• 如何獲得GridView內LinkButton的RowIndex? (初級) (.NET) (ASP.NET)(转)


    NET 2.0就改用SqlDataSource和GridView了,LinkButtom一樣得放在TemplateField,但GridView沒有ItemCommand event,取而代之的是RowCommand event。

    14  protected void Page_Load(object sender, EventArgs e) {

    15    if (!IsPostBack)

    16      GridView1_DataBind();

    17  }

    18

    19  protected void GridView1_DataBind() {

    20    SqlDataSource1.ConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=pubs;Integrated Security=True";

    21    SqlDataSource1.SelectCommand = "SELECT TOP 10 " +

    22                                          "fname," +

    23                                          "lname " +

    24                                   "FROM employee";

    25    GridView1.DataSourceID = SqlDataSource1.ID;

    26    GridView1.DataKeyNames = new string[] { "lname" };

    27    GridView1.AutoGenerateColumns = false;

    28  }

    29

    30  protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) {

    31    if (e.CommandName == "Select") {

    32      int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;

    33      Label1.Text = GridView1.DataKeys[rowIndex].Value.ToString();

    34    }

    35  }

    36</script>

    37

    38<html xmlns="http://www.w3.org/1999/xhtml">

    39<head runat="server">

    40  <title>Untitled Page</title>

    41</head>

    42<body>

    43  <form id="form1" runat="server">

    44    <div>

    45      <asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">

    46        <Columns>

    47          <asp:TemplateField HeaderText="First Name">

    48            <ItemTemplate>

    49              <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select" Text='<%#Eval("fname")%>'></asp:LinkButton>

    50            </ItemTemplate>

    51          </asp:TemplateField>

    52        </Columns>

    53      </asp:GridView>

    54    </div>

    55    <asp:Label ID="Label1" runat="server"></asp:Label>

    56    <asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>

    57  </form>

    58</body>

    59</html>

    最難理解的應該是32行

    int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;

    e.CommandSource傳的是按下去的LinkButton,不過由於傳回的是Object,就得自行轉成LinkButton,但由於我們想知道的是RowIndex,而LinkButton是包含在GridViewRow內,所以透過NamingContainer傳回目前的GridViewRow,但傳回的是Control,所以需在轉成GridViewRow後才能有RowIndex property。

  • 相关阅读:
    Django 路由层
    HTTP协议
    Python并发编程之协程
    Django配置KindEditor
    Django Form
    pymysql模块
    javascript获取URL参数代码(网络摘抄)
    javascript 实现飘动的广告(网络收藏,转)
    游标的使用
    javascript 一个很好用的日历控件(网络收藏,转)
  • 原文地址:https://www.cnblogs.com/rooney/p/1268061.html
Copyright © 2020-2023  润新知