Few days back i came across a question in the forum, the question was to set the visibility of the Button based on the column value. If the value of all the cells in a column is false, button should be visible otherwise it should be hidden.
Let's see how we can achieve this.
Step 1: Add a GridView and a Button in the page.
<asp:GridView ID="GridView1" OnRowDataBound="GridView1_DataBound" runat="server" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="ID" HeaderText="ID" /> <asp:BoundField DataField="Status" HeaderText="Status" /> </Columns> </asp:GridView> <asp:Button ID="btnDisplay" runat="server" Text="Success" Visible="false" />
Step 2: Declare a class level boolean variable
Boolean flag = false;
Step 3: Bind the GridView with data on Page_Load using GetData() method. protected void Page_Load(object sender, EventArgs e) { GridView1.DataSource = GetData(); GridView1.DataBind(); } private DataTable GetData() { DataTable dt = new DataTable("Data"); dt.Columns.Add(new DataColumn("ID")); dt.Columns.Add(new DataColumn("Status")); dt.Rows.Add(1, "false"); dt.Rows.Add(2, "false"); dt.Rows.Add(3, "false"); return dt; } Step 4: In GridView1_DataBound, check the value of each cell of Status column, set the value of class level flag variable
protected void GridView1_DataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if (e.Row.Cells[1].Text.Equals("true")) { flag = true; } } }
Step 5: On Page_PreRender set the visibility of the button based on the class level flag variable.
protected void Page_PreRender(object sender, EventArgs e) { if (!flag) { btnDisplay.Visible = true; } }
This ends the article. Live Demo
|