如何从asp:BoundField获取GridView值?

时间:2014-04-07 22:52:08

标签: c# asp.net gridview

我有GridViewDataSource检索连接两个表的值,我需要在代码隐藏中获取这些值并将其作为String传递。关于什么是最好的方法的任何想法?以下是我在aspx中的GridView

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataSourceID="SqlDsPoNumber" EnableModelValidation="True" Visible="True" 
        DataKeyNames="PO_NUMBER,SITE_NAME">
        <Columns>
            <asp:BoundField DataField="PO_NUMBER" HeaderText="PO_NUMBER" 
                SortExpression="PO_NUMBER" />
            <asp:BoundField DataField="SITE_NAME" HeaderText="SITE_NAME" 
                SortExpression="SITE_NAME" />
        </Columns>
</asp:GridView>

3 个答案:

答案 0 :(得分:18)

foreach (GridViewRow gr in GridView1.Rows)
{

   string cell_1_Value= GridView1.Rows[gr.RowIndex].Cells[0].Text; 
   string cell_2_Value= GridView1.Rows[gr.RowIndex].Cells[1].Text; 

}

答案 1 :(得分:3)

foreach (GridViewRow gr in userGrid.Rows)
{
    CheckBox check = (CheckBox)gr.FindControl("chkSelect");
    if (check.Checked == true)
    {
        string order = userGrid.Rows[gr.RowIndex].Cells[3].Text;
        gl.updatetracking (order);
    }
}

答案 2 :(得分:1)

如您所知,网格视图有多行。所以你可以从任何行中获取值。

使用数据键获取它:

var ponumber = GridView1.DataKeys[rowIndex].Values[0].ToString();
var sitename = GridView1.DataKeys[rowIndex].Values[1].ToString();

通过细胞获取:

// easiest way, but not the most recommended.
var ponumber = GridView1.Rows[rowIndex].Cells[0].Text; // try 0 or 1

您还可以在行数据绑定事件中获取数据:

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
     if(e.Row.RowType == DataControlRowType.DataRow)
     {
       var ponumber = GridView1.DataKeys[e.Row.RowIndex].Values[0].ToString();
       var sitename = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();
     }
}