0

我在页面加载事件中绑定 Gridview 控件中的数据。

如何从 Gridview 控件获取字符串中选定列的数据?

(即)它是该表的主键,因此对于用户选择的每一行,都会有一个与其绑定的主键 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);
}
4

2 回答 2

1

做这样的事情:

编辑

向您的标记添加隐藏字段:

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

在 GridVew 的 selectedIndexChanged 事件中,将值设置为隐藏字段:

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;
}
于 2013-10-26T15:06:41.437 回答
1

您可以使用RowCommand事件。下面是我的代码示例。您应该使用DataKeys 在GridView和 give中提供按钮字段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)
                {

                }
            }
        }          
    }
于 2013-11-09T05:41:25.853 回答