Save state of checkbox in gridview when changed to edite mode - c#

When I am clicking on imagebutton in my gridview, some cells become editable
but, it loses all the checkboxs values that in the gridview.
Is there a way to save these values?
I made a function who gets the checkboxes values from my xml but, when I call the function inside the command era it's not working.
When I call that function in other imagebutton command era in the gridview which doesn't make some cells editable, that works and the function runs and the values from the xml shown on the checkboxes.
Thanks
<asp:GridView style="direction:rtl; " ShowHeader="False" BorderColor="White" BorderWidth="2px" HeaderStyle-BackColor="#926c3f" HeaderStyle-Font-Bold="false" RowStyle-BorderColor="White" ID="GridView1" runat="server" DataSourceID="XmlDataSource1" AutoGenerateColumns="False" CssClass="auto-style100" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowCommand="GridView1_SelectedIndexChanged" OnRowCancelingEdit="GridView1_SelectedIndexChanged" OnRowEditing="GridView1_SelectedIndexChanged" AllowSorting="True">
<Columns>
<asp:TemplateField HeaderText=" שם משחק" ItemStyle-Width="200px" >
<ItemTemplate >
<asp:Label ID="NameLabel" runat="server" Text='<%#Server.UrlDecode(XPathBinder.Eval(Container.DataItem, "gameName").ToString())%>'> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="nameTB" runat="server" Text='<%#Server.UrlDecode(XPathBinder.Eval(Container.DataItem, "gameName").ToString())%>'> </asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="קוד משחק" ItemStyle-Width="85px">
<ItemTemplate>
<asp:Label ID="codeLabel" runat="server" Text='<%#Server.UrlDecode(XPathBinder.Eval(Container.DataItem, "gameCode").ToString())%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="הגדרות" ItemStyle-Width="70px">
<EditItemTemplate>
<asp:ImageButton ID="cancelImageButton" runat="server" ImageUrl="~/images/cancel.png" CommandName="cancel" OnClientClick="showWhoIsPublish" />
<asp:ImageButton ID="approveImageButton" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' runat="server" ImageUrl="~/images/approve.png" CommandName="approve" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="settingsImageButton" runat="server" CssClass="buttons" ImageUrl="~/images/אייקון הגדרות.png" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' CommandName="edit" OnClientClick="showWhoIsPublish" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="עריכה" ItemStyle-Width="70px" >
<ItemTemplate>
<asp:ImageButton ID="editImageButton" runat="server" CssClass="buttons" ImageUrl="~/images/אייקון עריכה.png" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' CommandName="editQ" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="מחיקה" ItemStyle-Width="70px">
<ItemTemplate>
<asp:ImageButton ID="deleteImageButton" CssClass="buttons" OnClick="doDelete_Click" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' runat="server" ImageUrl="~/images/אייקון מחיקה.png" CommandName="deleteRow" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" הגבלת זמן" ItemStyle-Width="90px" >
<EditItemTemplate>
<asp:DropDownList ID="DropDownListT" AppendDataBoundItems="True" runat="server" >
<asp:ListItem> 10 שניות</asp:ListItem>
<asp:ListItem> 20 שניות</asp:ListItem>
<asp:ListItem> 30 שניות</asp:ListItem>
<asp:ListItem> 40 שניות</asp:ListItem>
<asp:ListItem> 50 שניות</asp:ListItem>
<asp:ListItem> 60 שניות</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate >
<asp:Label ID="Time" runat="server" Text='<%#Server.UrlDecode(XPathBinder.Eval(Container.DataItem, "time").ToString())%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="פרסום" ItemStyle-Width="60px">
<ItemTemplate>
<asp:CheckBox runat="server" ID="Checkbox1" CssClass="buttons1" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' AutoPostBack="True" OnCheckedChanged="PublishYesNo_CheckedChanged" ViewStateMode="Inherit" EnableViewState="True" Checked="False" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void GridView1_SelectedIndexChanged(object sender, GridViewCommandEventArgs e)
{
showWhoIsPublish();
ImageButton i = (ImageButton)e.CommandSource;
// אנו מושכים את האי די של הפריט באמצעות מאפיין לא שמור במערכת שהוספנו באופן ידני לכפתור-תמונה
string theId = i.Attributes["theItemId"];
Session["theId"] = theId;
XmlDocument xmlDoc = XmlDataSource1.GetXmlDocument();
switch (e.CommandName)
{
//אם נלחץ על כפתור מחיקה יקרא לפונקציה של מחיקה
case "deleteRow":
popOfDelete.Visible = true;
string deleteId = (string)Session["theId"];
string theGameNameDelete = Server.UrlDecode(xmlDoc.SelectSingleNode("//game[#id='" + (string)Session["theId"] + "']/gameName").InnerXml);
nameOfGameDelete.Text = "'" + theGameNameDelete + "' " + "?";
showWhoIsPublish();
break;
case "editQ":
string editId = (string)Session["theId"];
string theGameNameEdit = xmlDoc.SelectSingleNode("//game[#id='" + (string)Session["theId"] + "']/gameName").InnerXml;
Session["nameOfEdit"] = theGameNameEdit;
Response.Redirect("Default3.aspx");
break;
case "edit":
addNameTB.Text = "jg";
showWhoIsPublish();
break;
case "cancel":
GridView1.DataBind();
showWhoIsPublish();
break;
case "approve":
GridViewRow gvRow = (GridViewRow)(i.Parent.Parent);
string ApproveId = (string)Session["theId"];
int index = gvRow.RowIndex;
string myName = ((TextBox)GridView1.Rows[index].FindControl("nameTB")).Text;
string myValue = ((DropDownList)GridView1.Rows[index].FindControl("DropDownListT")).Text;
xmlDoc.SelectSingleNode("//game[#id='" + ApproveId + "']/gameName").InnerText = Server.UrlEncode(myName);
xmlDoc.SelectSingleNode("//game[#id='" + ApproveId + "']/time").InnerText = Server.UrlEncode(myValue);
XmlDataSource1.Save();
// יציאה ממצב של עריכה
GridView1.EditIndex = -1;
// ריענון הגריד ויו
GridView1.DataBind();
showWhoIsPublish();
break;
}
}
protected void showWhoIsPublish()
{
//סימון מה שמפורסם
XmlDocument xmlDoc = XmlDataSource1.GetXmlDocument();
XmlNodeList myListPublish = xmlDoc.SelectNodes("/games/user[#id='" + Session["id"] + "']/game/#isPublish");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkItem = (CheckBox)GridView1.Rows[i].FindControl("Checkbox1");
if (myListPublish.Item(i).InnerXml == "yes")
{
chkItem.Checked = true;
}
else
{
chkItem.Checked = false;
}
}
}

