Jump to content
Sign in to follow this  
999ANDRE999

[Resolvido] Gridview botão delete

Recommended Posts

999ANDRE999

boas pessoal,

Estou com um problema no desenvolvimento de um portal. Tenho uma gridview que apresenta todos os dados que tenho numa base de daddos Npgsql, e nessa gridview coloquei as opções "auto generate delete button" e "auto generate update button" a true. Só que agora não sei como programar os botoes de maneira a eliminar a linha da gridview e consequentemente da base de dados.

O meu codigo para apresentar os dados na gridview da base de dados é: (está funcional)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Npgsql;//database
using System.Data;//database
public partial class Account_Login : System.Web.UI.Page
{
// mostra a tabela inteira
protected void Page_Load(object sender, EventArgs e)
{
 DataBase.Conecta();
 Npgsql.NpgsqlCommand comm = new Npgsql.NpgsqlCommand();
 comm.CommandText = " SELECT * FROM status_project ";
 comm.Connection = DataBase.Conn;
 Npgsql.NpgsqlDataAdapter myDataAdapter = new Npgsql.NpgsqlDataAdapter();
 myDataAdapter.SelectCommand = comm;
 DataSet myDataSet = new DataSet();
 int project_view = myDataAdapter.Fill(myDataSet);
 Panel_gridview_project.Visible = true;
 GridView_project.DataSource = myDataSet;
 GridView_project.DataBind();
}
}

Para programar o botão eliminar tentei este codigo mas sem sucesso:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
 DataBase.Conecta();
 Npgsql.NpgsqlCommand comm = new Npgsql.NpgsqlCommand();
 comm.Connection = DataBase.Conn;

 int ID = int.Parse(GridView_project.Rows[e.RowIndex].FindControl("ID").ToString());
 string delete_command = "DELETE FROM status_project WHERE ID = " + ID;
 comm.CommandText = delete_command;
}

No ficheiro asp a gridview está da seguinte forma:

<asp:GridView ID="GridView_project" runat="server" HorizontalAlign="Center" BackColor="White"
	 BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black"
	 AutoGenerateColumns="False" AutoGenerateDeleteButton="True"
	 AutoGenerateEditButton="True" GridLines="Vertical" ShowFooter="True"
	 AllowPaging="True">
	 <AlternatingRowStyle BackColor="White" />
	 <Columns>
		 <asp:TemplateField HeaderText="Road map of new products">
			 <%--<EditItemTemplate>
				 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
			 </EditItemTemplate>--%>
			 <ItemTemplate>
				 <asp:Label ID="Label1" Text='<%# Eval("project") %>'
					 runat="server"></asp:Label>
			 </ItemTemplate>
		 </asp:TemplateField>
		 <asp:TemplateField HeaderText="Time scheduling" InsertVisible="False">
			 <%--<EditItemTemplate>
				 <asp:CheckBox ID="CheckBox1" runat="server" />
			 </EditItemTemplate>--%>
			 <ItemTemplate>
				 <asp:Label ID="Label1" runat="server" Text='<%# Eval("Time_Scheduling") %>'></asp:Label>
			 </ItemTemplate>
		 </asp:TemplateField>
		 <asp:TemplateField HeaderText="B-Sample (Plant)/Part list/Technical design">
			 <ItemTemplate>
				 <asp:Label ID="Label1" runat="server" Text='<%# Eval("B_sample") %>'></asp:Label>
			 </ItemTemplate>
		 </asp:TemplateField>
		 <asp:TemplateField HeaderText="Aproval of C-Samples of parts ?">
			 <ItemTemplate>
				 <asp:Label ID="Label1" runat="server"
					 Text='<%# Eval("Aproval_of_c_samples_of_parts") %>'></asp:Label>
			 </ItemTemplate>
		 </asp:TemplateField>
		 <asp:TemplateField HeaderText="C-Sample (Plant)">
			 <ItemTemplate>
				 <asp:Label ID="Label1" runat="server" Text='<%# Eval("C_Sample") %>'></asp:Label>
			 </ItemTemplate>
		 </asp:TemplateField>
		 <asp:TemplateField HeaderText="Approval of C-Sample">
			 <ItemTemplate>
				 <asp:Label ID="Label1" runat="server" Text='<%# Eval("Aproval_of_c_sample") %>'></asp:Label>
			 </ItemTemplate>
		 </asp:TemplateField>
		 <asp:TemplateField HeaderText="Process definition "MAE + EWAK"">
			 <ItemTemplate>
				 <asp:Label ID="Label1" runat="server" Text='<%# Eval("Process_definition") %>'></asp:Label>
			 </ItemTemplate>
		 </asp:TemplateField>
		 <asp:TemplateField HeaderText="Process implementation">
			 <ItemTemplate>
				 <asp:Label ID="Label1" runat="server" Text='<%# Eval("Process_Implement") %>'></asp:Label>
			 </ItemTemplate>
		 </asp:TemplateField>
		 <asp:TemplateField HeaderText="D-Sample (Plant)">
			 <ItemTemplate>
				 <asp:Label ID="Label1" runat="server" Text='<%# Eval("D_sample") %>'></asp:Label>
			 </ItemTemplate>
		 </asp:TemplateField>
		 <asp:TemplateField HeaderText="Aproval of D-Sample">
			 <ItemTemplate>
				 <asp:Label ID="Label1" runat="server"
					 Text='<%# Eval("Approval_of_D_Sample") %>'></asp:Label>
			 </ItemTemplate>
		 </asp:TemplateField>
		 <asp:TemplateField HeaderText="0 series/SOP">
			 <ItemTemplate>
				 <asp:Label ID="Label1" runat="server" Text='<%# Eval("Series_SOP") %>'></asp:Label>
			 </ItemTemplate>
		 </asp:TemplateField>
		 <asp:TemplateField HeaderText="Delivering to costumer">
			 <ItemTemplate>
				 <asp:Label ID="Label1" runat="server"
					 Text='<%# Eval("Delivering_to_costumer") %>'></asp:Label>
			 </ItemTemplate>
		 </asp:TemplateField>
	 </Columns>
	 <FooterStyle BackColor="#565656" />
	 <HeaderStyle BackColor="#565656" ForeColor="White" HorizontalAlign="Center"
		 VerticalAlign="Middle" />
	 <PagerSettings Mode="NextPrevious" />
	 <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Center" />
	 <RowStyle BackColor="White" />
	 <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
	 <SortedAscendingCellStyle BackColor="#FBFBF2" />
	 <SortedAscendingHeaderStyle BackColor="#848384" />
	 <SortedDescendingCellStyle BackColor="#EAEAD3" />
	 <SortedDescendingHeaderStyle BackColor="#575357" />
 </asp:GridView>

