Cannot retrieve value on rowdeleting in GridView - c#

I have a problem for retrieving values for deleting records.
I'm using OnRowDeleting in a gridview with templatefields, and I can't retrive record selected value for deleting, this is my grid:
<asp:GridView ID="gvw_Cli_Emp_EmpData" runat="server" AutoGenerateColumns="false"
CssClass="mGrid" PagerStyle-CssClass="pgr" Width="50%" AutoGenerateDeleteButton="True"
AlternatingRowStyle-CssClass="alt" Font-Size="Small" OnRowDeleting="Borrando">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href="#" onclick="window.open('Clientes_Empleados_Detalle.aspx?cliCod= <%#Eval("ClienteCodigo1").ToString()
+ "&EmpNom=" + Eval("Empleado1").ToString()
+ "&EmpCod=" + Eval("IdCliEmp").ToString()
+ "&idDepart=" + Eval("IdDepartamento").ToString()
+ "&Depart=" + Eval("Departamento1").ToString()
+ "&EmpNiv=" + Eval("NivelAcceso1").ToString()
%> ','PrintMe','height=500px,width=800px,scrollbars=1');">Editar</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CLIENTE">
<ItemTemplate>
<asp:Label ID="lbl_CliEmp_CliCod" runat="server" Text='<%# Eval("ClienteCodigo1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CODIGO">
<ItemTemplate>
<asp:Label ID="lbl_CliEmp_EmpId" runat="server" Text='<%# Eval("IdCliEmp") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EMPLEADO">
<ItemTemplate>
<asp:Label ID="lbl_CliEmp_EmpNom" runat="server" Text='<%# Eval("Empleado1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID DEP">
<ItemTemplate>
<asp:Label ID="lbl_CliEmp_DepId" runat="server" Text='<%# Eval("IdDepartamento") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DEPARTAMENTO">
<ItemTemplate>
<asp:Label ID="lbl_CliEmp_EmpDep" runat="server" Text='<%# Eval("Departamento1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NIVEL">
<ItemTemplate>
<asp:Label ID="lbl_CliEmp_EmpNiv" runat="server" Text='<%# Eval("NivelAcceso1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And for delete:
protected void Borrando(object sender, GridViewDeleteEventArgs e)
{
string cell = gvw_Cli_Emp_EmpData.Rows[e.RowIndex].Cells[0].Text; //this retuns me ""
int EmpCliCod = Convert.ToInt32(cell);
DialogResult dialogResult = MessageBox.Show(new Form { TopMost = true }, "Delete?", "Confirma", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
cliEmpBL.clientesEmpleados_SupEmpleado(EmpCliCod); //here execute deletion record from my datalayer
Page.ClientScript.RegisterStartupScript(this.GetType(), "AlertScript", "alert('Deleted!');", true);
}
else if (dialogResult == DialogResult.No)
{ }
}
So, as you can see returns me "".
I have tried resolve this, using:
System.Windows.Forms.Label EmpId = e.Item.FindControl("lbl_CliEmp_CliCod") as System.Windows.Forms.Label;
string val = EmpId.Text;
But same result, any idea?
please, I hope anyone can help me.
best regards

Try implementing below example, you will get id for selected row
<asp:LinkButton ID="lnkdelete" runat="server" CommandName="Delete" CommandArgument='<%#Eval("ClienteCodigo1")%>'>Delete</asp:LinkButton>
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int ID = Convert.ToInt32(e.CommandArgument);
//now perform the delete operation using ID value
}
}

