grid_selected出现索引更改问题
本文关键字:问题 索引 selected grid | 更新日期: 2023-09-27 17:58:21
//aspx文件中的代码:
<html>
<body>
<form>
<asp:GridView ID="grid" runat="server" AutoGenerateColumns="False"
onselectedindexchanged="grid_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="RollID" HeaderText="RollID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:ButtonField CommandName="Select" Text="Select" />
</Columns>
</asp:GridView>
</div><br />
<asp:label ID="Label" runat="server" text=""></asp:label>
</form>
</body>
</html>
//代码隐藏文件:
protected void grid_SelectedIndexChanged(object sender, GridViewRowEventArgs e)
{
RowIndex = grid.SelectedIndex;
GridViewRow row = grid.Rows[RowIndex];
string a = row.Cells[4].Text;
Label.Text = "You selected " + a + ".";
}
问题是,虽然我可以在网格视图表单中打印数据,但当我选择一行时,我无法使用"标签"服务器控件打印出消息"You selected..etc."。
"任何人都能解决这个问题吗"。。。
不要使用SelectedIndexChanged事件。相反,使用RowCommand事件:
protected void grid_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "Select") {
int RowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = grid.Rows[RowIndex];
string a = row.Cells[4].Text;
Label.Text = "You selected " + a + ".";
}
}
MSDN链接:http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx
如何选择一行?您可能希望在网格视图上设置此属性,以便通过允许控件生成按钮来进行选择(网格视图知道):
AutoGenerateSelectButton="True"
你可以在这里看到更多的信息。当然,这不是创建命令按钮的唯一方法,但如果它不适合您的目的,您必须跟进。