How to specify which control to use in the gridview rowupdate - c#

I have a gridview and several template fields and several rowcommands. I would like to use the built in update row command but the problem I'm running into is making it so my application isn't functioning correctly.
Problem: In one of my edititem template fields I have both a Label control and a dropdown control. The reason for this is that I need to hide/show one or the other depending on the rowcommand is triggered. When I use the built in edit rowcommand I hide the dropdown and display the dropdownlist. So everything works there. However, when update rowcommand is triggered it is using the label value which is not visible and is bound to display the month rather than the full date that is needed. I use the drop down list to display the month to the user and the selected value is the full date. For some odd reason it wants to use the label value instead of the drop down list selected value even though I specify the update parameter in the code behind. If I remove the label from the commissionmonth column then everything works just fine except for the fact that on my other row commands the drop down list I would have to display a drop down list instead of the wanted label.
If any of you know how to specify the control to use in the update rowcommand or somehow dynamically change that column to read only on certain row commands I would greatly appreciate it!
Code Sample:
<asp:GridView ID="UnverifiedSalesGV" runat="server" AllowSorting="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4"
DataSourceID="UnverifiedSalesSDS" ForeColor="Black" GridLines="Vertical"
Width="100%" ShowHeaderWhenEmpty="True" DataKeyNames="ID"
onrowupdating="UnverifiedSalesGV_RowUpdating"
onrowcommand="UnverifiedSalesGV_RowCommand"
onrowdatabound="UnverifiedSalesGV_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="EditBTN" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit" />
<asp:Button ID="VerifyBTN" runat="server" Text="Verify" CommandName="VerifyRecord" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<EditItemTemplate>
<asp:Button ID="UpdateBTN" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:Button ID="UpdateProductBTN" runat="server" Text="Verify" CommandName="UpdateProduct" Visible="false" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:Button ID="CancelBTN" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CompanyName" HeaderText="Company"
SortExpression="CompanyName" ReadOnly="True" />
<asp:BoundField DataField="SalesRep" HeaderText="Sales Rep"
SortExpression="SalesRep" ReadOnly="True" >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="AccountManager" HeaderText="Account Manager"
SortExpression="AccountManager" ReadOnly="True" >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="ProductID" HeaderText="ProductID"
SortExpression="ProductID" Visible="False" />
<asp:TemplateField HeaderText="Product" SortExpression="Product">
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("Product") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="CurrentProductLBL" runat="server" Text='<%# Eval("Product") %>'></asp:Label>
<asp:DropDownList ID="RenewalProductDDL" runat="server"
DataSourceID="RenewalProductSDS" DataTextField="Product" DataValueField="ID" Visible="false">
</asp:DropDownList>
<asp:SqlDataSource ID="RenewalProductSDS" runat="server"
ConnectionString="<%$ ConnectionStrings:Wizard_SwearsConnectionString1 %>"
SelectCommand="SELECT * FROM [Product] LEFT JOIN ProductToProductCategory AS Category ON Product.ID = Category.ProductID WHERE Category.ProductCategoryID = 5 AND Product.ID <> 38 ORDER BY [Product]"></asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DateFulfilled" DataFormatString="{0:M/d/yyyy}"
HeaderText="Date Fulfilled" SortExpression="DateFulfilled"
ReadOnly="True" />
<asp:TemplateField HeaderText="Gross Sales Amount"
SortExpression="GrossSalesAmount">
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("GrossSalesAmount", "{0:C}") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="GrossSalesLBL" runat="server"
Text='<%# Bind("GrossSalesAmount", "{0:C}") %>' Visible="false"></asp:Label>
<asp:TextBox ID="GrossSalesTXT" runat="server"
Text='<%# Bind("GrossSalesAmount") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Net Sales Amount"
SortExpression="NetSalesAmount">
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Bind("NetSalesAmount", "{0:C}") %>' ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="NetSalesLBL" runat="server" Text='<%# Bind("NetSalesAmount", "{0:C}") %>' Visible="false"></asp:Label>
<asp:TextBox ID="NetSalesTXT" runat="server" Text='<%# Bind("NetSalesAmount") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Commission Month"
SortExpression="CommissionMonth">
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("CommissionMonth", "{0:MMMM}") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="CommissionMonthDDL" runat="server"
DataSourceID="SalesCommissionDDLSDS" DataTextField="Month"
DataValueField="CommissionMonth">
</asp:DropDownList>
<asp:Label ID="SalesCommissionLBL" runat="server"
Text='<%# Bind("CommissionMonth") %>' Visible="false" ></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Notes" SortExpression="Notes">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("Notes") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="NotesLBL" runat="server" Text='<%# Bind("Notes") %>' Visible="false"></asp:Label>
<asp:TextBox ID="NotesTXT" runat="server" Text='<%# Bind("Notes") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
Code behind:
protected void UnverifiedSalesGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Get date and user info
DateTime getDate = System.DateTime.Now;
MembershipUser user = Membership.GetUser();
string activeuser = user.UserName;
try
{
//Get dropdown and textbox values
string commisionMonth;
string grossSalesAmount;
string netSalesAmount;
string notes;
TextBox grossSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.RowIndex)].FindControl("GrossSalesTXT");
TextBox netSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.RowIndex)].FindControl("NetSalesTXT");
TextBox notesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.RowIndex)].FindControl("NotesTXT");
DropDownList commissionMonthValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.RowIndex)].FindControl("CommissionMonthDDL");
grossSalesAmount = grossSalesValue.Text;
netSalesAmount = netSalesValue.Text;
commisionMonth = commissionMonthValue.SelectedValue;
notes = notesValue.Text;
UnverifiedSalesSDS.UpdateParameters["GrossSalesAmount"].DefaultValue = grossSalesAmount;
UnverifiedSalesSDS.UpdateParameters["NetSalesAmount"].DefaultValue = netSalesAmount;
UnverifiedSalesSDS.UpdateParameters["CommissionMonth"].DefaultValue = commisionMonth;
UnverifiedSalesSDS.UpdateParameters["Notes"].DefaultValue = notes;
UnverifiedSalesSDS.UpdateParameters["DateLastModified"].DefaultValue = getDate.ToString();
UnverifiedSalesSDS.UpdateParameters["UserLastModified"].DefaultValue = activeuser;
UnverifiedSalesSDS.Update();
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not update record. Message: " + ex.Message;
}
}

