问题描述:

I have used grid view in my ASP.NET application.

 <asp:GridView ID="grdView" runat="server">

<Columns>

<asp:TemplateField>

<ItemTemplate>

<asp:CheckBox ID="chkbox" runat="server" />

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Jurisdiction">

<ItemTemplate>

<asp:Label ID="lblJurisdiction" runat="server" />

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="License Number">

<ItemTemplate>

<asp:TextBox ID="txtLicenseNumber" runat="server" />

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

in cs file

 protected void btnSave_Click(object sender, EventArgs e)

{

foreach (GridViewRow row in grdView.Rows)

{

for (int i = 0; i < grdView.Columns.Count; i++)

{

String cellText = row.Cells[i].Text;

}

}

}

Note that the above grid will be populated by data. Now I need to get data from already populated gridview. The above code is not working. Also I need to retrieve from labels, textboxes, checkboxes values inside grid. Please help !!!

网友答案:

You can use FindControl method to retrieve the control's data:-

protected void btnSave_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in grdView.Rows)
    {
        CheckBox chkbox = row.FindControl("chkbox") as CheckBox;
        Label lblJurisdiction = row.FindControl("lblJurisdiction") as Label;
        ..and so on

        //Finally retrieve the data like your normal control
        string labelText = lblJurisdiction.Text;
    }
}
网友答案:

Use GridViewRow.FindControl method.

foreach (GridViewRow row in grdView.Rows)
{
    // return you the check-box control from current row
    var chkbox = row.FindControl("chkbox");
}
网友答案:

Check whether the row type is DataControlRowType.DataRow.

 protected void btnSave_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in grdView.Rows)
        {       
             if (row.RowType == DataControlRowType.DataRow)
            {               
                for (int i = 0; i < grdView.Columns.Count; i++)
                {
                    String cellText = row.Cells[i].Text;
                }
            }
        }
      }

To get the TextBox, CheckBox value from the grid use this,

string TextBoxvalue = ((TextBox)GridViewID.Rows[i].FindControl("TextBoxName")).Text; 
string CheckBoxvalue = ((CheckBox)GridViewID.Rows[i].FindControl("CheckBoxName")).Text; 
网友答案:

In your code .cs file, you are missing to check only for datarow. As it will check all 3 places:-

1. Header
2. Body
3. Footer

Might any one place, any exception can occur.

Please add one more if condtion just after the for loop, as below.

if (row.RowType == DataControlRowType.DataRow) {

Hope this post will help's you :).

网友答案:

Use cells[i].EditedFormatedValue

相关阅读:
Top