Add summary row in Gridview for one column - asp.net

I have this GridView, and I want to add in the footer summation of PremiseScore score (third column).
How I can do this?
<asp:BoundField DataField="PremiseUno" HeaderText='<%$ Resources:Language, grdPremiseUno %>' ReadOnly="True" SortExpression="PremiseUno" >
<HeaderStyle CssClass="gHeaderStyle" />
<ItemStyle CssClass="gControlStyle" />
</asp:BoundField>
<asp:BoundField DataField="PremiseName" HeaderText='<%$ Resources:Language, grdPremisesName %>'
ReadOnly="True" SortExpression="grdPremisesName" >
<HeaderStyle CssClass="gHeaderStyle" />
<ItemStyle CssClass="gControlStyle" />
</asp:BoundField>
<asp:BoundField DataField="PremiseScore" HeaderText='<%$ Resources:Language, grdPremiseScore %>' ReadOnly="True" SortExpression="PremiseScore" >
<HeaderStyle CssClass="gHeaderStyle" />
<ItemStyle CssClass="gControlStyle" />
</asp:BoundField>
<asp:TemplateField ShowHeader="False" HeaderText= '<%$ Resources:Language, btnDelete %>'>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" CommandArgument='<%# Eval("PremiseUno") %>' onclick="LinkButton1_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>

If you convert the bound field to a template field, you can access the control holding the value of premise score:
<asp:TemplateField HeaderText="test">
<ItemTemplate>
<asp:Label runat="server" ID="testLabel" Text='<%# Eval("PremiseScore") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
You can then do the following to compute the sum in the Databound-event of the gridview:
protected void Grid_DataBound(Object sender, EventArgs e)
{
GridViewRow footerRow = grid.FooterRow;
var sum = (from GridViewRow row in grid.Rows select ((Label)row.FindControl("testLabel")).Text).Sum(d => Convert.ToInt16(d));
footerRow.Cells[0].Text = sum.ToString();
}
I assume here that all values are ints, but it´s easily convertible to other value types.

Related

ASP.NET GridView with DRopDown list check if user updated/ changed the dropdown selection

I have a GridView that the user can edit, in particular a datafield (MemberApproved) is displayed as a dropdown list when edited.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1" CssClass="gridview" AllowSorting="True" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowUpdated="GridView1_RowUpdated" OnRowUpdating="GridView1_RowUpdating" >
<HeaderStyle Font-Bold="True" ForeColor="White" />
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
<asp:BoundField DataField="Affiliation" HeaderText="Affiliation" SortExpression="Affiliation" />
<asp:BoundField DataField="Id" HeaderText="Id" SortExpression="Id" ReadOnly="True" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:BoundField DataField="MembershipCategory" HeaderText="Membership Category" SortExpression="MembershipCategory" />
<asp:TemplateField HeaderText="MemberApproved" SortExpression="MemberApproved">
<EditItemTemplate>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("MemberApproved") %>'></asp:HiddenField>
<asp:DropDownList ID="ddlStatus" runat="server"
SelectedValue='<%# Bind("MemberApproved") %>'>
<asp:ListItem Value="Yes">Yes</asp:ListItem>
<asp:ListItem Value="No">No</asp:ListItem>
<asp:ListItem Value="Locked">Locked</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("MemberApproved") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SupportingMember" HeaderText="Reference Member" SortExpression="SupportingMember" />
<asp:BoundField DataField="ReferenceEmail" HeaderText="Reference Email" SortExpression="ReferenceEmail" />
</Columns>
<HeaderStyle CssClass="fixedHeader " />
</asp:GridView>
I am trying to capture if the user changes the "MemberApproved" field, in the . I am able to capture the updated new value using the code below
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddl = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlStatus");
string NewSelection = ddl.SelectedValue;
}
I am however unable to hold the initial value of the dropdownlist in a variable to compare it to the NewSelection.
Any thoughts or suggestion to different approaches are greatly appreciated.
You're using a template field already. Why not store your value as part of a hiddenfield and then compare to it?
<asp:TemplateField HeaderText="MemberApproved" SortExpression="MemberApproved">
<EditItemTemplate>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("MemberApproved") %>'></asp:HiddenField>
<asp:DropDownList ID="ddlStatus" runat="server"
SelectedValue='<%# Bind("MemberApproved") %>'>
<asp:ListItem Value="Yes">Yes</asp:ListItem>
<asp:ListItem Value="No">No</asp:ListItem>
<asp:ListItem Value="Locked">Locked</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("MemberApproved") %>'></asp:Label>
<asp:hiddenField ID="label1History" runat="server" value='<%# Bind("MemberApproved") %>'
</ItemTemplate>
</asp:TemplateField>
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddl = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlStatus");
HiddenField labelHistory = (HiddenField)GridView1.Rows[e.RowIndex].FindControl("label1History");
string NewSelection = ddl.SelectedValue;
Boolean changedValue = NewSelection = labelHistory.value;
}

