【问题标题】:generating new column in grid view for checkbox column在网格视图中为复选框列生成新列
【发布时间】:2013-02-07 15:04:29
【问题描述】:

我正在使用数据表作为网格视图的数据源

     DataTable table = new DataTable();
    table.Columns.Add("Dosage", typeof(int));
    table.Columns.Add("Drug", typeof(string));
    table.Columns.Add("Patient", typeof(string));
    table.Columns.Add("Select",typeof(bool));


    //
    // Here we add five DataRows.
    //
    table.Rows.Add(25, "Indocin", "David");
    table.Rows.Add(50, "Enebrel", "Sam");
    table.Rows.Add(10, "Hydralazine", "Christoff");
    table.Rows.Add(21, "Combivent", "Janet");
    table.Rows.Add(100, "Dilantin", "Melanie");


    GridView2.DataSource = table;


    GridView2.DataBind();   

在页面加载时 我想在网格中创建新列以添加单选按钮

实际上我想为数据库中选定的复选框提交行值..

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    如果您想向GridView 添加一个新列,您应该将它添加到它的DataSource。通过从数据库中选择另一列,或者,如果您在此处使用内存中的DataTable,则添加另一个DataColumn。但我假设您已经添加了该列(Select)。

    然后使用TemplateField 添加RadioButton 并将其评估/绑定到列。

    <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView2_RowDataBound" >
             <Columns>
                <asp:TemplateField HeaderText="Select">
                      <ItemTemplate>
                         <asp:RadioButton ID="rbSelect"   runat="server" />
                      </ItemTemplate>
                </asp:TemplateField>
    

    可以根据数据源使用RowDataBound查看:

    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var rbSelect = (RadioButton)e.Row.FindControl("rbSelect");
            var row = ((DataRowView)e.Row.DataItem).Row;
            rbSelect.Checked = row.Field<bool>("Select");
        }
    }
    

    【讨论】:

    • 当我使用项目模板添加单选按钮时.. 然后数据表无法添加为我需要的数据源 bcz 我将在循环中添加随机行。
    • @InderpalSingh:您可以将其用作数据源。只需设置AutoGenerateColumns=False 并手动为标记中的每一列添加TemplateFieldsBoundFields(如上所示)。您可以在 aspx 标记上使用 EvalBind 将数据绑定到列或从 RowDataBound 中的代码隐藏以编程方式设置它,如上所示。
    • 非常感谢。我要在 RowDataBound 上的每一列中添加数据。
    猜你喜欢
    • 2014-11-01
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多