Related

Cannot retrieve value on rowdeleting in GridView

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

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);
}
}
}

Edit Command in Gridview

I am extracting data from database in gridview, where I have given a link button "Edit" for editing the data of that row. However while editing , one of the columns(YEAR) of my gridview becomes a dropdown list. While fetching the data from database, the Column "Year" consists of label and in edit mode it gets changed to dropdownlist. Moreover I added a condition to make the link buttons appear/disappear based on the value of the Label "Year". When I edit the particular row it throws an error because as soon as edit command is called it converts the column into dropdownlist however the row_databound searches for label. It shows "Object not set to an instance....." PLease help
Aspx
<asp:GridView ID="gv1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataSourceID="SqlDataSource2" OnRowDataBound="gv1_RowDataBound" OnRowUpdating="gv1_RowUpdating" DataKeyNames="tid" CssClass="auto-style1" Width="694px">
<Columns>
<asp:TemplateField HeaderText="Sr No">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="tid" SortExpression="tid" Visible="false">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("tid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" SortExpression="title">
<EditItemTemplate>
<asp:TextBox ID="txtTitle1" runat="server" Text='<%# Bind("title") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblTitle" runat="server" Text='<%# Bind("title") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Category" SortExpression="category">
<ItemTemplate>
<asp:Label ID="lblCategory" runat="server" Text='<%# Bind("category") %>'></asp:Label></ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="rbtnlist" runat="server"><asp:ListItem Text="Soft Skills"></asp:ListItem><asp:ListItem Text="Technical Skills"></asp:ListItem></asp:RadioButtonList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Announced at" SortExpression="dt">
<ItemTemplate>
<asp:Label ID="lblDt" runat="server" Text='<%# Bind("dt", "{0:dd/MMM/yyyy HH:mm tt}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Year" SortExpression="year">
<EditItemTemplate>
<asp:DropDownList ID="ddlyr" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblyr" runat="server" Text='<%# Bind("year") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User Id" SortExpression="userid">
<ItemTemplate>
<asp:Label ID="lblUid" runat="server" Text='<%# Bind("userid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="btndel" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" OnClientClick="return isConfirm()" Visible="false"></asp:LinkButton>
<%--<asp:LinkButton ID="btnmail" runat="server" CausesValidation="False" OnClientClick="return isConfirm()" Text="Send Mail" Visible="false"></asp:LinkButton>--%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="btnupdte" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="btncncl" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="btnedit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" Visible="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="btnmail" runat="server" CausesValidation="False" OnClientClick="return isConfirm()" Text="Send Mail" Visible="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle ForeColor="#003399" HorizontalAlign="Left" BackColor="#99CCCC" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
c#
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbly = (Label)e.Row.FindControl("lblyr");
if (lbly.Text == DateTime.Now.Year.ToString() || lbly.Text == ((DateTime.Now.Year)-1).ToString())
{
LinkButton btedt = (LinkButton)e.Row.FindControl("btnedit");
LinkButton btdel = (LinkButton)e.Row.FindControl("btndel");
LinkButton btsm = (LinkButton)e.Row.FindControl("btnmail");
btdel.Visible = true;
btedt.Visible = true;
btsm.Visible = true;
}
if ((e.Row.RowState & DataControlRowState.Edit) > 0) {
RadioButtonList rbtnlist = (RadioButtonList)e.Row.FindControl("rbtnlist");
DropDownList ddlist = (DropDownList)e.Row.FindControl("ddlyr");
for (int i = (DateTime.Now.Year); i >= ((DateTime.Now.Year)-1) ; i--)
{
ddlist.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
ddlist.DataBind();
rbtnlist.DataBind();
}
}
}
I am assuming that you are binding your grid with a DataTable with colum name "Year". Try below code where dt refers to your Datatable:
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int rowno = e.Row.DataItemIndex;
//Suppose dt is DataTable to which you are binding your grid
//and year is the column name within this datatable
string year = Convert.ToString(dt.Rows[e.Row.DataItemIndex]["year"]);
if (year == DateTime.Now.Year.ToString() || year == ((DateTime.Now.Year) - 1).ToString())
{
LinkButton btedt = (LinkButton)e.Row.FindControl("btnedit");
LinkButton btdel = (LinkButton)e.Row.FindControl("btndel");
LinkButton btsm = (LinkButton)e.Row.FindControl("btnmail");
btdel.Visible = true;
btedt.Visible = true;
btsm.Visible = true;
}
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
RadioButtonList rbtnlist = (RadioButtonList)e.Row.FindControl("rbtnlist");
DropDownList ddlist = (DropDownList)e.Row.FindControl("ddlyr");
for (int i = (DateTime.Now.Year); i >= ((DateTime.Now.Year) - 1); i--)
{
ddlist.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
ddlist.DataBind();
rbtnlist.DataBind();
}
}

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