I have a Gridview with two buttons and I want to be able to run code when the user clicks on them. I have tried using Row_command and setting a CommandName on the buttons , but i am going round in circles! Help!

I cant seem to get the username name from the first cell in order to search for the user in the rowcommand:

protected void gridview_search_RowCommand(object sender, 
    GridViewCommandEventArgs e)
{
   if (e.CommandName == "unlock_account")
   {
      string user = gridview_search.SelectedRow.Cells[0].ToString();  

      //run code when user is obtained 
   }
}
有帮助吗?

解决方案 3

My syntax was wrong for the command name part. I finally figured it out and then was able to get selected value from the gridview using DataKeys and was then able to send this value to unlock user account.

    protected void gridview_search_RowCommand(object sender, 
    GridViewCommandEventArgs e)
{
   if (e.CommandName.CompareTo("unlock_account") == 0)
   {
      int user = (int)gridview_search.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;

      //unlock account method
      userObj.unlockAccount(user);

      }
}

其他提示

should be able to set the event-handlers for those buttons to whichever function you are trying to run.

dgvbutton1.clickevent = dosomething();
dgvbutton2.clickevent = dosomething();

something along those lines should work

 <asp:TemplateField>
  <ItemTemplate>
    <asp:Button ID="AddButton" runat="server" 
      CommandName="AddToCart" 
      CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
      Text="Add to Cart" />
  </ItemTemplate> 
</asp:TemplateField>    

      protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
      {
          if (e.CommandName == "AddToCart")
          {
              // Retrieve the row index stored in the 
              // CommandArgument property.
              int index = Convert.ToInt32(e.CommandArgument);

              // Retrieve the row that contains the button 
              // from the Rows collection.
              GridViewRow row = GridView1.Rows[index];

              // Add code here to add the item to the shopping cart.
          }
      }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top