How to disable "Edit" button in Gridview? - asp.net

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.

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

Sorting asp.net GridView with SPDataSource

I would like to sort my GridView by clicking on the column's header. So far I declared a SPDataSource
<SharePoint:SPDataSource
runat="server"
ID="SPdsInventarGrid"
DataSourceMode="List"
UseInternalName="true"
Scope="Recursive"
SelectCommand="<View><Query><Where><Or><Neq><FieldRef Name='EBS_x002e_CN_x002e_Inventar_x00210' /><Value Type='Text'>Open</Value></Neq><IsNull><FieldRef Name='EBS_x002e_CN_x002e_Inventar_x0028' /></IsNull></Or></Where></Query><ViewFields><FieldRef Name='Title'/><FieldRef Name='ID'/><FieldRef Name='EBS_x002e_CN_x002e_Inventar_x0028'/><FieldRef Name='EBS_x002e_CN_x002e_Inventar_x00210'/><FieldRef </ViewFields></View>">
<SelectParameters>
<asp:Parameter Name="ListName" DefaultValue="Inventar" />
</SelectParameters>
</SharePoint:SPDataSource>
Then I created my grid, based on the datasource
<asp:GridView Visible="true" Width="100%"
ID="gvInventar"
AutoGenerateColumns="false" runat="server" CellPadding="2" AllowPaging="false" AllowSorting="true" OnSorted="gvInventar_Sorted" OnSorting="gvInventar_Sorting" GridLines="None" DataSourceID="SPdsInventarGrid" OnRowCommand="gvInventar_RowCommand">
<Columns>
<asp:CommandField ButtonType="Image" ShowEditButton="true" EditImageUrl="/_layouts/images/edit.gif" UpdateImageUrl="/_layouts/images/save.gif" CancelImageUrl="/_layouts/images/delete.gif" />
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label Text='<%# Bind("ID") %>' runat="server" ID="lblIdProduct"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" >
<ItemTemplate>
<asp:Label Text='<%# Bind("Title") %>' runat="server" ID="lblTitleProduct" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product" SortExpression="Product">
<ItemTemplate>
<asp:Label Text='<%# Bind("EBS_x002e_CN_x002e_Inventar_x0028") %>' runat="server" ID="lblProduct" "></asp:Label>
</ItemTemplate>
</Columns>
</asp:GridView>
Now, I have this function where I wanted to get the current Query as a string and add <OrderBy>(my field) before <Query> but i get an error saying that the DataSource has been already declared (which is true because i want to be declared in asp)
protected void gvInventar_Sorting(object sender, GridViewSortEventArgs e)
{
SPQuery q = new SPQuery();
q.Query = SPdsInventarGrid.SelectCommand;
switch (e.SortExpression)
{
case "Product":
if (e.SortDirection == SortDirection.Ascending)
{
gvInventar.DataSource = q.Query;
gvInventar.DataBind();
}
else
{
}
break;
}
}
Even though it's not working this way, I don't think modifying the Query is the solution.
Could anyone help me with this matter?
You don't need to write any custom code to sort the gridview by clicking the column headers, all you have to do is set the SortExpression property of the TemplateField to the required column name, e.g:
<Columns>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<asp:Label Text='<%# Bind("ID") %>' runat="server" ID="lblIdProduct" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" SortExpression="Title">
<ItemTemplate>
<asp:Label Text='<%# Bind("Title") %>' runat="server" ID="lblTitleProduct" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product" SortExpression="EBS_x002e_CN_x002e_Inventar_x0028">
<ItemTemplate>
<asp:Label Text='<%# Bind("EBS_x002e_CN_x002e_Inventar_x0028") %>' runat="server"
ID="lblProduct" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
Now you can sort on all 3 columns:

How to validate dropdownlist control inside the gridview

