asp.net|[ASP.NET]GridView触发SelectedIndexChanged事件


首先在GridView中必须加上“选择”的按钮,然后在Page_Load中添加
view plain copy to clipboard print ?

  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. gvTest.SelectedIndexChanged+=new EventHandler(GridView1_SelectedIndexChanged);
  4. }
protected void Page_Load(object sender, EventArgs e) { gvTest.SelectedIndexChanged+=new EventHandler(GridView1_SelectedIndexChanged); } 最后在点击绑定的GridView项的时候就可以触发SelectedIndexChanged事件了。
这里我把“选择”按钮设置成了TemplateField,然后让它的Text绑定Email字段,数据库的其余字段也可以绑定到GridView上,但是在这个程序里我把他们的可见属性都设置成了False。
页面代码:
view plain copy to clipboard print ?
  1. "overflow-y: auto; width: 100%; height: 100%">
  2. "gvTest" runat="server" AutoGenerateColumns="False"
  3. DataKeyNames="UserId" DataSourceID="SqlDataSource1" ShowHeader ="false">
  4. "UserId" HeaderText="UserId" InsertVisible="False"
  5. ReadOnly="True" SortExpression="UserId" Visible="False" />
  6. "EMail" HeaderText="EMail" SortExpression="EMail"
  7. Visible="False" />
  8. "Passwd" HeaderText="Passwd" SortExpression="Passwd"
  9. Visible="False" />
  10. "LastLogin" HeaderText="LastLogin"
  11. SortExpression="LastLogin" Visible="False" />
  12. "False">
  13. "LinkButton1" runat="server" CausesValidation="False"
  14. CommandName="Select" Text=''>


  15. "lblRegionCaption" runat="server" Text="Label">

  16. "SqlDataSource1" runat="server"
  17. ConnectionString=""
  18. SelectCommand="SELECT [UserId], [EMail], [Passwd], [LastLogin] FROM [Users]">



在页面中加入了垂直滚动条。

【asp.net|[ASP.NET]GridView触发SelectedIndexChanged事件】SelectIndexChenged事件的代码:
view plain copy to clipboard print ?
  1. protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
  2. {
  3. int index = GridView1.SelectedIndex;
  4. string ID = GridView1.SelectedDataKey.Values["UserId"].ToString();
  5. lblRegionCaption.Text = ID;
  6. GridViewRow row = GridView1.SelectedRow;
  7. }

    推荐阅读