I was finally able to solve my problem with the following code:
//Verify and Update Record
protected void UnverifiedSalesGV_RowCommand(object sender, GridViewCommandEventArgs e)
{
buttonCommand = e.CommandName;
if (buttonCommand != "Cancel" && buttonCommand != "Edit" && buttonCommand != "Sort")
{
//Get Gridview data key and row index
rowIndex = Convert.ToInt32(e.CommandArgument);
salesID = UnverifiedSalesGV.DataKeys[rowIndex].Value.ToString();
MessageLBL.Text = "";
//Get productID
SalesData getSalesRecord = new SalesData();
getSalesRecord.GetRowValuesSalesID(salesID);
string productID = getSalesRecord.productID;
if (buttonCommand == "VerifyRecord")
{
if (productID != "38")
{
try
{
UpdateSalesRecordSDS.UpdateCommand = "UPDATE Sales SET Verified = #Verified WHERE ID = #ID";
UpdateSalesRecordSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UpdateSalesRecordSDS.UpdateParameters["Verified"].DefaultValue = true.ToString();
UpdateSalesRecordSDS.Update();
UnverifiedSalesGV.DataBind();
VerifiedSalesGV.DataBind();
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not verify sale. Message: " + ex.Message;
}
}
else
{
//Get row index.
UnverifiedSalesGV.SetEditRow(rowIndex);
UnverifiedSalesGV.DataBind();
}
}
if (buttonCommand == "UpdateProduct")
{
DropDownList productValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("RenewalProductDDL");
if (productValue.SelectedIndex != 0)
{
try
{
UpdateSalesRecordSDS.UpdateCommand = "UPDATE Sales SET ProductID = #ProductID, Verified = #Verified WHERE ID = #ID";
UpdateSalesRecordSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UpdateSalesRecordSDS.UpdateParameters["ProductID"].DefaultValue = productValue.SelectedValue;
UpdateSalesRecordSDS.UpdateParameters["Verified"].DefaultValue = true.ToString();
UpdateSalesRecordSDS.Update();
UnverifiedSalesGV.DataBind();
UnverifiedSalesGV.EditIndex = -1;
VerifiedSalesGV.DataBind();
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not verify sale. Message: " + ex.Message;
}
}
else
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Please select renewal type.";
}
}
if (buttonCommand == "UpdateRecord")
{
//Get date and user info
DateTime getDate = System.DateTime.Now;
MembershipUser user = Membership.GetUser();
string activeuser = user.UserName;
try
{
//Get dropdown and textbox values
string amid;
string commisionMonth;
string grossSalesAmount;
string netSalesAmount;
string notes;
DropDownList accountManagerID = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("AccountManagerDDL");
TextBox grossSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("GrossSalesTXT");
TextBox netSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("NetSalesTXT");
TextBox notesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("NotesTXT");
DropDownList commissionMonthValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("CommissionMonthDDL");
amid = accountManagerID.SelectedValue;
grossSalesAmount = grossSalesValue.Text;
netSalesAmount = netSalesValue.Text;
commisionMonth = commissionMonthValue.SelectedValue;
notes = notesValue.Text;
UnverifiedSalesSDS.UpdateCommand = "UPDATE [Sales] SET [OriginalAMID] = #OriginalAMID, [GrossSalesAmount] = #GrossSalesAmount, [NetSalesAmount] = #NetSalesAmount, [Notes] = #Notes, [CommissionMonth] = #CommissionMonth, [DateLastModified] = #DateLastModified, [UserLastModified] = #UserLastModified WHERE [ID] = #ID";
UnverifiedSalesSDS.UpdateParameters["OriginalAMID"].DefaultValue = amid;
UnverifiedSalesSDS.UpdateParameters["GrossSalesAmount"].DefaultValue = grossSalesAmount;
UnverifiedSalesSDS.UpdateParameters["NetSalesAmount"].DefaultValue = netSalesAmount;
UnverifiedSalesSDS.UpdateParameters["CommissionMonth"].DefaultValue = commisionMonth;
UnverifiedSalesSDS.UpdateParameters["Notes"].DefaultValue = notes;
UnverifiedSalesSDS.UpdateParameters["DateLastModified"].DefaultValue = getDate.ToString();
UnverifiedSalesSDS.UpdateParameters["UserLastModified"].DefaultValue = activeuser;
UnverifiedSalesSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UnverifiedSalesSDS.Update();
UnverifiedSalesGV.DataBind();
UnverifiedSalesGV.EditIndex = -1;
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not update record. Message: " + ex.Message;
}
}
}
}
//Hide and show fields
protected void UnverifiedSalesGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == rowIndex)
{
string state = e.Row.RowState.ToString();
if (state == "Alternate, Edit" || state == "Edit")
{
//Get record ID
string salesID = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.Row.DataItemIndex)].Value.ToString();
//Get productID
SalesData getSalesRecord = new SalesData();
getSalesRecord.GetRowValuesSalesID(salesID);
string productID = getSalesRecord.productID;
if (productID == "38")
{
//Items to Hide/Display
Button UpdateProductBTN = (Button)e.Row.FindControl("UpdateProductBTN");
Button UpdateBTN = (Button)e.Row.FindControl("UpdateBTN");
Label productLBL = (Label)e.Row.FindControl("CurrentProductLBL");
Label accountManagerLBL = (Label)e.Row.FindControl("AccountManagerLBL");
DropDownList productDDL = (DropDownList)e.Row.FindControl("RenewalProductDDL");
DropDownList accountManagerDDL = (DropDownList)e.Row.FindControl("AccountManagerDDL");
Label grossSalesLBL = (Label)e.Row.FindControl("GrossSalesLBL");
TextBox grossSalesTXT = (TextBox)e.Row.FindControl("GrossSalesTXT");
Label netSalesLBL = (Label)e.Row.FindControl("NetSalesLBL");
TextBox netSalesTXT = (TextBox)e.Row.FindControl("NetSalesTXT");
Label commissionMonthLBL = (Label)e.Row.FindControl("SalesCommissionLBL");
DropDownList commissionMonthDDL = (DropDownList)e.Row.FindControl("CommissionMonthDDL");
TextBox notesTXT = (TextBox)e.Row.FindControl("NotesTXT");
Label notesLBL = (Label)e.Row.FindControl("NotesLBL");
UpdateProductBTN.Visible = true;
UpdateBTN.Visible = false;
productLBL.Visible = false;
productDDL.Visible = true;
accountManagerLBL.Visible = true;
accountManagerDDL.Visible = false;
grossSalesLBL.Visible = true;
grossSalesTXT.Visible = false;
netSalesLBL.Visible = true;
netSalesTXT.Visible = false;
commissionMonthLBL.Visible = true;
commissionMonthDDL.Visible = false;
notesTXT.Visible = false;
notesLBL.Visible = true;
}
}
}
}

