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;
}
Related
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;
}
I looked for some similar questions, but found only ListView solutions
But I have a GridView and a button outside of the GridView and need to udate only records specified by a selected checkbox.
<asp:GridView ID="gvData"
runat="server" Width = "850px"
CellPadding="5"
AutoGenerateColumns="false"
AllowPaging ="true"
OnPageIndexChanging ="OnPaging" PageSize="5">
<HeaderStyle CssClass="HeaderStyle" />
<PagerStyle CssClass="HeaderStyle" HorizontalAlign="Center" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
<RowStyle CssClass="RowStyle" />
<RowStyle HorizontalAlign="Left" />
<Columns>
<asp:TemplateField HeaderText="Id" ItemStyle-Width="20px" Visible="false">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="20px">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked = "false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Message" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblMessage" runat="server" Width="500px" Text='<%# Eval("Message") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<div style="text-align:left;">
<asp:Button ID="btnChange" runat="server" Text="Change Type" OnClick="btnChange_Click" />
</div>
I have a method btnChange_Click():
protected void btnChange_Click()
{
int index = gvFailedMerchants.SelectedRow.RowIndex;
DbConnection.UpdateMessageType(index);
}
When I click the button, I'm getting the message
"Object reference not set to an instance of an object"
I want to write a logic that where I traverse the grid and add ids of the selected row into one string where all ids are separated by commas:
1,2,3,4,5
Then I will send this string to the stored procedure and use them in a query within IN close:
UPDATE MYTABLE SET column = myValue WHERE ID IN('1,2,3,4,5')
I do not know what is the right approach to the problem.
How can I do that?
Please try this,
<asp:TemplateField HeaderText="Select" ItemStyle-Width="20px">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked = "false"
OnCheckedChanged="ChkSelect_CheckedChanged" data-id='<%# Eval("id") %>'></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
protected void ChkSelect_CheckedChanged(object sender, EventArgs e)
{
try
{
CheckBox chkSel = sender as CheckBox;
string id= chkSel.Attributes["data-id"].ToString();
if (chkSel.Checked == true)
{
Session["ID"] += (Session["ID"].ToString() == "" ? id: "," + id);
}
else
{
string existingCodes = Session["ID"].ToString();
Session["ID"] = existingCodes.Replace(id, "");
}
protected void btnChange_Click()
{
string ids = Session["ID"].ToString();
DbConnection.UpdateMessageType(ids);
}
I have a grid view with template fields and can bind data into it. In my grid view I also have a command field (Select) to print the respective selected row data in a report. when i made the template fields into bound field, the GridView_SelectedIndexChanged() method works properly. But I need the same functionality by keeping the template fields as it is (not changing to Bound Field).
My Grid View is
<asp:GridView ID="dgvGeneralBillList" runat="server" style="font-size:11px;margin:0px auto auto 30px;width:auto;" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" OnSelectedIndexChanged="dgvGeneralBillList_SelectedIndexChanged">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="Bill ID">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("BillID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblBillID" runat="server" Text='<%# Bind("BillID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bill No">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("SerialNo") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblSerialNo" runat="server" Text='<%# Bind("SerialNo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Billed Week">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("BilledWeekNo") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblBilledWeekNo" runat="server" Text='<%# Bind("BilledWeekNo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Billed Date">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("BilledWeekDate") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblBilledWeekDate" runat="server" Text='<%# Bind("BilledWeekDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("Amount") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblAmount" runat="server" Text='<%# Bind("Amount") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bill Status">
<EditItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("BillStatus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblBillStatus" runat="server" Text='<%# Bind("BillStatus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField SelectText="print" ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
And the function is
protected void dgvGeneralBillList_SelectedIndexChanged(object sender, EventArgs e)
{
clsBill[] oBillList = new clsBill[1];
clsBill oBill = new clsBill();
//oBill.BillID = Convert.ToDouble(dgvGeneralBillList.SelectedRow.Cells[0].Text.ToString());
oBill.BillID = Convert.ToDouble(dgvGeneralBillList.SelectedRow.FindControl("lblBillID").ToString());
oBillList[0] = oBill;
if (oBillList.Length < 1)
{
lblMessage.Text = "Error : No Bill Entry found";
return;
}
BLBill oBLBill = new BLBill();
string sErrorMessage = string.Empty;
Object oOutput = oBLBill.Execute((int)BOCollectionType.ACTION_BILL.ACTION_BILL_GET_SINGLE_REPORT, oBillList, ref sErrorMessage);
DSBillReport oDSBillReport = new DSBillReport();
if (sErrorMessage != "")
{
lblMessage.Text = sErrorMessage;
return;
}
else
{
oDSBillReport = (DSBillReport)oOutput;
if (oDSBillReport.BillReport.Rows.Count > 0)
{
Session["GeneralBill"] = oDSBillReport;
Session["MedicalBill"] = null;
Response.Redirect("frmReportHolder.aspx");
}
}
return;
}
Please help !
Well, looks like a quite simple solution of this question. Here is the code currently I am using. I just type cast the SelectedRow as GridViewRow and then type cast the required Label in a new Label object (inside the try...catch block). This worked for me so far. Thanks to everyone.
protected void dgvGeneralBillList_SelectedIndexChanged(object sender, EventArgs e)
{
clsBill[] oBillList = new clsBill[1];
clsBill oBill = new clsBill();
try
{
GridViewRow oGridRow = (GridViewRow)dgvGeneralBillList.SelectedRow;
Label lblID = (Label)oGridRow.FindControl("lblBillID");
oBill.BillID = Convert.ToDouble(lblID.Text.ToString());
}
catch (Exception ex)
{
}
oBillList[0] = oBill;
if (oBillList.Length < 1)
{
lblMessage.Text = "Error : No Bill Entry found";
return;
}
BLBill oBLBill = new BLBill();
string sErrorMessage = string.Empty;
Object oOutput = oBLBill.Execute((int)BOCollectionType.ACTION_BILL.ACTION_BILL_GET_SINGLE_REPORT, oBillList, ref sErrorMessage);
DSBillReport oDSBillReport = new DSBillReport();
if (sErrorMessage != "")
{
lblMessage.Text = sErrorMessage;
return;
}
else
{
oDSBillReport = (DSBillReport)oOutput;
if (oDSBillReport.BillReport.Rows.Count > 0)
{
Session["GeneralBill"] = oDSBillReport;
Session["MedicalBill"] = null;
Response.Redirect("frmReportHolder.aspx");
}
}
return;
}
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.
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.