Get values from GridView and place it in text boxes

I just want to get the cell values from my GridView and place it in the different textboxes. I tried so many things but I just couldn't get it to work. Maybe you could help. Thanks.
This is the last thing I tried:
<asp:GridView ID="GridView1" runat="server" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" CellSpacing="2" AutoGenerateColumns="False" AutoGenerateSelectButton="True" onselectedindexchanged="GridView1_SelectedIndexChanged" OnSelectedIndexChanging="Gridview1_SelectedIndexChanging">
<Columns>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText="Employee ID">
<ItemTemplate>
<asp:Label ID="lblEmpID" runat="server" Text='<%# Eval("emp_id") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("emp_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("emp_add") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contact Num.">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("emp_contact") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hire Date">
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Eval("hire_date") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Branch ">
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Eval("hire_date") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
Code Behind:
protected void btnUpdate_Click(object sender, EventArgs e)
{
EmployeeDLL edll = new EmployeeDLL();
edll.Update_Employee(txtEmpID.Text, txtName.Text, txtAddress.Text, txtContact.Text, txtHireDate.Text, txtBranchID.Text);
lblStatus.Text = "Record has been updated.";
edll = null;
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
// txtEmpID.Text = GridView1.SelectedValue.ToString();
GridViewRow row = GridView1.SelectedRow;
txtEmpID.Text = row.Cells[0].Text;
txtName.Text = row.Cells[1].Text;
}
Use something like this
TextBox TextBoxLot = (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("label");
When using <asp:TemplateField>, the data is not inside Cell but is contained in the Control present inside the Cell.
So, There are two steps to read the value:
Access the Control inside Cell
Access the Value from Control in step 1
Example:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
// Step 1: Access the Control inside Cell
Label lblEmpId = (Label)row.Cells[0].FindControl("lblEmpID");
// Step 2: Access the Value from Control in step 1
string value = lblEmpId.Text;
// Combine Step 1 & Step 2
string valueEmpID = ((Label)row.Cells[0].FindControl("lblEmpID")).Text;
string name = ((Label)row.Cells[0].FindControl("Label2")).Text;
}

How to get the ID of the column on gridview radiobutton click

I have one radio button in gridview itemplate field. But when I am selecting the radiobutton i am unable to get the id of that row. So that based on that id textbox value will be autopopulated.
enter code here
<asp:GridView ID="gvItem" SkinID="GridView" runat="server" OnRowDataBound="gvItem_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="" Visible="false">
<ItemTemplate>
<%#Container.DataItemIndex %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="rbtnQuantity" runat="server" AutoPostBack="true" OnCheckedChanged="rbtnQuantity_CheckedChanged" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="20px" />
</asp:TemplateField>
<%--1--%>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text=' <%# Eval("ID")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="90px" />
</asp:TemplateField>
<%--2--%>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
<asp:Label ID="lblItemName" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="140px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
You can try on the radiobutton click event to look for sender.parent.findcontrol("lblID").
this would be on the code-behind and for vb.net it would look like this:
Dim rowID as String = CType(CType(sender, RadioButton).Parent.FindControl("lblID"),Label).Text

How to disable "Edit" button in Gridview?