Alguem me consegue ajudar na maneira de como configurar os botões de delete e update da gridview?

Share this post


Link to post
Share on other sites
999ANDRE999

Já consegui colocar a funcionar :P

Para quem necessitar:

protected void gridview_RowDeleting(object sender, GridViewDeleteEventArgs e)
   {
    GridView_project.RowDeleting += new GridViewDeleteEventHandler(gridview_RowDeleting);
    DataBase.Conecta();
    Npgsql.NpgsqlCommand comm = new Npgsql.NpgsqlCommand();
    comm.Connection = DataBase.Conn;
    string id = GridView_project.DataKeys[e.RowIndex].Value.ToString();
    comm.CommandText = "DELETE FROM status_project WHERE project='" + id + "'";
    comm.ExecuteNonQuery();
    DataBase.Desconecta();
    refresh_table(); 
   }

Agora precisava de colocar uma espécie de popup para quando alguem clicar em "delete", aparecer uma janela a perguntar se deseja mesmo eliminar, e clicando sim apaga, clicando não, não faz nada. Mas não estou a conseguir. Alguem pode ajudar?

Edited by 999ANDRE999

Share this post


Link to post
Share on other sites
N3lson
DialogResult xx = MessageBox.Show("deseja eliminar " + id + "?", "titulo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

if(xx == DialogResult.Yes)
{
//Apaga
}

Edited by N3lson
  • Vote 1

You can't do it, kid. But don't worry, my boy. You're not the only one. No one else can do it.

Share this post


Link to post
Share on other sites
999ANDRE999

DialogResult xx = MessageBox.Show("deseja eliminar " + id + "?", "titulo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

if(xx == DialogResult.Yes)
{
//Apaga
}

Obrigado Nelson.

Ao implementar dá erros no DialogResult (The name ' DialogResult ' does not exist in the current context), MessageBox (The name 'MessageBox ' does not exist in the current context), MessageBoxButtons (The name 'MessageBoxButtons ' does not exist in the current context) e MessageBoxIcon (The name 'MessageBoxIcon ' does not exist in the current context).

Consegues ajudar?

protected void gridview_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
 GridView_project.RowDeleting += new GridViewDeleteEventHandler(gridview_RowDeleting);
 DataBase.Conecta();
 Npgsql.NpgsqlCommand comm = new Npgsql.NpgsqlCommand();
 comm.Connection = DataBase.Conn;
 string id = GridView_project.DataKeys[e.RowIndex].Value.ToString();
 DialogResult xx = MessageBox.Show("deseja eliminar " + id + "?", "titulo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
 if (xx == DialogResult.Yes)
 {
	 comm.CommandText = "DELETE FROM status_project WHERE project='" + id + "'";
	 comm.ExecuteNonQuery();
 }
 DataBase.Desconecta();
 refresh_table();
}

Edited by apocsantos

Share this post


Link to post
Share on other sites
N3lson

Faz o reference using System.Windows.Forms

ou coloca

System.Windows.Forms.DialogResult , etc...

https://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox%28v=vs.110%29.aspx

Desculpa não tinha reparado que estavas a usar asp

Vais ter de usar Javascript para isso

Edited by N3lson

You can't do it, kid. But don't worry, my boy. You're not the only one. No one else can do it.

Share this post


Link to post
Share on other sites
999ANDRE999

Faz o reference using System.Windows.Forms

ou coloca

System.Windows.Forms.DialogResult , etc...

https://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox%28v=vs.110%29.aspx

Desculpa não tinha reparado que estavas a usar asp

Vais ter de usar Javascript para isso

E como consigo algo idêntico em asp? :confused:

Encontrei este código que abre a janela de confirmação, mas depois não sei configurar no código os botões dessa janela:

ScriptManager.RegisterStartupScript(this, this.GetType(), "CallConfirmBox", "CallConfirmBox();", true);

Edited by 999ANDRE999

Share this post


Link to post
Share on other sites
999ANDRE999

http://www.aspneto.com/how-to-show-confirm-message-box-from-code-behind-asp-net.html

Tomando o exemplo no teu caso no lugar de btlcall_click coloca gridview_RowDeleting

Tb não estou muito á vontade com o asp.net mas , o processo é esse

O problema é que não tenho um botão fisico. É o botão AutoGenerateDeleteButon das propriedades da grid view. Com essa opção ativa, aparece na gridview em cada linha um botão delete.

Daí a minha maior dificuldade.

u4U4G.jpg

Edited by 999ANDRE999

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.