Related

Cell Text Always &nbsp:

I want to display the text of a specific cell in a textbox whenever I select a row from my gridview but whenever i do this "&nbsp" is the only text that I get even though the cell is not empty. Data on the gridview is bound from my database and I made a function where all the data from my database will be bound on my gridview. Below is the code that I'm using.
textbox1.Text = myGridView.SelectedRow.Cells[3].Text;
Markup
<asp:GridView ID="TraineeGrid" runat="server" AutoGenerateSelectButton ="true" AllowSorting="True" ShowHeader="true"
ShowFooter="false" AutoGenerateColumns="False" AutoGenerateEditButton="false" ScrollBars="Auto"
OnRowEditing="TraineeGrid_RowEditing"
OnRowUpdating="TraineeGrid_RowUpdating" OnRowCancelingEdit="TraineeGrid_RowCancelingEdit"
DataKeyNames="ID" Width="100%"
CellPadding="4" ForeColor="#333333" GridLines="None" HorizontalAlign="Center"
EditRowStyle-VerticalAlign="Middle" OnInit="Page_Load" OnRowDataBound="TraineeGrid_RowDataBound" OnSelectedIndexChanging="TraineeGrid_SelectedIndexChanging" OnSelectedIndexChanged="TraineeGrid_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("Delegate") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rank/Position">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbRankPos" runat="server" Text="Rank/Position" CommandName="Sort"
CommandArgument="RankPos" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newRankPos" TabIndex="2" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("RankPos") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtRankPos" runat="server"
Text='<%# Eval("RankPos") %>'/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
Function that binds Data
private void PopulateData()
{
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TestCS"].ConnectionString))
{
string path = "PopulateSQL.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
string sql = sb.ToString();
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
using (SqlDataAdapter dataAdapt = new SqlDataAdapter(cmd))
{
dataAdapt.Fill(dataTable);
ViewState["NormalGrid"] = dataTable;
}
}
}
}
if (dataTable.Rows.Count > 0)
{
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
}
else
{
//Displays 'No Data Found' to gridview if there are no data in table
dataTable.Rows.Add(dataTable.NewRow());
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
TraineeGrid.Rows[0].Cells.Clear();
TraineeGrid.Rows[0].Cells.Add(new TableCell());
TraineeGrid.Rows[0].Cells[0].ColumnSpan = dataTable.Columns.Count;
TraineeGrid.Rows[0].Cells[0].Text = "No Data Found";
TraineeGrid.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
You can use this: textbox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
In OnSelectedIndexChanged :
protected void OnSelectedIndexChanged1(object sender, EventArgs e)
{
//Get the selected row
GridViewRow row = GridView1.SelectedRow;
if (row != null)
{
// With
// TextBox1.Text = (row.FindControl("lblLocalTime") as Label).Text;
// Without
TextBox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
}
}
Complete Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnSelectedIndexChanged="OnSelectedIndexChanged1" AutoGenerateSelectButton="true">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="150" />
</Columns>
I've already found a solution. The problem is Im using TemplateField instead of BoundField that's why I cant use .Cells[] to get the specific cell that I wanted to get. However, if you are using TemplateField you can use .FindControl() and put in the ID of the label where your binding of data happens (ex. Text ='<%# Eval("FirstName") %>'). You can see that I put label on ItemTemplate to call it's ID.
Markup
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbName" runat="server" Text = '<%# Eval("Delegate") %>'> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>' />
</EditItemTemplate>
</asp:TemplateField>
Code Behind
Label varName = (Label)rows.FindControl("lbName");
string name = varName.Text;

How to Access elements of a checked/selected row elements of gridview

I am working in windows 8.2 and was working to insert a selected row to my data base and i have web form which have a grideview with checkboxes to select/deselect and an event to insert.
the code of the web form is as
<asp:Panel runat="server" ID="pnlStudData">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:checkbox runat="server" ID="chKCheckAll" onclick="javascript:SelectAllCheckboxes(this)"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkCheck" onclick="javascript:CheckedCheckboxes(this)"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Id">
<ItemTemplate>
<asp:Label ID="lblStudName" runat="server" Text='<%#Eval("Stud_Id")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Text='<%#Eval("FirstName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Middle Name">
<ItemTemplate>
<asp:Label ID="lblMiddleName" runat="server" Text='<%#Eval("MiddleName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%#Eval("LastName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cumpase">
<ItemTemplate>
<asp:Label ID="lblCumpase" runat="server" Text='<%#Eval("Cumpase")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="College">
<ItemTemplate>
<asp:Label ID="lblCollege" runat="server" Text='<%#Eval("College")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<asp:Label ID="lblDept" runat="server" Text='<%#Eval("Dept")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Block">
<ItemTemplate>
<asp:Label ID="lblBlock" runat="server" Text='<%#Eval("Block")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dorm Number">
<ItemTemplate>
<asp:Label ID="lblDormNo" runat="server" Text='<%#Eval("Dorm")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
<br />
<asp:Button ID="Save" runat="server" Text="Save" Width="169px" Height="46px" OnClick="Save_Click" />
<br />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
</asp:Panel>
and the java script to select/deselect a check-box as
<script language="javascript" type="text/javascript">
function SelectAllCheckboxes(chk)
{
var totalRows = $("#<%=GridView1.ClientID%> tr").length;
var selected = 0;
$('#<%=GridView1.ClientID%>').find("input:checkbox").each(function () {
if (this != chk) {
this.checked = chk.checked;
selected += 1;
}
});
}
function CheckedCheckboxes(chk)
{
if(chk.checked)
{
var totalRows = $('#<%=GridView1.ClientID %> :checkboxes').length;
var checked = $('#<%=GridView1.ClientID %> :checkbox:checked').length;
if(checked==(totalRows-1))
{
$('#<%=GridView1.ClientID %>').find("input:checkbox").each(function () {
this.checked = true;
});
}
else
{
$('#<%=GridView1.ClientID %>').find('input:checkbox:first').removeAttr('checked');
}
}
else {
$('#<%=GridView1.ClientID %>').find('input:checkbox:first').removeAttr('checked');
}
}
</script>
and the button save click event which sends this selected row cells to a database class insert method as
foreach(GridViewRow gd in GridView1.Rows)
{
if ((gd.Cells[0].FindControl("chkCheck") as CheckBox).Checked)
{
// gd.Cells[0].Visible = false;
string stId = gd.Cells[1].Text.ToString();
string fName = gd.Cells[2].Text.ToString();
string mName = gd.Cells[3].Text.ToString();
string lName = gd.Cells[4].Text.ToString();
string cumpas = gd.Cells[5].Text.ToString();
string college = gd.Cells[6].Text.ToString();
string dept = gd.Cells[7].Text.ToString();
int bl = Convert.ToInt32(gd.Cells[8].Text);
int dormNo = Convert.ToInt32(gd.Cells[9].Text);
DbCon db = new DbCon();
if (db.RegisterStud(stId, fName, mName, lName, cumpas, college, dept, bl, dormNo) == 1)
{
Label1.Text = "You Have Inserted";
}
else
{
Label1.Text = "Errror";
}
}
else { Label1.Text = "Please select a row"; }
}
but i can't find each cells value and not assigned to those string variables.
When using <asp:TemplateField>, the data is not inside Cell but is contained in the Control present inside the Cell.
row.Cells[].Text works only when using <asp:BoundField> for GridView Columns.
So, There are two steps to read the value when using <asp:TemplateField>:
Access the Control inside Cell
Access the Value from Control in step 1
I see you did the above steps to read the Checkbox value from first Column already. Follow the same for all other Columns.
if ((gd.Cells[0].FindControl("chkCheck") as CheckBox).Checked)
{
// Step 1: Access the Control inside Cell
Label lblName = (Label)gd.Cells[1].FindControl("lblStudName");
// Step 2: Access the Value from Control in step 1
string Name = lblName.Text;
// Combine Step 1 & Step 2: Access Values in one line
string Name = ((Label)gd.Cells[1].FindControl("lblStudName")).Text;
string firstName = ((Label)gd.Cells[2].FindControl("lblFirstName")).Text;
// ....same way for all Columns which use a <asp:TemplateField>
}

Gridview footer Textbox javascript call not working after two insert

I have text boxes in footer for with insert button. Called a javascript Calculate on textbox onchange() for multiplying values.
Its working fine for first two inserts. From third i am getting this error.
"Microsoft JScript runtime error: Object required"
Below is the code:
function calculate() {
var Num1 = parseFloat(document.getElementById('<%=((TextBox)gvDowntime.FooterRow.FindControl("txtAddImpactedNoEmployee")).ClientID %>').value);
var Num2 = parseInt(document.getElementById('<%=((TextBox)gvDowntime.FooterRow.FindControl("txtAddDowntimePerEmployee")).ClientID %>').value);
var Num3 = Num1 * Num2;
if (!isNaN(Num3)) {
document.getElementById('<%=((TextBox)gvDowntime.FooterRow.FindControl("txtAddTotalDowntimeImpact")).ClientID %>').value = Num3;
}
}
<asp:GridView ID="gvDowntime" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True"
EnableModelValidation="True" ShowFooter="True" Width="100%"
CellPadding="4" ForeColor="#333333" GridLines="None"
onrowdatabound="gvDowntime_RowDataBound"
onrowcommand="gvDowntime_RowCommand">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Downtime" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblEntryID" runat="server" Visible="false"></asp:Label>
<asp:Label ID="lblDowntime" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlAddDowntime" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="StartTime" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblStartTime" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlAddStartTime" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EndTime" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblEndTime" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlAddEndTime" runat="server"></asp:DropDownList>
<asp:Label ID="lblAddTimeValidation" runat="server" ForeColor="Red"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Impacted # of<BR>Employees" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblImpactedNoEmployee" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddImpactedNoEmployee" runat="server" Width="100px" Font-Size="Smaller" onchange="calculate();"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqImpact" runat="server" Display="Dynamic" Text="*"
ControlToValidate="txtAddImpactedNoEmployee" ValidationGroup="NewEntry" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator runat="server" id="rexNumber" controltovalidate="txtAddImpactedNoEmployee" ValidationGroup="NewEntry"
validationexpression="[0-9]+(\.[0-9][0-9]?)?" errormessage="<BR>Please enter number!" ForeColor="Red" Display="Dynamic"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Downtime per<BR>Employee(Mins)" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblDowntimePerEmployee" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddDowntimePerEmployee" runat="server" Width="100px" Font-Size="Smaller" onchange="calculate();"></asp:TextBox>
<asp:RequiredFieldValidator ID="req" runat="server" Display="Dynamic" Text="*"
ControlToValidate="txtAddDowntimePerEmployee" ValidationGroup="NewEntry" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator runat="server" id="rex" controltovalidate="txtAddDowntimePerEmployee" ValidationGroup="NewEntry"
validationexpression="^[0-9]+$" errormessage="<BR>Please enter number!" ForeColor="Red" Display="Dynamic"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Downtime<BR>Impact(Mins)" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblTotalDowntimeImpact" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddTotalDowntimeImpact" runat="server" Width="100px" Font-Size="Smaller" ReadOnly="true"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Production Units" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblProductionUnits" runat="server" ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddProductionUnits" Width="100px" Font-Size="Smaller" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqDowntime" runat="server" Display="Dynamic" Text="*"
ControlToValidate="txtAddProductionUnits" ValidationGroup="NewEntry" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator runat="server" id="rexProdUnit" controltovalidate="txtAddProductionUnits" ValidationGroup="NewEntry"
validationexpression="^[0-9]+$" errormessage="<BR>Please enter number!" ForeColor="Red" Display="Dynamic"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="btnDelete" runat="server" CommandName="DEL">Delete</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnInsert" runat="server" Text="Insert" ValidationGroup='NewEntry' CausesValidation='true' CommandName="insert" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" CssClass="gradientDemo" Height="35px"/>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
protected void gvDowntime_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "insert")
{
GridViewRow gvr = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
DropDownList ddlAddDowntime = (DropDownList)gvr.FindControl("ddlAddDowntime");
DropDownList ddlAddStartTime = (DropDownList)gvr.FindControl("ddlAddStartTime");
DropDownList ddlAddEndTime = (DropDownList)gvr.FindControl("ddlAddEndTime");
TextBox txtAddImpactedNoEmployee = (TextBox)gvr.FindControl("txtAddImpactedNoEmployee");
TextBox txtAddDowntimePerEmployee = (TextBox)gvr.FindControl("txtAddDowntimePerEmployee");
TextBox txtAddTotalDowntimeImpact = (TextBox)gvr.FindControl("txtAddTotalDowntimeImpact");
TextBox txtAddProductionUnits = (TextBox)gvr.FindControl("txtAddProductionUnits");
Label lblAddTimeValidation = (Label)gvr.FindControl("lblAddTimeValidation");
txtAddTotalDowntimeImpact.Text = Request.Form[txtAddTotalDowntimeImpact.UniqueID];
DowntimeEntry objEntry = new DowntimeEntry();
if (!BLL.DowntimeEntryDetail.isValidTimes(ddlAddStartTime.SelectedItem.Text, ddlAddEndTime.SelectedItem.Text))
{
lblAddTimeValidation.Text = "EndTime should be greater!";
return;
}
objEntry.Downtime = ddlAddDowntime.SelectedItem.Text;
objEntry.StartTime = ddlAddStartTime.SelectedItem.Text;
objEntry.EndTime = ddlAddEndTime.SelectedItem.Text;
objEntry.ImpactedNoEmployees = Convert.ToDouble(txtAddImpactedNoEmployee.Text);
objEntry.DowntimePerEmployee = Convert.ToInt32(txtAddDowntimePerEmployee.Text);
objEntry.TotalDowntimeImpact = Convert.ToDouble(txtAddTotalDowntimeImpact.Text);
objEntry.ProductionUnit = Convert.ToInt32(txtAddProductionUnits.Text);
objEntry.ResolutionAction = "";
objEntry.ResolutionOwner = "";
objEntry.RequestID = Convert.ToInt32(Request.QueryString["ReqID"]);
BLL.DowntimeEntryDetail.UpdateDowntimeEntryRecord(objEntry);
loadDowntimeEntry();
}
}
catch (Exception ex)
{
BLL.DowntimeSummaryDetail.AddException(ex);
}
}
public void loadDowntimeEntry()
{
try
{
bool blResolutionvisiblity = true;
listDowntimeEntry = BLL.DowntimeEntryDetail.LoadDowntimeEntryDetail(Convert.ToInt32(Request.QueryString["ReqID"]));
gvDowntime.DataSource = listDowntimeEntry;
gvDowntime.DataBind();
//if (listDowntimeEntry.FindAll(x => x.ResolutionAction == "" || x.ResolutionAction == null).Count > 0 && blResolutionvisiblity)
// lblHeader.Text = "Reporting & Resolution Pending";
//else
lblHeader.Text = "Reporting & Resolution";
if (blResolutionvisiblity)
{
gvResolution.DataSource = listDowntimeEntry;
gvResolution.DataBind();
}
//else
// panelHeader.Visible = false;
}
catch (Exception ex)
{
BLL.DowntimeSummaryDetail.AddException(ex);
}
}
protected void gvDowntime_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DowntimeEntry objEntry = (DowntimeEntry)e.Row.DataItem;
if (objEntry.Downtime == null)
{
e.Row.Visible = false;
}
else
{
Label lblDowntime = (Label)e.Row.FindControl("lblDowntime");
Label lblStartTime = (Label)e.Row.FindControl("lblStartTime");
Label lblEndTime = (Label)e.Row.FindControl("lblEndTime");
Label lblImpactedNoEmployee = (Label)e.Row.FindControl("lblImpactedNoEmployee");
Label lblDowntimePerEmployee = (Label)e.Row.FindControl("lblDowntimePerEmployee");
Label lblTotalDowntimeImpact = (Label)e.Row.FindControl("lblTotalDowntimeImpact");
Label lblProductionUnits = (Label)e.Row.FindControl("lblProductionUnits");
Label lblEntryID = (Label)e.Row.FindControl("lblEntryID");
lblEntryID.Text = Convert.ToString(objEntry.EntryID);
lblDowntime.Text = objEntry.Downtime;
lblStartTime.Text = objEntry.StartTime;
lblEndTime.Text = objEntry.EndTime;
lblImpactedNoEmployee.Text = Convert.ToString(objEntry.ImpactedNoEmployees);
lblDowntimePerEmployee.Text = Convert.ToString(objEntry.DowntimePerEmployee);
lblTotalDowntimeImpact.Text = Convert.ToString(objEntry.TotalDowntimeImpact);
lblProductionUnits.Text = Convert.ToString(objEntry.ProductionUnit);
}
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlAddDowntime = (DropDownList)e.Row.FindControl("ddlAddDowntime");
DropDownList ddlAddStartTime = (DropDownList)e.Row.FindControl("ddlAddStartTime");
DropDownList ddlAddEndTime = (DropDownList)e.Row.FindControl("ddlAddEndTime");
TextBox txtAddImpactedNoEmployee = (TextBox)e.Row.FindControl("txtAddImpactedNoEmployee");
TextBox txtAddDowntimePerEmployee = (TextBox)e.Row.FindControl("txtAddDowntimePerEmployee");
TextBox txtAddTotalDowntimeImpact = (TextBox)e.Row.FindControl("txtAddTotalDowntimeImpact");
TextBox txtAddProductionUnits = (TextBox)e.Row.FindControl("txtAddProductionUnits");
List<DownTime> listDowntime = BLL.DowntimeDetail.LoadDowntimeDetail(true);
foreach (DownTime objDowntime in listDowntime)
{
ListItem itmDowntime = new ListItem(objDowntime.DowntimeName, Convert.ToString(objDowntime.ID));
itmDowntime.Attributes.Add("Title", objDowntime.Desc);
ddlAddDowntime.Items.Add(itmDowntime);
}
List<TimeHour> listTime = BLL.TimeHourDetail.LoadTimeHourDetail(true);
foreach (TimeHour objTime in listTime)
{
ddlAddStartTime.Items.Add(new ListItem(objTime.TimeHours, Convert.ToString(objTime.ID)));
ddlAddEndTime.Items.Add(new ListItem(objTime.TimeHours, Convert.ToString(objTime.ID)));
}
}
}