Iam using Item Template field in my gridview to update the values inside particular column.
The ItemTemplate field contains "label" control and EditItemTemplate contains "DropDownList". Now the problem is I need to disable the "Edit" button based on the value of "Label"... Attached the lines of coding. Can anyone give me a solution.
Home.Aspx:
**********
<Columns>
<asp:BoundField DataField="Date" HeaderText="Date" ReadOnly="true" />
<asp:BoundField DataField="Type" HeaderText="Type" ReadOnly="true" />
<asp:BoundField DataField="Reason" HeaderText="Reason" ReadOnly="true" />
<asp:BoundField DataField="Request By" HeaderText="Request By" ReadOnly="true" />
<asp:TemplateField HeaderText="Status" HeaderStyle-HorizontalAlign="center">
<EditItemTemplate>
<asp:DropDownList ID="ddlState" AutoPostBack="false" runat="server">
<asp:ListItem Text="Approved" Value="Approved"> </asp:ListItem>
<asp:ListItem Text="Declined" Value="Declined"> </asp:ListItem>
<asp:ListItem Text="Pending" Value="Pending"> </asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Status") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
Here in my coding "lblName" has the status value in ItemTemplate and "ddlState" has the status value in EditItemTemplate. Based upon the "lblName" value , "Edit" option has to be enabled...
Another approach is to use RowDataBound so you can use the value of Status directly. This assumes you are using a DataTable or other DataRow collection for your data source. The DataItem cast will need to be updated if you are using a different data type.
<asp:GridView ID="ExampleGridView" runat="server" OnRowDataBound="ExampleGridView_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Status" HeaderStyle-HorizontalAlign="center">
<EditItemTemplate>
<asp:DropDownList ID="StateDropDownList" AutoPostBack="false" runat="server">
<asp:ListItem Text="Approved" Value="Approved" />
<asp:ListItem Text="Declined" Value="Declined" />
<asp:ListItem Text="Pending" Value="Pending" />
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="NameLabel" runat="server" Text='<%# Bind("Status") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="EditButton" runat="server" CommandName="Edit" Text="Edit" Visible="true" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<asp:LinkButton ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
From code behind you can handle the row independently and have access to most of what is going on:
protected void ExampleGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow
&& (
e.Row.RowState == DataControlRowState.Alternate
|| e.Row.RowState == DataControlRowState.Normal
|| e.Row.RowState == DataControlRowState.Selected
))
{
Button EditButton = (Button)e.Row.FindControl("EditButton");
System.Data.DataRow dataRecord = (System.Data.DataRow)e.Row.DataItem;
if (EditButton != null && dataRecord != null)
{
if (dataRecord["Status"] == "ValueThatShowsEditButton")
{
EditButton.Visible = true;
}
}
}
}
Convert your Edit CommandField to a TemplateField.
In the newly-generated Button, add the following markup:
Enabled='<%# IsEditEnabled(Eval("Status")) %>'
In your code-behind, create a new method:
protected bool IsEditEnabled(string statusValue)
{
// Here is where you determine the value
}
Let me know how that works for you.

gridview delete happens but gridview doesnt refresh?

