2014-04-07 85 views
6

我有一個GridView,從一個DataSource連接兩個表中檢索值,我需要得到這些值在代碼隱藏,並通過他們的String。任何關於什麼是最好的方法的想法?下面是我的GridView in aspx:如何從ASP獲得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> 

回答

12
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

如您所知,網格視圖有多行。所以你可以從任何行中獲取值。

獲取它使用數據鍵:

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(); 
    } 
} 
2
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); 
    } 
}