Bind data to nested grid in footer

I have added programatically button to the footer in RowDataBound:
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[1].Text = "Total: ";
e.Row.Cells[2].Text = totalStaff.ToString();
Button showStaff = new Button();
showStaff.CommandName = "ShowAll";
showStaff.Text = e.Row.Cells[2].Text.ToString();
e.Row.Cells[2].Controls.Add(showStaff);
e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
showStaff.Click += new EventHandler(showStaff_Click);
}
now I want to handle showStaff_Click to bind data to nested gridview. I wrote bwlow code in RowCommand but index is null:
if(e.CommandName == "ShowAll")
{
int index = Convert.ToInt32(e.CommandArgument.ToString());
GridViewRow row = Staff.Rows[index];
GridView StaffInfo = (GridView)Staff.Rows[index].FindControl("StaffInfo");
int TeamID = 0;
int cityID = 3699;
StaffInfo.DataSource = GetStaff(cityID, TeamID);
StaffInfo.DataBind();
}
I will appreciate Your help.
EDIT:
I have nade some changes:
protected void Staff_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
//Checking for command name which command/button is pressed
if (e.CommandName == "ShowDetails")
{
GridView Staff = (GridView)sender;
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Staff.Rows[index];
GridView StaffInfo = (GridView)Staff.Rows[index].FindControl("StaffInfo");
int TeamID = Convert.ToInt16(Staff.DataKeys[index].Values[0].ToString());
int cityID = Convert.ToInt16(Staff.DataKeys[index].Values[1].ToString());
StaffInfo.DataSource = GetStaff(cityID, TeamID);
StaffInfo.DataBind();
StaffInfo.Visible = true;
}
else if(e.CommandName == "ShowAll")
{
int index = Convert.ToInt32(e.CommandArgument);
GridView StaffInfo = (GridView)Staff.Rows[index].FindControl("StaffInfo");
int TeamID = 0;
int cityID = 3699;
StaffInfo.DataSource = GetStaff(cityID, TeamID);
StaffInfo.DataBind();
StaffInfo.Visible = true;
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
<asp:GridView ID="Staff" runat="server" AutoGenerateColumns="false"
OnRowCommand="Staff_RowCommand"
DataKeyNames="TeamID,CityID" ShowFooter="True" HorizontalAlign="Center">
<Columns>
<asp:TemplateField HeaderText=" Function">
<ItemTemplate>
<asp:Label Width="150px" ID="Function" ItemStyle-HorizontalAlign="Center" runat="server" Text='<%# Bind("Function") %>'></asp:Label>
<asp:GridView ID="StaffInfo" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="FirstName" HeaderText="First Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="LastName" HeaderText="Last Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="SOEID" HeaderText="SOEID" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Team">
<ItemTemplate>
<asp:Label Width="150px" ID="Team" ItemStyle-HorizontalAlign="Center" runat="server" Text='<%# Bind("Team") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Staff Count">
<ItemTemplate>
<asp:Button Width="40px" ID="StaffCount" ItemStyle-HorizontalAlign="Center" runat="server" Text='<%# Bind("StaffCount") %>' CommandName="ShowDetails" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" CausesValidation="True" UseSubmitBehavior="False" />
</ItemTemplate>
<FooterTemplate>
<asp:Button id="TotalStaff" runat="server" Text="Button1" CommandName="ShowAll" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" CausesValidation="True" UseSubmitBehavior="False" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField Visible ="false">
<ItemTemplate>
<asp:Label runat="server" Width="150px" DataField="TeamID" HeaderText="TeamID" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible ="false">
<ItemTemplate>
<asp:Label runat="server" ItemStyle-Width="150px" DataField="CityID" HeaderText="CityID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
When I try to click the ShowAll button ite returns that index is out of range. I made Response.Write(intex.ToString()) and it returns -1. The index number in case or row is returned correctly. The problem is with footer button. Could You please help me?
You did not set CommandArgument when you crated your button.
Button showStaff = new Button();
showStaff.CommandName = "ShowAll";
showStaff.CommandArgument = e.Row.RowIndex.ToString();
showStaff.Text = e.Row.Cells[2].Text.ToString();

row.Cells[4].Text returns nothing in GridView1_SelectedIndexChanged?

I have a GridView in my page :
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" BackColor="White"
AutoGenerateColumns="False" EmptyDataText="No data available." BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4" Width="729px" ForeColor="Black"
GridLines="Vertical" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<RowStyle BackColor="#F7F7DE" />
<Columns>
<asp:TemplateField HeaderText="TransactionKey" SortExpression="TransactionKey">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewTransactionKey" runat="server" Text='<%# Bind("TextBoxTransactionKey") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewTransactionKey" runat="server" Text='<%# Bind("TextBoxTransactionKey") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="TerminalID" SortExpression="TerminalID">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewTerminalID" runat="server" Text='<%# Bind("TextBoxTerminalID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewTerminalID" runat="server" Text='<%# Bind("TextBoxTerminalID") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="MerchantID" SortExpression="MerchantID">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewMerchantID" runat="server" Text='<%# Bind("TextBoxMerchantID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewMerchantID" runat="server" Text='<%# Bind("TextBoxMerchantID") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="شماره حساب" SortExpression="شماره حساب">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewBankAccount" runat="server" Text='<%# Bind("TextBoxBankAccount") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewBankAccount" runat="server" Text='<%# Bind("TextBoxBankAccount") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="نام بانک" SortExpression="نام بانک">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewBankName" runat="server" Text='<%# Bind("BankName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewBankName" runat="server" Text='<%# Bind("BankName") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" >
<ItemStyle Font-Size="12px" />
</asp:CommandField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<PagerStyle ForeColor="Black" HorizontalAlign="Right" BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
I set the DataSource with the follwing code :
protected void Page_Load(object sender, EventArgs e)
{
try
{
LabelTitr.Text = "Add Banks";
LabelResult.Text = "";
if (Session["Username"] != null)
{
string permission = "";
bool login = PublicMethods.CheckUsernamePass(Session["Username"].ToString(), Session["Password"].ToString(), out permission);
if (!login)
{
permission = "";
Response.Redirect("../Default.aspx");
Session["Username"] = Session["Password"] = null;
return;
}
}
else
{
Response.Redirect("../Default.aspx");
Session["Username"] = Session["Password"] = null;
return;
}
if (!IsPostBack)
BindDataToGridView1();
}
catch (Exception ex)
{
LabelResult.Text = ex.Message;
}
}
void BindDataToGridView1()
{
try
{
DataSet1 dataSet = new DataSet1();
DataClasses2DataContext dbc2 = new DataClasses2DataContext();
var Definitions = dbc2.Definitions;
if (Definitions.Count() <= 0) return;
foreach (var Definition in Definitions)
{
string bankName = dbc2.Banks.Where(c => c.BankID == Definition.BankID).First().BankName;
string CheckBox = "<input name=\"CheckBoxSubmitChanges\" type=\"checkbox\" value=" + Definition.DefinitionID + " />";
dataSet.DataTableBanks.Rows.Add(bankName, Definition.BankAccount, Definition.MerchantID, Definition.TerminalID, Definition.TerminalID);
GridView1.DataSource = dataSet.DataTableBanks;
}
GridView1.DataBind();
}
catch (Exception ex)
{
LabelResult.Text = ex.Message;
}
}
and this is GridView1_SelectedIndexChanged method :
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string temp = row.Cells[4].Text;
LabelResult.Text = temp;
}
But always temp string is empty !!!
What's wrong with it ?
Thanks
If it's a TemplateField, you have to use the FindControl("control ID") option, not the text fo the cell. I count cell 4 as being a templatefield...
There is no Text as your data is stored in controls. You need to search for the control you want and pull the Text out of.
Eg:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string temp = row.Cells[4].FindControl('LabelGridViewBankName').Text;
LabelResult.Text = temp;
}
Optionally you could could key off the DataKey property if you are using it and then use it to search your datasource for the value you want.
//this will give you control over the textbox object
var field = (TextBox)(GridView1.Rows[e.RowIndex].FindControl("your_control_ID"));
//and here you can access the text
string temp = field.Text;

Categories