Thanks Patrik your solution helped me.
<asp:GridView ID="gvw_CliEmp_EmpData" runat="server" AutoGenerateColumns="false"
CssClass="mGrid" PagerStyle-CssClass="pgr" Width="50%"
AlternatingRowStyle-CssClass="alt" Font-Size="Small"
OnRowCommand="gvw_CliEmp_EmpData_RowCommand" OnRowDeleting="gvw_CliEmp_EmpData_RowDeleting">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href="#" onclick="window.open('Clientes_Empleados_Detalle.aspx?cliCod= <%#Eval("ClienteCodigo1").ToString()
+ "&EmpNom=" + Eval("Empleado1").ToString()
+ "&EmpCod=" + Eval("IdCliEmp").ToString()
+ "&idDepart=" + Eval("IdDepartamento").ToString()
+ "&Depart=" + Eval("Departamento1").ToString()
+ "&EmpNiv=" + Eval("NivelAcceso1").ToString()
%> ','PrintMe','height=500px,width=800px,scrollbars=1');">Editar</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CLIENTE">
<ItemTemplate>
<asp:Label ID="lbl_CliEmp_CliCod" runat="server" Text='<%# Eval("ClienteCodigo1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CODIGO">
<ItemTemplate>
<asp:Label ID="lbl_CliEmp_EmpId" runat="server" Text='<%# Eval("IdCliEmp") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EMPLEADO">
<ItemTemplate>
<asp:Label ID="lbl_CliEmp_EmpNom" runat="server" Text='<%# Eval("Empleado1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID DEP">
<ItemTemplate>
<asp:Label ID="lbl_CliEmp_DepId" runat="server" Text='<%# Eval("IdDepartamento") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DEPARTAMENTO">
<ItemTemplate>
<asp:Label ID="lbl_CliEmp_EmpDep" runat="server" Text='<%# Eval("Departamento1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NIVEL">
<ItemTemplate>
<asp:Label ID="lbl_CliEmp_EmpNiv" runat="server" Text='<%# Eval("NivelAcceso1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server" CommandName="Delete"
CommandArgument='<%#Eval("IdCliEmp")%>'>Eliminar
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and code behind:
#region ==== BORRAR REGISTROS DEL INGRESO ====
protected void gvw_CliEmp_EmpData_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int EmpCliCod = Convert.ToInt32(e.CommandArgument);
DialogResult dialogResult = MessageBox.Show(new Form { TopMost = true }, "Eliminar?", "Confirmar", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
cliEmpBL.clientesEmpleados_SupEmpleado(EmpCliCod); //eliminar desde DL
Page.ClientScript.RegisterStartupScript(this.GetType(), "AlertScript", "alert('Eliminado!');", true);
}
else if (dialogResult == DialogResult.No)
{ }
gvw_CliEmp_EmpData.DataSource = null;
gvw_CliEmp_EmpData.DataBind();
gvw_CliEmp_EmpData.DataSource = cliEmpBL.clientes_Empleados_cons_EmpxCliente(lbl_CliEmp_CliCod.Text);
gvw_CliEmp_EmpData.DataBind();
}
}
protected void gvw_CliEmp_EmpData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{//this is because grid fired event RowDeleting which wasn't handled
}
#endregion

Related

Selecting a row from a gridview in asp.net?

I am trying to select a row from a gridview by using a select button link but when I click on the button, it doesn't call that C# method. So, I am wondering what could I be doing wrong. Please help me out. Thanks
form.aspx-
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added." Height="72px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Width="723px">
<Columns>
<asp:TemplateField HeaderText="Title" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lbltitle" runat="server" Text='<%# Eval("Title") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txttitle" runat="server" Text='<%# Eval("Title") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="150px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subtitle" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblsubtitle" runat="server" Text='<%# Eval("Subtitle") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtsubtitle" runat="server" Text='<%# Eval("Subtitle") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="150px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Content" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblContent" runat="server" Text='<%# Eval("Content") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtContent" runat="server" Text='<%# Eval("Content") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="150px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" Text="SELECT" CommandName="MyCustomCommand" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
NewsFeedDemo.cs
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("MyCustomCommand"))
{
GridViewRow clickedRow = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;
Label lblID = (Label)clickedRow.FindControl("lblID");
}
}
please use this OnRowCommand="GridView1_RowCommand"
<asp:LinkButton ID="lnkbedit" runat="server" CommandName="MyCustomCommand" CommandArgument='<%#Eval("id") %>'>Edit</asp:LinkButton>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
}
}
You use the Method GridView1_RowCommand, but it is not bound to GridView1. You need to add OnRowCommand to the GridView.
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">

How to get data from TextBox in gridview?