I've got a gridview inside an update panel.
In the gridview I have an image button.
The button is used to delete a row.
In the rowCommand event of the grid view I do something like this:
protected void gvLineItems_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
switch (e.CommandName)
{
case "Delete":
Label l = null;
l = (Label)row.FindControl("lblLineItemID");
if(l!=null)
{
long lID;
lID = Convert.ToInt64(l.Text);
BL.DeleteLineItem(Convert.ToInt64(hlID.Text), lID);
BindGrid(Session["SortExpression"].ToString(), Convert.ToInt32(rbSortGrid.SelectedValue));
}
break;
}
}
I debug this and I see the row deleted in the database (data is deleted correctly). But the gridview still shows the "deleted" row even after bind grid. Bind grid is simple it looks like this:
protected void BindGrid(string sortExpression, int sortDirection)
{
DataSet ds
ds = BL.GetLineItemGridData(Convert.ToInt64(hlID.Text), sortExpression, sortDirection);
gvLineItems.DataSource = ds.Tables[0];
gvLineItems.DataBind();
gvLineItems.Visible = true;
}
The dataset is returning the correct rows (without the deleted row) but when I look at the webpage it still shows the row that was deleted.
Edit
Someone asked for the HTML of the gridview, here it is:
<asp:UpdatePanel ID="myPanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:GridView GridLines="Horizontal" CellPadding="4" Font-Size="Small"
DataKeyNames="ID" Width="100%" AlternatingRowStyle-BackColor="#e5f1fa"
BackColor="#E8E8E8" HeaderStyle-ForeColor="White"
HeaderStyle-BackColor="#1367AD" ID="gvLineItems" runat="server"
AllowSorting="True" AutoGenerateColumns="False" ShowFooter="True"
onrowcommand="gvLineItems_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemStyle Width="1px" />
<ItemTemplate>
<asp:Label Width=".05px" ID="lblLineItemID" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ID") %>' style="display:none"></asp:Label>
</ItemTemplate>
<ControlStyle Width="0px" />
<HeaderStyle Width="0px" />
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ToolTip="Select / Deselect all rows?" ID="HeaderLevelCheckBox" onclick="toggleSelection(this);" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelector" ToolTip="Select row?" runat="server" onclick="ChangeRowColor(this)" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ibAddLineItem" runat="server" ImageUrl="images/InsertRow.gif" CommandName="Insert" ToolTip="Insert new line item."/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ibDeleteLineItem" runat="server" ImageUrl="images/DeleteRow.gif" CommandName="Delete" ToolTip="Delete line item."/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item #" SortExpression="LineItemNumber">
<ItemTemplate>
<asp:Label runat="server" ID="lblItemNumber" Visible="True" Text='<%# DataBinder.Eval(Container, "DataItem.LineItemNumber") %>' />
</ItemTemplate>
<ItemStyle Width="10%" HorizontalAlign="Center" />
<HeaderStyle HorizontalAlign="Center" Width="10%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" SortExpression="LineItemQuantity">
<ItemTemplate>
<asp:TextBox Font-Names="Arial" ToolTip="Enter item quantity." ID="txtLineItemQuantity" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.LineItemQuantity") %>' />
</ItemTemplate>
<ItemStyle Width="4%" HorizontalAlign="Center" />
<HeaderStyle HorizontalAlign="Center" Width="4%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" SortExpression="LineItemDescription">
<ItemTemplate>
<asp:TextBox Columns="15" Width="300px" Font-Names="Arial" ToolTip="Enter item description." ID="txtLineItemDescription" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.LineItemDescription") %>' />
</ItemTemplate>
<ItemStyle Width="15%" HorizontalAlign="Left" />
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Added By" SortExpression="AddedBy">
<ItemTemplate>
<asp:Label runat="server" ID="lblAddedBy" Visible="True" Text='<%# DataBinder.Eval(Container, "DataItem.AddedBy") %>' />
</ItemTemplate>
<ItemStyle Width="10%" HorizontalAlign="Center" />
<HeaderStyle HorizontalAlign="Center" Width="10%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Added On" SortExpression="AddedOn">
<ItemTemplate>
<asp:Label runat="server" ID="lblAddedOn" Visible="True" Text='<%# DataBinder.Eval(Container, "DataItem.AddedOn") %>' />
</ItemTemplate>
<ItemStyle Width="10%" HorizontalAlign="Center" />
<HeaderStyle HorizontalAlign="Center" Width="10%" />
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddLineItem" />
<asp:AsyncPostBackTrigger ControlID="rbSortGrid" />
</Triggers>
</asp:UpdatePanel>
Err I got it I just added this:
protected void gvLineItems_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataSet ds = null;
gvLineItems.DataSource = null;
ds = BL.GetLineItemGridData(Convert.ToInt64(hlID.Text), Session["SortExpression"].ToString(), Convert.ToInt32(rbSortGrid.SelectedValue));
gvLineItems.DataSource = ds.Tables[0];
gvLineItems.DataBind();
gvLineItems.Visible = true;
}
And removed the call to BindGrid from this:
protected void gvLineItems_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
switch (e.CommandName)
{
case "Delete":
Label l = null;
l = (Label)row.FindControl("lblLineItemID");
if(l!=null)
{
long lID;
lID = Convert.ToInt64(l.Text);
BL.DeleteLineItem(Convert.ToInt64(hlID.Text), lID);
//BindGrid(Session["SortExpression"].ToString(), Convert.ToInt32(rbSortGrid.SelectedValue));
}
break;
}
}
Alternatively you can bind your GridView in the Page PreRender event which occurs after processing of control events has been completed. You don't need to hook up the datasource and bind the grid in the rowCommand event then.

Resources