C# 简单从asp.net web应用程序的gridview中选择一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11164878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple Selecting a row from gridview in asp.net web application
提问by TBogdan
I know this question had been asked a hundred times, but I have difficulties implementing different solutions.I need to retrieve a selected row from a grid view in asp.net web application C#.I've done the databinding.I don't want to use edit/update buttons or checkboxe/radio button, just to select it by clicking on the row.Please help, I'm a little stuck, and I would like not to implement javascript based solutions.Thanks.
我知道这个问题已被问过一百次,但我在实施不同的解决方案时遇到了困难。我需要从 asp.net web 应用程序 C# 的网格视图中检索选定的行。我已经完成了数据绑定。我不想要使用编辑/更新按钮或复选框/单选按钮,只需通过单击行来选择它。请帮助,我有点卡住了,我不想实现基于 javascript 的解决方案。谢谢。
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("OnMouseOver", "this.style.cursor='pointer';this.style.textDecoration='underline';");
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.ToolTip = "Click on select row";
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(this.SingleSelectGrid, "Select$" + e.Row.RowIndex);
LinkButton selectbutton = new LinkButton()
{
CommandName = "Select",
Text = e.Row.Cells[0].Text
};
e.Row.Cells[0].Controls.Add(selectbutton);
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(selectbutton, "");
}
采纳答案by Thousand
if i get it right, this should do what you want:
如果我做对了,这应该做你想做的:
.aspx:
.aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" onselectedindexchanged="GridView1_SelectedIndexChanged">
code behind:
后面的代码:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int index = Convert.ToInt16(GridView1.SelectedDataKey.Value);
}
this should do what you want..index will give you the selected row ID, provided by the DataKeyNamesattribute in your .aspx page. This however does require the "Enable Selection" to be checked. (Go to your .aspx page, designer, click your gridview, you should see the "Enable selection" attribute).
这应该做你想要的..index 会给你选定的行 ID,由DataKeyNames你的 .aspx 页面中的属性提供。然而,这确实需要检查“启用选择”。(转到您的 .aspx 页面,设计器,单击您的 gridview,您应该会看到“启用选择”属性)。
回答by Saad Qureshi
If you are adding a DataSourcefrom code behind file then you have to set property called "AutoGenerateSelectButton" to True. This will enable you to select a row.
如果您 从代码隐藏文件添加数据源,则必须将名为“ AutoGenerateSelectButton”的属性设置为True。这将使您能够选择一行。

