zxc
zxc

Reputation: 1526

GridView CheckBox Disable

I have a gridview populated by checkbox using the code below

Data Source Result:

Branch,101,102,103,104,105,106,107,108,109,110  
00001,null,null,null,null,null,null,null,null,null,null  
00016,1,1,1,1,1,0,0,0,0,0
00244,1,1,1,1,1,1,1,1,1,1



 <asp:TemplateField HeaderText="101">
                <ItemTemplate>
                    <asp:CheckBox runat="server" id="cb101" Checked='<%# Eval("101").ToString().Equals("1") %>' />
                </ItemTemplate>
           </asp:TemplateField>... and so on

enter image description here It is properly working for checkbox if if the column is 0 and 1. Now what I need to do is if the column is null the checkbox should be disabled/readonly

Upvotes: 1

Views: 2058

Answers (3)

Karl Anderson
Karl Anderson

Reputation: 34846

Another option is to use the GridView's RowDataBound event, which fires for each row bound to the grid view, like this:

Markup:

<asp:GridView runat="server" id="GridView1" OnRowDataBound="GridView1_RowDataBound" />

Code-behind:

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    // Only work with data rows, ignore header and footer rows
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        if(DataBinder.Eval(e.Row.DataItem, "Difference") == null)
        {
            CheckBox the101Checkbox = e.Row.FindControl("cb101") as CheckBox;

            // Verify the check box was found before we try to use it
            if(the101Checkbox != null) 
            {
                the101Checkbox.Enabled = false;
            }
        }
        else
        {
            if(DataBinder.Eval(e.Row.DataItem, "Difference") == "1")
            {
                CheckBox the101Checkbox = e.Row.FindControl("cb101") as CheckBox;

                // Verify the check box was found before we try to use it
                if(the101Checkbox != null) 
                {
                    the101Checkbox.Checked = true;
                }
            }
        }
    }
}

Note: Using the RowDataBound event offers the advantage of leveraging Visual Studio's Intellisense and generally catching problems as compile-time syntax errors, whereas embedded code blocks result in catching problems as run-time errors.

Upvotes: 1

afzalulh
afzalulh

Reputation: 7943

It should be something like this:

 <asp:CheckBox runat="server" id="CheckBox1" Checked='<%# Eval("101").ToString()=="1" ? true : false %>' Enabled='<%#(String.IsNullOrEmpty(Eval("101").ToString()) ? false: true) %>'/>

And it worked for me.

Upvotes: 2

AB Vyas
AB Vyas

Reputation: 2389

Try this

<asp:CheckBox runat="server" id="cb101" Checked='<%# Convert.ToString(Eval("101")) == string.Empty ? 'True' : 'False' %>' Enabled='<%# Eval("101")==null ? 'false': 'true' %>' />

Here 101 mean your column name.

Regards Amit Vyas

Upvotes: 0

Related Questions