2013-10-26 79 views
0

我在頁面加載事件中的Gridview控件中綁定數據。如何從gridview中獲取字符串中的選定列的數據

如何從Gridview控件的字符串中獲取選定列的數據?

(ie)它是該表的主鍵,所以對於用戶選擇的每一行,都會有一個主鍵ID列綁定到它。因此,我需要使用此ID獲取ID &,我需要鏈接到我的Web應用程序的下一頁。

使用Visual Studio 2005 asp.net C#2.0。

下面是一些代碼我試過的:

protected void SubmitButton_Click(object sender, EventArgs e) 
{ 
string bS = Convert.ToString(gridview1.Rows[rowIndex].Cells[2].Text); 
} 
+2

使用GridView的SelectedRow屬性。以下鏈接有一些方法可以讓你的工作更好地解釋。 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.selectedrow.aspx –

+0

發表你的gridview代碼!有很多選項可以用來說Selected Row屬性,RowCommand等等。 –

回答

1

做這樣的事情:

編輯

隱藏字段添加到您的標記:

<asp:HiddenField ID="hdnID" runat="server" /> 
<asp:GridView ID="GridView1" runat="server" 
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"> 
... ... ... ... ... ... ... ... ... ... ... ... 

在GridVew的selectedIndexChanged事件上,在vallue設置爲隱藏字段:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    GridViewRow row = GridView1.SelectedRow; 
    hdnID.Value = row.Cells[2].Text; 
} 

在按鈕事件從隱藏的領域獲得的價值:

protected void SubmitButton_Click(object sender, EventArgs e) 
{ 
    string bS = hdnID.Value; 
} 
+0

此代碼提取所需列的每個值,而不是gridview中只有選定行的一個值 – kumartyr

+0

我編輯了我的答案。 – afzalulh

+0

是的,這是我通常做的。我甚至有幾個複選框,並通過網格循環僅抓取複選框中的名稱。 –

1

可以使用RowCommand事件。以下是我的代碼示例。您應該使用DataKey s來提供GridView中的按鈕字段並給出CommandName = Select

protected void GridView_AccGroups_RowCommand(object sender, GridViewCommandEventArgs e) 
    { 
     if (e.CommandName == "Select") //commandName given to the button field in the Gridview 
     { 

      foreach (GridViewRow i in GridView_AccGroups.Rows) //takes each Gridview Row..my Gridview name is 'GridView_AccGroups' 
      { 
       try 
       { 
        int index = Convert.ToInt32(e.CommandArgument); // gets the selected Index 
        GridViewRow selectedRow = GridView_AccGroups.Rows[index]; // with the selected index gets the selected Row 
        string txtAccGroupName = GridView_AccGroups.DataKeys[index].Values["Account Group"].ToString(); // DataKey Names are given in the Gridview Properties..!! each key name in one line,these key names are column names in the result of the select query that is bound to the Gridview, 
        string txtAccGroupShortName = GridView_AccGroups.DataKeys[index].Values["Short Name"].ToString(); 

        string txtAccGroupRemarks = GridView_AccGroups.DataKeys[index].Values["Remarks"].ToString(); 
        string id = GridView_AccGroups.DataKeys[index].Values["ID"].ToString(); 

        string = GridView_AccGroups.DataKeys[index].Values["Parent Group ID"].ToString(); 
       } 
       catch (Exception ex) 
       { 

       } 
      } 
     }   
    } 
+0

你能評論和格式化你的代碼嗎? – user35443

+0

我已經編輯我的代碼,正如你所說的..!希望它可以幫助你..! –

相關問題