【问题标题】:Selected Index of GridView has the value -1 on button clickGridView 的选定索引在按钮单击时的值为 -1
【发布时间】:2014-01-24 05:55:09
【问题描述】:

我有一个GridView,每行都有一个ImageButton。我想在单击按钮时从模板字段中获取值。我在button_click 中使用了SelectedIndex

SelectedIndex 始终为-1。

我试过的代码如下。

   protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
   {
       int i = GridView1.SelectedIndex;
       Label t = (Label)GridView1.Rows[i].Cells[0].FindControl("Label1");
       Session["course"] = t.Text;
       Response.Redirect("registration.aspx");
   }

【问题讨论】:

  • 按钮的点击不一定选择行。查看图像是如何添加的,以及如何在单击图像按钮时强制选择行。
  • 我在gridview中使用了图片按钮作为模板字段。

标签: asp.net .net gridview


【解决方案1】:

在这种情况下,您可以转到行命令,您可以在其中设置图像按钮的单击事件。

Grid View Row command

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    您不会在 ButtonCLick 事件中获得 SelectedIndex

    这样试试

    protected void imgbtn_Click(object sender, EventArgs e)
    {
        try {
            // Get the button that raised the event
            LinkButton lnkbtn = (LinkButton)sender;
            // Get the row that contains this button
            GridViewRow gvRow = (GridViewRow)lnkbtn.NamingContainer;
            // Get rowindex
           int i = gvRow.RowIndex;
           Label t = (Label)GridView1.Rows[i].Cells[0].FindControl("Label1");
           Session["course"] = t.Text;
           Response.Redirect("registration.aspx");
            }
        } catch (Exception ex) {
    
        }
    }
    
    protected void grdview1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try {
            if ((e.CommandName == "ImageButton")) {
                // Get RowIndex
                int RowIndex = Convert.ToInt32(e.CommandArgument);
                // Get Row
                GridViewRow gvr = grdPhone.Rows(RowIndex);
            }
        } catch (Exception ex) 
            {
    
        }
    }
    

    ASPX:

    在网格视图中

    你需要像这样设置 CommandName 和 Argument

     <asp:TemplateField ShowHeader="false">
     <ItemTemplate>
       <asp:ImageButton ID="imgbtn" runat="server" OnClick="imgbtn_Click" CausesValidation="false" CommandName="ImageButton" CommandArgument='<%# Container.DataItemIndex %>'>Edit</asp:ImageButton >
       </ItemTemplate>
      </asp:TemplateField>
    

    【讨论】:

    • 我不认为点击会在网格视图中工作,以及当你可以在 onRowcommand 中编写所有逻辑时为什么需要它。
    猜你喜欢
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 2013-08-26
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 2015-09-05
    相关资源
    最近更新 更多