How to programmatically add a button to gridview and assign it to a specific function with a code lock?

At run time, I create a DataTable and use nested for-loops to populate the table. This table, which I later designate as a DataSource for gridview, and in RowDataBound, I assign a value to each cell. I want to know how I can give each cell a button and assign this button to the codebehind function. I will have 12 buttons, and each of them will contain a different value. I would prefer that they all call the same function with some kind of event that stores a cell-specific value.

This is the table creation code:

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)
        {
            /*This is where I'd like to add the button*/
            //e.Row.Cells[i].Controls.Add(new Button);
            //e.Row.Cells[i].Controls[0].Text = specific value from below

            //This is where the specific value gets input
            e.Row.Cells[i].Text = diceTable.Rows[e.Row.RowIndex][i].ToString();
        }

    }
}

I would like to handle buttonclick with something like this:

protected void DiceButton_Click(int column, int row, int value)
{
    //Do whatever
}

Any suggestions?

+3
3

gridview CommandArgument , ( gridviewrow) .

 <asp:Button ID="lbnView" runat="server" Text="Button" OnClick="btn_Clicked" 
CommandArgument="<%# ((GridViewRow)Container).RowIndex %>"></asp:Button>

, ,

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);
        }
    }
}

,

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
     }
   }
}
+7

, . , , "" , , , , , .

ASP.NET , Button . Init CreateChildControls.

, . , RowDataBound , .

+3

The easiest way to do this is to simply add a column to your GridView (you can use a button, not a hyperlink, if you want):

<Columns>
 <asp:HyperLinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="~/pUser.aspx?field={0}" HeaderText="Select" Text="Select" />

-1
source

Source: https://habr.com/ru/post/1736340/


All Articles