buba
buba

Reputation: 59

Adding buttons in DataRow in DataTable

I have dynamically created DataTable to bind the GridView. I have two buttons, their visibility is set to false. I want when I add a new row on button click I want one of the buttons to be set visibility=true in that new row, and the other one button to stay visibility=false. So the button should be visible only for the row which the user adds, not visible in all rows in DataTable. Here is my code, I don't have any idea how to fix this. Please help

Markup:

  <asp:GridView ID="GridView2"  runat="server" OnRowDataBound="GridView2_RowDataBound">
        <Columns>
    <asp:TemplateField>
    <ItemTemplate>

             <asp:Button ID="Button189" Visible="false" OnClick="Button189_Click" runat="server" Text="odzemi svez vrganj" />

             <asp:Button ID="btnTest" Visible="false"   runat="server" CommandName="odzemi" CssClass="button2" OnClick="btnTest_Click" Text="-" Width="100px" Font-Bold="True" />

         </ItemTemplate>
    </asp:TemplateField>

            </Columns>
                   </asp:GridView>

Code behind:

 protected void Button5_Click(object sender, EventArgs e)
    {
        MethodForAddFirstRow();
       //Here i need somehow to set bnTest to be visible only for this row,other button to stay invisible
    }
    protected void Button5_Click(object sender, EventArgs e)
    {
        MethodForAddSecondRow();
       //Here I need somehow to set Button189 to be visible only for this row,other button to stay invisible
    }

Upvotes: 0

Views: 1347

Answers (1)

Hossam Barakat
Hossam Barakat

Reputation: 1399

In order to handle events of buttons inside grid you need to use OnRowCommand so you need to update your grid to be like the following

<asp:GridView ID="GridView2"  runat="server" OnRowDataBound="GridView2_RowDataBound" onrowcommand="gv_RowCommand">

and make sure that each button has CommandName attribute like the following

<asp:Button ID="Button189" Visible="false" OnClick="Button189_Click" runat="server" Text="odzemi svez vrganj" CommandName="Command1" />

<asp:Button ID="btnTest" Visible="false"   runat="server" CommandName="Command2" CssClass="button2" OnClick="btnTest_Click" Text="-" Width="100px" Font-Bold="True" />

then create the following event handler inside the code behind

 void gv_RowCommand(Object sender, GridViewCommandEventArgs e)
  {
     if(e.CommandName=="Command1")
     {
     }
     else if(e.CommandName=="Command2")
     {
     }
  }

In order to access buttons inside the rowcommand event handler you can use the following

GridView customersGridView = (GridView)e.CommandSource;
GridViewRow row = customersGridView.Rows[index];
Button btn = (Button)row.FindControl("Button189");
btn.Visible=false;

Upvotes: 1

Related Questions