This is the code where I have problem, I don't have any problems in the previous page but this is happening in this and following page.
<asp:GridView ID="gv_employee" runat="server" ShowHeaderWhenEmpty="true" AutoGenerateColumns="false" OnRowEditing="Edit" OnRowCancelingEdit="CancelEdit" OnRowUpdating="Update" Width="1070px"
AlternatingRowStyle-BackColor="WhiteSmoke" HeaderStyle-BackColor="#C5D9F1">
<Columns>
<asp:TemplateField HeaderText="S.No" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="60px">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee Code" ItemStyle-Width="160px">
<ItemTemplate>
<asp:Label ID="lbl_gv_empcode" runat="server" Text='<%#Eval("employeecode")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee Name">
<ItemTemplate>
<asp:Label ID="lbl_gv_empname" runat="server" Text='<%#Eval("employeename") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_empname" runat="server" Text='<%#Eval("employeename") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address1">
<ItemTemplate>
<asp:Label ID="lbl_gv_addr1" runat="server" Text='<%#Eval("address1") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_addr1" runat="server" Text='<%#Eval("address1") %>' />
</EditItemTemplate>
</asp:TemplateField>
<%-- <asp:TemplateField HeaderText="Address2">
<ItemTemplate>
<asp:Label ID="lbl_gv_addr2" runat="server" Text='<%#Eval("address2") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_addr2" runat="server" Text='<%#Eval("address2") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address3">
<ItemTemplate>
<asp:Label ID="lbl_gv_addr3" runat="server" Text='<%#Eval("address3") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_addr3" runat="server" Text='<%#Eval("address3") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lbl_gv_city" runat="server" Text='<%#Eval("city")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_city" runat="server" Text='<%#Eval("city")%>' />
</EditItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="lbl_gv_email" runat="server" Text='<%#Eval("email") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_email" runat="server" Text='<%#Eval("email") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phone">
<ItemTemplate>
<asp:Label ID="lbl_gv_phone" runat="server" Text='<%#Eval("phone") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_phone" runat="server" Text='<%#Eval("phone") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btndel" runat="server" Text="Delete" CommandArgument='<%#Eval("employeecode") %>'
OnClientClick="return confirm('Do you want to delete?')" OnClick="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is my asp code
public void BindData()
{
string ls_sqlcmd = "select * from employeemst";
SqlCommand cmd = new SqlCommand(ls_sqlcmd);
gv_employee.DataSource = add.GetData(cmd);
gv_employee.DataBind();
}
protected void Delete(object sender, EventArgs e)
{
LinkButton lnk_deletestate = (LinkButton)sender;
string str = "delete from employeemst where employeecode='" + lnk_deletestate.CommandArgument + "'";
add.adddata(str);
BindData();
}
protected void Update(object sender, GridViewUpdateEventArgs e)
{
String emplname = ((TextBox)gv_employee.Rows[e.RowIndex].FindControl("txt_gv_empname")).Text;
String Addr1= ((TextBox)gv_employee.Rows[e.RowIndex].FindControl("txt_gv_addr1")).Text;
String addr2 = ((TextBox)gv_employee.Rows[e.RowIndex].FindControl("txt_gv_addr2")).Text;
String addr3 = ((TextBox)gv_employee.Rows[e.RowIndex].FindControl("txt_gv_addr3")).Text;
gv_employee.EditIndex = -1;
BindData();
}
protected void Edit(object sender, GridViewEditEventArgs e)
{
gv_employee.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gv_employee.EditIndex = -1;
BindData();
}
}
This is my aspx.cs code.
My problem is that I am unable to get data from textbox which is in gridview <EditItemTemplate></EditItemTemplate>
I don't get updated value in string emplname, addr1, addr2,addr3.
your issue is you are binding grid view in each postback, move your BindData method inside the IsPostBack check, then you can get the data
protected void Page_Load(object sender, EventArgs e)
{
Session["page"] = "Employee";
if (!IsPostBack)
{
BindData();
DataTable dt = add.retrive("select * from statemst");
for (int i = 0; i < dt.Rows.Count; i++)
{
ListItem item = new ListItem();
item.Text = dt.Rows[i]["statedesc"].ToString();
item.Value = dt.Rows[i]["statecode"].ToString();
ddl_state.Items.Add(item);
}
}
}

Understanding Gridview RowCommand

