开发者

Default a Null Value on DataBind

I am binding a nullable boolean column to a CheckBox. How can I default the checkbox to checked if开发者_如何学运维 the column is null, but keep the true/false value if one exists?

<asp:CheckBox ID="boolCheckBox" runat="server" Checked='<%# Bind("MyBoolColumn") %>' 


Unlike Eval apparently you can't do much with Bind, other than use a string format:

Bind("MyColumn", "{0:c}"))

The solution I found was to use the ItemCreated event

        protected void myListView_OnItemCreated(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.InsertItem)
        {
            ((CheckBox)((ListView)sender).InsertItem.FindControl("MyCheckBox")).Checked = true;
        }
    }


try this:

<asp:CheckBox ID="boolCheckBox" runat="server" "<%# (Bind("MyBoolColumn") == null? "Checked='checked'" : null %>">


Not sure if this will work, but give it a shot:

<%# If(Bind("MyBoolColumn") Is Nothing, True, Bind("MyBoolColumn")) %>


You can do at database level. Something like this:

SELECT 
MyBooleanColumn = 
Case 
When MyBooleanColumn Is Null Then 1 
Else MyBooleanColumn End
FROM YourTable


You could add a property with only a getter to your model:

public class SomeClass
{
    public bool? MyBoolColumn { get; set; }
    public bool MyBoolColumnChecked
    {
        get { return MyBoolColumn ?? true; }
    }
}

Then bind to the new property

Checked='<%# Bind("MyBoolColumnChecked") %>'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