在gridview中如何使用rowcommand事件作为按钮

时间:2014-07-16 06:28:17

标签: c# asp.net button gridview rowcommand

我在aspx中使用gridview,我有两个页面注册和details.aspx一旦注册完成它应该转到详细信息页面详细信息.aspx我保留了一个gridview在GV我应该使用行命令事件为一个按钮,它应该显示学生的所有结果,编辑按钮作为我使用项目模板的所有学生的最后一列。但是在行命令事件中我不知道写入的功能如果用户点击编辑它应该使用用户ID转到编辑页面,id应该是正午编辑模式,其他字段可以编辑。

details.aspx

   <asp:GridView ID="GridView3" runat="server" CellPadding="3" ForeColor="#333333" GridLines="None" AutoGenerateColumns="false"  OnRowCommand="GridView3_RowCommand" OnSelectedIndexChanged="GridView3_SelectedIndexChanged">
     <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
         <Columns>
             <asp:BoundField DataField="UserName" HeaderText="UserName" ReadOnly="True"/>
             <asp:BoundField DataField="Password" HeaderText="Password" />
             <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
             <asp:BoundField DataField="LastName" HeaderText="LastName" />
             <asp:BoundField DataField="EMail" HeaderText="Emaid-ID" />
             <asp:BoundField DataField="PhoneNo" HeaderText="Phone Number" />
             <asp:BoundField DataField="Location" HeaderText="Location" />

              <asp:TemplateField ShowHeader="False">
                <ItemTemplate>
                   <asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="Edit" CommandArgument="UserName"/>
                </ItemTemplate>          
             </asp:TemplateField> 
         </Columns>
     <EditRowStyle BackColor="#999999" />
     <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
     <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
     <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
     <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
     <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
     <SortedAscendingCellStyle BackColor="#E9E7E2" />
     <SortedAscendingHeaderStyle BackColor="#506C8C" />
     <SortedDescendingCellStyle BackColor="#FFFDF8" />
     <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
 </asp:GridView>
    </div>
</form>

details.aspx.cs

 protected void Page_Load(object sender, EventArgs e)
 {
    string connection2 = System.Web.Configuration.WebConfigurationManager.ConnectionStrings        ["connection1"].ConnectionString;
    SqlConnection con = new SqlConnection(connection2);
    con.Open();
    SqlCommand cmd = new SqlCommand("select * from User_Information", con);
    SqlDataReader rdr = cmd.ExecuteReader();
    GridView3.DataSource = rdr;
    GridView3.DataBind();
    con.Close();
}
protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
{

}


protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
{

}

}

2 个答案:

答案 0 :(得分:5)

两种方法要做到这一点

方法1

请在标记中更改这些内容

  1. 更改CommandName="EditUserName"
  2. 省略CommandArgument。我们不需要这个
  3. 代码隐藏

    protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "EditUserName")
        {
            //first find the button that got clicked
            var clickedButton = e.CommandSource as Button;
            //find the row of the button
            var clickedRow = clickedButton.NamingContainer as GridViewRow;
            //now as the UserName is in the BoundField, access it using the cell index.
            var clickedUserName = clickedRow.Cells[0].Text;
        }
    }
    

    方法2

    提供CommandArgument。您可以提供许多不同的参数,例如

    1. CommandArgument="<%# Container.DataItemIndex %>"
    2. CommandArgument="<%# Container.DisplayIndex %>"
    3. CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"the one Ali gave
    4. 现在在代码中,执行此操作

      protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
      {
          if (e.CommandName == "EditUserName")
          {            
              var clickedUserName = CustomersTable
                  .Rows[Convert.ToInt32(e.CommandArgument)]//find the row with the clicked index
                  .Cells[0]//find the index of the UserName cell
                  .Text;//grab the text
          }
      }
      

      P.S:

      1.更改CommandName的原因是,如果CommandName="Edit",它将触发RowEditing事件,这将导致此错误

        

      GridView'GridView3'触发了未处理的事件RowEditing。

      2.将Page_Load代码放在if(!IsPostBack)内,否则上述方法都无效。

答案 1 :(得分:4)

首先,您的按钮控件CommandArgument属性必须在每行中具有唯一值:

 <asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="Edit" 
             CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />

然后在GridView3_RowCommand事件后面的代码中,您将获得类似下面的代码:

protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int index = 0;
    GridViewRow row;
    GridView grid = sender as GridView;

    switch (e.CommandName)
    {
        case "Edit":
            index = Convert.ToInt32(e.CommandArgument);
            row = grid.Rows[index];

            //use row to find the selected controls you need for edit, update, delete here
            // e.g. HiddenField value = row.FindControl("hiddenVal") as HiddenField;

            break;
    }
}