How do I programmatically add a button to a gridview and assign it to a specific code-behind function?

前端 未结 3 548

In runtime I\'m creating a DataTable and using nested for-loops to populate the table. This table I later assign as DataSource to a gridview and on RowDataBound I assign the

3条回答
  •  醉梦人生
    2020-12-10 10:06

    On your gridview in markup, assign CommandArgument attribute to whichever you want (here I choose the index of the current gridviewrow) inside the your buttons.

     
    

    Or in your code behind, you can create a button like below

    protected void GridViewDice_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
    
    
        DataTable diceTable = _gm.GetDice(_gameId); 
        for (int i = 0; i < GameRules.ColumnsOfDice; i++) 
        { 
            if(e.Row.RowIndex > -1) 
            { 
                Button btn = new Button();
                btn.CommandArgument = diceTable.Rows[e.Row.RowIndex][i].ToString(); 
                btn.Attributes.Add("OnClick", "btn_Clicked");
    
                e.Row.Cells[i].Controls.Add(btn);
            }
        }
    }
    

    then make an event handler like below

    protected void btn_Clicked(object sender, EventAgrs e)
    {
       //get your command argument from the button here
       if (sender is Button)
       {
         try
         {
            String yourAssignedValue = ((Button)sender).CommandArgument;
         }
         catch
         {
           //Check for exception
         }
       }
    }
    

提交回复
热议问题