0

How can I set in my button_Click event, visibility of button in gridView to false? All the time it give me an error:Compilation Error

Compiler Error Message: CS0103: The name 'btnTest' does not exist in the current context

 <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView2_RowDataBound"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:Button ID="Button189" OnClick="Button189_Click" runat="server" Text="odzemi svez vrganj" /> <asp:Button ID="btnTest" runat="server" CommandName="odzemi" CssClass="button2" OnClick="btnTest_Click" Text="-" Width="100px" Font-Bold="True" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> 

Following is my button event from where i want to hide button inside gridview.

 protected void Button10_Click(object sender, EventArgs e) { btnTest.Visible = true; Button189.Visible = false; } 
1
  • Your btnTest is repeated in each row in gridview with asp generated id you need to use findcontrol on each row and then set its visibility to false. Commented Jan 30, 2015 at 10:42

2 Answers 2

2

Use following code to set button visible property to True or False . The Button in gridview which will be clicked will act as sender. Doing so will give you the row id where the button is fired from and then you can find other controls and set your desired property on that particular row.

protected void Button189_Click(object sender, EventArgs e) { Button Btn = sender as Button; GridViewRow gvRow = Btn.NamingContainer as GridViewRow; int rowId = gvRow.RowIndex; Button Button189 = GridView2.Rows[rowId].FindControl("Button189") as Button; Button btnTest = GridView2.Rows[rowId].FindControl("btnTest") as Button; Button189.Visible = false; btnTest.Visible = true; } 
Sign up to request clarification or add additional context in comments.

9 Comments

You can cast sender as Button189 .
but protected void Button10_Click(object sender, EventArgs e) { } is outside of gidview
@Suprabhat give error int rowId = gvRow.RowIndex; Object reference not set to an instance of an object.
@Buba Couldn't understood what u said above "protected void...is outside of gidview". Your both buttons are inside gridview and button event will be generated from gruidview. Just give it a try, i have done such kind of thing many times in my project. If, it doesn't work lets us know here. We can resolve it in other ways.
It's ok, work..i understood you! But i want to set button189 to false from another button which is NOT in gridview.
|
1

You need to loop through the gridview rows and find the control

 foreach (GridViewRow row in grid.Rows) { if(row.RowType == DataControlRowType.DataRow) { var control = ((Button)row.FindControl("btnTest")); if (control != NULL) { ((Button)control).Visible = false; } } } 

1 Comment

now isn't give me an error, but the button is still visible :(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.