1
votes

i have a gridview in my asp.net application. for example

SN name Date Action

1 mike button(do something)

This is just one out of my gridview rows. I want for every row that has an empty cell, button field cell for the row should show. If there's no empty cell in that row, the button should hide. What i get with my code is that all the button visible becomes false which i do not want.

Here is my code behind

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" Height="326px" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5" style="text-align: left; margin-left: 169px" Width="1069px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowEditing="GridView1_RowEditing">                       
<Columns>
  <asp:BoundField HeaderText="S/N" DataField="SN" />
  <asp:BoundField HeaderText="First Name" DataField="FirstName" />
  <asp:BoundField HeaderText="Address" DataField="Address" />
  <asp:BoundField HeaderText="Phone Number" DataField="PhoneNumber" />
  <asp:BoundField HeaderText="Sex" DataField="Sex" />
  <asp:BoundField HeaderText="Reason" DataField="Reason" />
  <asp:BoundField HeaderText="SignIn" DataField="SignIn_Time" />
  <asp:BoundField HeaderText="SignOut" DataField="Signout_Time" />

<asp:TemplateField HeaderText="Action" Visible="True">
   <ItemTemplate>
      <asp:Button ID="out" runat="server" Text="Sign out" CommandName="SignOut"  CommandArgument='<%# Eval("SN") %>' CssClass="active"/>
   </ItemTemplate>
</asp:TemplateField>

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    for (int i =0 ; i < e.Row.Cells.Count; i ++)
    {
      if (e.Row.Cells[i].Text == "&nbsp;")
      {
        Button status = (Button)e.Row.FindControl("out");
        status.Visible = true;
      }
      else
      {
        Button status = (Button)e.Row.FindControl("out");
        status.Visible = false;
      }
    }
  }  
}
2
Maybe e.Row.Cells[i].Text == "&nbsp;" is never true? When you debug this, what is the actual text values for empty cells? Wouldn't it be empty?David

2 Answers

1
votes

try with this code

string.IsNullOrEmpty(e.Row.Cells[i].Text)

or

e.Row.Cells[i].Text.Equals("&nbsp;")
0
votes

What you are doing is checking all cells inside entire grid. The fix is to check all cells inside each RowDataBound event.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var status = (Button) e.Row.FindControl("out");
        // Show button if at least one cell is empty.
        status.Visible = e.Row.Cells.Cast<TableCell>()
            .Any(cell => string.IsNullOrEmpty(cell.Text));
    }
}

Normally, database should not return &nbsp; for empty data, unless you intentionally store them in database.