在gridview之外获取Gridview RowIndex

时间:2013-07-22 02:10:16

标签: c# asp.net

我的Button1位于Panel内部,我想访问rowindex,以便隐藏Imagebutton。但是当我进入调试模式时,GridView1.SelectedIndex具有空值。请求帮助!

  protected void Button1_Click1(object sender, EventArgs e)
    {

        foreach (GridViewRow row in GridView1.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                if (row.RowIndex == Convert.ToInt32(GridView1.SelectedIndex))
                {
                    ImageButton StopButton = (ImageButton)row.FindControl("stopImageButton");
                    ImageButton StartButton = (ImageButton)row.FindControl("startImageButton");
                    StopButton.Visible = true;
                    StartButton.Visible = false;          
                }
            }
        }

        this.StopTimeNotesPanel_ModalPopupExtender.Hide();
    }

2 个答案:

答案 0 :(得分:2)

你说按钮在面板内。为了能够有效地处理GridView事件,请使用Gridview内部的按钮。

如果您仍想在面板中使用按钮,则

1。)首先在Gridview中添加一个选择按钮。使用选择按钮和

选择一行

2。)单击Panel中的按钮。

仅当您选择了一行网格视图时才设置GridView.SelectedIndex。有两种方法可以:

1。)将AutoGenerateSelectButton属性设置为true。

<asp:gridview id="CustomersGridView" 
       datasourceid="CustomersSource" 
       autogenerateselectbutton="True"
       runat="server">

2。)在gridView的section部分中添加一个buttonField:

<asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="false"
        runat="server">
       <columns>
          <asp:buttonfield buttontype="Button" 
            commandname="Select"
            headertext="Select Customer" 
            text="Select"/>
          <asp:boundfield datafield="CompanyName" 
            headertext="Company Name"/>
       </columns>
</asp:gridview>

现在选择了一行后,将触发两个GridView事件: selectedindexchanging&amp;的SelectedIndexChanged。

仅在需要时,执行以下步骤以获取SelctedIndexChangedEvent中的SelectedRow

void CustomersGridView_SelectedIndexChanged(Object sender, EventArgs e)
  {

    // Get the currently selected row using the SelectedRow property.
    GridViewRow row = CustomersGridView.SelectedRow;
    MessageLabel.Text = "You selected " + row.Cells[2].Text; // just for Display

  }

现在,在按钮点击事件中,获取所选索引:

protected void Button1_Click1(object sender, EventArgs e)
{
     int i = CustomersGridView.SelectedIndex;
}

答案 1 :(得分:0)

foreach循环的代码:

ImageButton StopButton = (ImageButton)row.FindControl("stopImageButton");
ImageButton StartButton = (ImageButton)row.FindControl("startImageButton");
StopButton.Visible = true;
StartButton.Visible = false;