I've coded a gridview that doesn't fire when I click the edit button and I found an older question that addresses my issue by just using e.CommandName with if statements under the RowCommand method. I'm trying to figure out how to implement it with my code.
My question is, how do I use e.RowIndex during update to find my controls and reference those now? Also, I've tried calling my old Update method but it won't let me use sender and e as parameters because GridviewCommandEventArgs is different from GridViewEventUpdateArgs. I'm pretty lost, any help would be appreciated in straightening this out.
C#:
void RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Edit")
{
}
if (e.CommandName == "Update")
{
UpdateCustomer(sender, e);
string nFirstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtFirstName")).Text;
string nLastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLastName")).Text;
string nEmergency = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmergency")).Text;
string nCell = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCell")).Text;
string nAge = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAge")).Text;
string nActivityCard = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtActivityCard")).Text;
string nBoat = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtBoat")).Text;
string nInitials = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtInitials")).Text;
string nGroup = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtGroup")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Person set FirstName=#FirstName, LastName=#LastName, " +
"Emergency#=#Emergency, Cell#=#Cell, Age=#Age, ActivityCard=#ActivityCard, Initials=#Initials, CraftType=#Boat, Group#=#Group " +
"where Person.PersonID=#Pid;" +
"SELECT Person.PersonID, Person.FirstName AS FirstName, Person.LastName AS LastName, Person.Emergency# AS Emergency#, Person.Cell# AS Cell#, Person.Age AS Age, " +
"Person.ActivityCard AS ActivityCard, Person.CraftType AS CraftType, Person.Initials AS Initials, Person.Group# AS Group# " +
"FROM Person INNER JOIN " +
"TripSchedule ON Person.PersonID = TripSchedule.PersonID where TripSchedule.Date = #Date and " +
"TripSchedule.Time = #Time and TripSchedule.TripType = #Type order by Person.Group#;";
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = nFirstName;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = nLastName;
cmd.Parameters.Add("#Emergency", SqlDbType.NChar).Value = nEmergency;
cmd.Parameters.Add("#Cell", SqlDbType.NChar).Value = nCell;
cmd.Parameters.Add("#Age", SqlDbType.NChar).Value = nAge;
cmd.Parameters.Add("#ActivityCard", SqlDbType.NChar).Value = nActivityCard;
cmd.Parameters.Add("#Initials", SqlDbType.NChar).Value = nInitials;
cmd.Parameters.Add("#Boat", SqlDbType.VarChar).Value = nBoat;
cmd.Parameters.Add("#Group", SqlDbType.VarChar).Value = nGroup;
cmd.Parameters.AddWithValue("#Date", TextBox1.Text);
cmd.Parameters.AddWithValue("#Time", ddlTripTime.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Type", ddlTripType.SelectedItem.ToString());
long personID = long.Parse(GridView1.DataKeys[e.RowIndex].Values["PersonID"].ToString());
cmd.Parameters.AddWithValue("#Pid", personID);
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
if (e.CommandName == "Cancel")
{
}
}
ASP.NET:
<div id="dvGrid" style="padding: 0px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" DataKeyNames="PersonID" runat="server" AutoGenerateColumns="False"
Font-Names="Arial" Font-Size="10pt" AlternatingRowStyle-BackColor="blue" HeaderStyle-BackColor="aqua"
ShowFooter="true" OnRowEditing="EditCustomer" OnRowUpdating="UpdateCustomer"
OnRowCancelingEdit="CancelEdit" ShowHeaderWhenEmpty="true" Height="95px">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Height="20px" Text='<%# Eval("FirstName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width = "60px" />
<FooterTemplate>
<asp:TextBox ID="txtFirstName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%#Bind("LastName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLastName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAge" Width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Activity Card">
<ItemTemplate>
<asp:Label ID="lblActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtActivityCard" Width="50px" MaxLength="7" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cell Phone">
<ItemTemplate>
<asp:Label ID="lblCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCell" Width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emergency Phone">
<ItemTemplate>
<asp:Label ID="lblEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmergency" width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Boat Type">
<ItemTemplate>
<asp:Label ID="lblBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBoat" Width="80px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Initials">
<ItemTemplate>
<asp:Label ID="lblInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtInitials" width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group #">
<ItemTemplate>
<asp:Label ID="lblGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtGroup" MaxLength="2" Width="20px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server" CommandArgument='<%# Eval("PersonID")%>'
OnClientClick="return confirm('Are you sure you want to delete?')" Text="Delete"
OnClick="DeleteCustomer"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Submit" OnClick="AddNewCustomer" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can pass RowIndex as CommandArgument for your LinkButtons.
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update" CommandArgument='<%# Container.DataItemIndex %>'>Update</asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel" CommandArgument='<%# Container.DataItemIndex %>'>Cancel</asp:LinkButton>
</EditItemTemplate>
Which can be access from code behind. Using rowindex you can get hold of the current row and find any controls using FindControl
void RowCommand(Object sender, GridViewCommandEventArgs e)
{
int rowindex = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Update")
{
....
}
if (e.CommandName == "Cancel")
{
....
}
}
e.CommandArgument will contain the index of the row clicked, so you can access the relevant controls via
int index = Convert.ToInt32(e.CommandArgument);
GridView1.Rows[index].Controls[x];

Cannot display Sum of column in Gridview

I am not able to display the Value in a lable in footer. Below is the code
Aspx
<asp:GridView ID="gvallAccount" runat="server" AutoGenerateColumns="False" Width="589px"
OnRowDataBound="gvallAccount_RowDataBound" OnRowCommand="gvallAccount_RowCommand">
<Columns>
<asp:TemplateField Visible="False">
<ItemTemplate>
<asp:Label ID="lblAccountID" runat="server" Text='<%# Bind("ProductAccountID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" Visible="True">
<ItemTemplate>
<asp:Label ID="lblProductName" runat="server" Text='<%# Bind("ProductName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Account Number" Visible="True">
<ItemTemplate>
<asp:LinkButton ID="lnkAccCode" runat="server" Text='<%# Bind("ProductAccountCode") %>'
OnClick="lnkAccCode_Click" CommandName="gotoLink"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Account Value(KES)" Visible="True">
<ItemTemplate>
<asp:Label ID="lblBalance" runat="server" Text='<%# Bind("BalanceToDate") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C# Code
protected void gvallAccount_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
decimal rowTotal = Convert.ToDecimal
(DataBinder.Eval(e.Row.DataItem, "BalanceToDate"));
grdTotal = grdTotal + rowTotal;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lblTotal = (Label)e.Row.FindControl("lblTotal");
lblTotal.Text = grdTotal.ToString();
}
}
catch (Exception Ex)
{
logger.Error("gvallAccount_RowDataBound : " + Ex.Message);
}
}
You need to have ShowFooter="True" attribute in the GridView tag.
<asp:GridView ID="gvallAccount" runat="server" AutoGenerateColumns="False" Width="589px"
OnRowDataBound="gvallAccount_RowDataBound" OnRowCommand="gvallAccount_RowCommand" ShowFooter="True">

