开发者

ASP.NET CheckBoxField - setting value question

I trying to pass some values that the user selects but I am unable to set the CheckBoxField in my gridview.

Could someone please let me know how to do this?

Here is my code so far...

<asp:GridView ID="GridView1" SkinID="CompacGrid" runat="server" AutoGenerateColumns="False"
            DataSourceID="ObjectDataSource1" Width="400px" AllowPaging="True" BackColor="White" 
                                BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" 
                                GridLines="Vertical">
            <RowStyle BackC开发者_Python百科olor="#EEEEEE" ForeColor="Black" />
            <Columns>


                    <asp:CheckBoxField headertext="mm" />

Thank you,

Steve


For some reason, Microsoft omitted the 'Value' property from its specification for CheckBox in ASP.NET, despite it being a completely valid feature of HTML. My guess is that they wanted it to be as similar to the WinForms CheckBox as possible (which also lacks a 'Value' property).

If you want to give your <asp:CheckBox /> or <asp:CheckBoxField /> a 'Value' property you will either have to extend the control yourself and define a custom 'Value' property, or make use of the code-behind to populate the Attributes or InputAttributes collection of the control. See this article for more details.

cbMyCheckBoxField.Attributes.Add("Value", "foo");

or

cbMyCheckBoxField.InputAttributes.Add("Value", "foo");

The main difference between these two approaches is that the former will not include the Value in the generated HTML (only ViewState), while the latter will.


Try setting the DataField attribute based on a boolean condition on the datasource object. It appears you're binding to an ObjectDataSource. Perhaps there's a boolean condition on the class -- say it's IsHired.

Perhaps something like:

     <asp:CheckBoxField headertext="mm" DataField="IsHired" />

There's a sample on the MSDN CheckBoxField article.


To add onto Nathan's answer: I would use the RowDataBound event for your GridView. Assuming you bound to a DataTable, with the interesting column being [0].

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //Check for a data row
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //Find the checkbox control by ID and set it.
        ((CheckBox)e.Row.FindControl("CheckBoxId")).Checked = IsItemChecked(((DataRowView)e.Row.DataItem)[0]);
    } 
}

The IsItemChecked function can be passed the data from the DataItem to create custom logic that passes back a boolean. Once you have the control, you can also add attributes to it. This is a powerful technique once you master it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