Rooney Rooney - 1 month ago 13
SQL Question

Disable gridview rows based on database table column value

I have a gridview which is being loaded from database table.
There is one column in the table named 'valid',whose values are 'Y' or 'N'.
Now, what I want to do is, to check if the value of 'valid' is Y, then the whole record in that row should appear as disabled when loading the gridview.

How to proceed with that? should I write a procedure for this or it can be done from code behind?

Note: the column Valid is not a part of gridview.

Answer

You need to use RowDataBound event of gridview to disable rows.
Note that if you use databound columns then it is rendered in tr and td then you need to find the cell and then set the disable property.

protected void gvEntity_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
       //CheckBox cbAttachClrReq = (CheckBox) e.Row.FindControl("chkAdd");
       //check the value here and set enable property
       e.Row.Enabled = false;

    }

}

As @Hanlet Escaño has suggested you can add the field value in the same column as follows

<asp:TemplateField>
   <ItemTemplate>
      <<asp:Label ID="lbl1" runat="server" 
             Value='<%# Eval("Name") %>' />
      <asp:HiddenField ID="HiddenField1" runat="server" 
             Value='<%# Eval("valid") %>' />
</ItemTemplate>

and get the hidden field value in row-databound event as follows

protected void gvEntity_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
       HiddenField Hf = (HiddenField) e.Row.FindControl("HiddenField1");
       if(Hf.Value=="Y")
           e.Row.Enabled = false;

    }

}
Comments