Custom paging with gridview and linqdatasource

I have a problem which in theory should be very simple but i spent 3 hours now not being able to figure it out. I have a gridview and lingdatasource and i try to implement custom paging. No matter what i do i seem to be stuck with a pagesize of 25! Code below
Thanks!
aspx page
<asp:GridView ID="gvCustomerList" SkinID="StandardGridView" AutoGenerateColumns="false" DataSourceID="LqCustomerSource"
AllowPaging="false" AllowSorting="false" PageSize="50" runat="server" OnSorting="gvCustomerList_OnSorting"
OnRowCommand="gvSupplierCustomerList_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Customer Id" HeaderStyle-HorizontalAlign="Left" SortExpression="CustomerId">
<ItemTemplate>
<asp:Label ID="lblCustomerId" runat="server" Text='<%# ((ITB.DAL.LinqObjects.Customer)Container.DataItem).CustomerId %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name" HeaderStyle-HorizontalAlign="Left" SortExpression="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Text='<%# ((ITB.DAL.LinqObjects.Customer)Container.DataItem).FirstName %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" HeaderStyle-HorizontalAlign="Left" SortExpression="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%# ((ITB.DAL.LinqObjects.Customer)Container.DataItem).LastName %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Details" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:HyperLink ID="lnkDetails" Text="Details" NavigateUrl='<%# "~/BackOffice/Customers/CustomerDetails.aspx?CustomerId=" + ((ITB.DAL.LinqObjects.Customer)Container.DataItem).CustomerId %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ask" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:HyperLink ID="lnkAsk" Text="Ask" NavigateUrl='<%# "~/BackOffice/Customers/Ask.aspx?CustomerId=" + ((ITB.DAL.LinqObjects.Customer)Container.DataItem).CustomerId %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:LinqDataSource ID="LqCustomerSource" AutoPage="false" runat="server"
OnSelecting="LqCustomerSource_Selecting" AutoSort="False">
</asp:LinqDataSource>
code behind
protected void LqCustomerSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
try
{
CustomerDataManager manager = new CustomerDataManager();
string searchName = "";// txtCustomerName.Text.Trim();
int count = 0;
List<Customer> customerList = manager.GetSelectedCustomers(gvCustomerList.PageIndex * 50, 50, searchName, SortExpression, SortDirectionForCustomers, out count);
//List<CustomerInsuranceInfo> infoList = manager.GetCustomerInsuranceDataFromList(customerList);
lblRows.Text = count.ToString();
e.Arguments.StartRowIndex = 0;
e.Arguments.MaximumRows = 50;
e.Arguments.TotalRowCount = count;
if (customerList == null)
e.Cancel = true;
else
e.Result = customerList;
}
catch (Exception ex)
{
ApplicationLogBO.Log(ex);
// Alert(WebsiteUtil.StandardErrorMessage);
e.Cancel = true;
}
}
Ok, it looks like you need to set it in the code behind in LqCustomerSource_Selecting
gvCustomerList.PageSize = 50

Categories

Resources