edit:
var dropDownControls = $('#<%=GridView1.ClientID %> select option:selected');
var checkbox = $.......checkbox .....
for(index = 0; index < dropDownControls.length; index++)
{
if (checkbox.checked) //my code gets exaclty what checkbox i checked
{
if(dropDownControls[index].selectedIndex == 0)
{
flag = false;
break;
}
}
}
the above code works
i have my button outside the gridivew and i am trying to validate the dropdownlist which is inside the gridivew.
<asp:Button ID="btn" runat="server" Text="Submit" OnClick="btn_Click" CausesValidation="true"/>
<asp:GridView ID="GVInputMapping" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
EnableModelValidation="True" onrowdatabound="GVInputMapping_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" ControlStyle-Width="250px" HeaderText="Name" SortExpression="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox id="checkbox1" runat="server"/>
<asp:DropDownList runat="server" ID="ddldetail">
<asp:ListItem Selected="True" Value="0">Select me</asp:ListItem>
<asp:ListItem Value="1">abc</asp:ListItem>
<asp:ListItem Value="2">GHt</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="requiredDDL" runat="server"
ControlToValidate="ddldetail" ErrorMessage="Please select" InitialValue="Select me" Display="Dynamic"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
credit goes to ahaliav fox
http://stackoverflow.com/questions/10566599/how-to-control-asp-net-validator-controls-client-side-validation
gridview:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" OnRowDataBound="gv_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" ControlStyle-Width="250px" HeaderText="ID" SortExpression="ID" />
<asp:BoundField DataField="FirstName" ControlStyle-Width="250px" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" ControlStyle-Width="250px" HeaderText="LastName"
SortExpression="LastName" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkbox1" runat="server" />
<asp:DropDownList ID="drpPaymentMethod" runat="server">
<asp:ListItem Value="-1">----</asp:ListItem>
<asp:ListItem Value="0">Month</asp:ListItem>
<asp:ListItem Value="1">At End</asp:ListItem>
<asp:ListItem Value="2">At Travel</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfv" InitialValue="-1" ControlToValidate="drpPaymentMethod" Enabled="false" Display="Static" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:TextBox ID="txt_Value" runat="server" Width="58px" Text="0"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox checkbox1 = e.Row.FindControl("checkbox1") as CheckBox;
RequiredFieldValidator rfv = e.Row.FindControl("rfv") as RequiredFieldValidator;
DropDownList drpPaymentMethod = (DropDownList)e.Row.FindControl("drpPaymentMethod");
// you can just pass "this" instead of "myDiv.ClientID" and get the ID from the DOM element
checkbox1.Attributes.Add("onclick", "UpdateValidator('" + checkbox1.ClientID + "','" + drpPaymentMethod.ClientID + "','" + rfv.ClientID + "');");
if (!checkbox1.Checked)
drpPaymentMethod.Attributes.Add("disabled", "disabled");
}
}
javascript:
function UpdateValidator(chkID, drpID, validatorid) {
//enabling the validator only if the checkbox is checked
var enableValidator = $("#" + chkID).is(":checked");
if (enableValidator)
$('#' + drpID).removeAttr('disabled');
else
$('#' + drpID).attr('disabled', 'disabled');
var vv = $('#' + validatorid).val();
ValidatorEnable(document.getElementById(validatorid), enableValidator);
}
Set the RequiredFieldValidator's InitialValue to 0 instead of "Select me" since the item that is selected by default has a value of 0
<asp:ListItem Selected="True" Value="0">Select me</asp:ListItem>
Apart from that it should work fine.
Edit: Your comments revealed that you use jQuery to enable a CheckBox that fixes the DropDownList selection. The user should have selected something now. So your requirement actualy is that no the validator should be active. So disable all Validators initially(Enabled="false").
Since you're handling the checkbox click on clientside anyway, i would recommend to enable the validator if it's checked and disable it when it's unchecked. You can use the (Mini-)Validation-Client-Side API especially the ValidatorEnable(val, enable) function. You only need a reference to the validator. But that should not a problem for you.
I think the best way is to use a customValidator and use client side scripts to validate. Then use a validation summary to display the error or the requirement

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.

Add summary row in Gridview for one column

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.

Resources