【问题标题】:How to get a CheckBoxField from a DetailsView如何从 DetailsView 中获取 CheckBoxField
【发布时间】:2017-03-23 17:53:05
【问题描述】:

我已经尝试了几个小时来解决这个问题。好难过!我的ascx 的结构是这样的

<asp:DetailsView ...>
    <Fields>
        .
        .
        <asp:CheckBoxField DataField="ThingEnabled" HeaderText="Thing Enabled"/>
        .
        .
        .
    </Fields>
</asp:DetailsView>

我想要的元素是ThingEnabled 一个。

设置:

DetailsView dv = (DetailsView)sender;
CheckBoxField cbf = ????

注意CheckBoxFields 没有ID 属性,所以我不能使用FindControl

【问题讨论】:

    标签: c# asp.net .net webforms ascx


    【解决方案1】:

    请注意,DetailsView 使用其上的单元格而不是其拥有的每一行的控件 ID,因此您可以使用行、单元格和控件位置获取 CheckBoxField 值,如下所示:

    // Page_Load is just an example event here, change to any event you need
    protected void Page_Load(object sender, EventArgs e)
    {
        DetailsView dv = sender as DetailsView;
    
        // the checkbox uses checked state as its value to be passed
        // n = row/cell/control indexes where CheckBoxField has bound into, starting from 0
        // e.g. dv.Rows[0].Cells[0].Controls[0] as CheckBox
        bool checkboxvalue = (dv.Rows[n].Cells[n].Controls[n] as CheckBox).Checked;
    }
    

    如果您仍想使用FindControl,请使用ItemTemplate 包装元素并在其上创建CheckBox 控件(请注意,您可能需要在TemplateField 之上使用BoundFieldDataField="ThingEnabled"数据绑定):

    <asp:DetailsView runat="server" ...>
        <Fields>
            ...
            <asp:TemplateField HeaderText="Thing Enabled">
                <ItemTemplate>
                    <asp:CheckBox ID="ThingEnabled" runat="server" Checked="<%# Bind("ThingEnabled") %>">
                    </asp:CheckBox>
                </ItemTemplate>
            </asp:TemplateField>
        </Fields>
    </asp:DetailsView>
    

    然后您可以使用FindControl 访问该复选框控件:

    DetailsView dv = sender as DetailsView;
    
    // n = row/cell indexes, starting from 0
    bool checkboxvalue = (dv.Rows[n].Cells[n].FindControl("ThingEnabled") as CheckBox).Checked;
    

    参考/类似问题:

    How to get value from DetailsView Control in ASP.NET?

    Get the value of a BoundField from a DetailsView

    Accessing DetailsView check box value

    【讨论】:

    • Checked='&lt;%# Bind("ThingEnabled") %&gt;' - 如果您不将属性用单引号括起来,您将收到一条错误消息,指出标签格式错误。
    【解决方案2】:

    也可以通过这种方式使用 linq 获取 DetailsView 中的任何字段。

    // Page_Load is just an example event here, change to any event you need
    protected void Page_Load(object sender, EventArgs e)
    {
        DetailsView dv = sender as DetailsView;
    
        //using linq to get the CheckBoxField control
        var field = dv.Fields.Cast<DataControlField>().Single(x => x.HeaderText == "TitleOfCheckboxField") as CheckBoxField;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多