通过从数据库加载数据来创建Gridview列标题

时间:2012-04-12 07:12:51

标签: c# asp.net sql-server-2008

我想通过从表中检索数据来绑定网格列标题名称。该表有两个字段,DomainID和DomainName,我想将DomainNames显示为Grid的Column标题。 实际上我正在创建员工网格视图。我希望员工的所有域名都显示为标题,我必须在Checkbox中检查相应的域名。

请给我一些想法。

提前致谢。

2 个答案:

答案 0 :(得分:1)

从我的理解......

  1. 制作网格视图
  2. 创建两列:   一个。 TextBoxColumn   湾CheckBoxColumn
  3. 使用.HeaderText属性设置列标题
  4. 将列添加到数据网格视图
  5. 查询您的数据库并从中获取data_table
  6. 使用dgv.DataSource = data_table将数据绑定到表中 要么 为data_table中的所有行创建一个for循环,并明确添加每一行

  7. 要使复选框生效,请处理数据网格视图的cellContentClick事件并在数据库中执行必要的更新.....

  8. 希望它有所帮助......

答案 1 :(得分:1)

您可以将标头加载到DataTable中,然后使用自定义TemplateField动态创建标题。

这是aspx部分:

<asp:GridView ID="GridView1" AutoGenerateColumns="false" DataKeyNames="EmployeeID" runat="server" >
    <SelectedRowStyle BackColor="Aqua" />
    <Columns>
        <asp:TemplateField HeaderText="Employee" SortExpression="Employee">
           <ItemTemplate>
                <asp:HiddenField ID="HiddenEmpID" Value='<%# Bind("EmployeeID") %>' runat="server" />
                <asp:label runat="server" ID="LblEmployee" Text='<%# Bind("EmployeeName") %>'></asp:label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Button ID="BtnSave" Text="Save" runat="server" onclick="BtnSave_Click" />

这是一个完整的样本:

public partial class GridTest : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        CreateGridColumns();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) BindGrid();
    }

    private void CreateGridColumns()
    {
        var tblDomain = GetDomains();
        // Create dynamic TemplateFields
        foreach (DataRow row in tblDomain.Rows)
        {
            String domainName = row.Field<String>("DomainName");
            TemplateField field = new TemplateField();
            //Initalize the DataField value.
            field.ItemTemplate = new GridViewCheckBoxTemplate(ListItemType.Item, domaninName);
            field.HeaderText = domainName;
            //Add the newly created field to the GridView.
            GridView1.Columns.Add(field);
        }
    }

    private DataTable GetDomains()
    {
        var tblDomain = new DataTable();
        tblDomain.Columns.Add("DomainID", typeof(int));
        tblDomain.Columns.Add("DomainName");
        tblDomain.Rows.Add(1, "Google.com");
        tblDomain.Rows.Add(2, "Yahoo.com");
        tblDomain.Rows.Add(3, "Msn.com");
        tblDomain.Rows.Add(4, "Youtube.com");
        tblDomain.Rows.Add(5, "Myspace.com");
        tblDomain.Rows.Add(6, "Facebook.com");
        tblDomain.Rows.Add(7, "Wikipedia.org");
        return tblDomain;
    }

    private void BindGrid()
    {
        var tblDomain = GetDomains(); // load domains from database or wherever
        var tblData = new DataTable();// load sample data
        tblData.Columns.Add("EmployeeID", typeof(int));
        tblData.Columns.Add("EmployeeName");
        //add domains as DataTable-Columns 
        foreach (DataRow row in tblDomain.Rows)
        {
            String domaninName = row.Field<String>("DomainName");
            //Add column from domain-name
            tblData.Columns.Add(domaninName, typeof(bool)); //CheckBox-Checked is a boolean
        }

        //get some Employees and random checked state
        var rnd = new Random();
        var empRow = tblData.NewRow();
        empRow["EmployeeID"] = 1;
        empRow["EmployeeName"] = "Jon";
        foreach (DataRow dom in tblDomain.Rows)
        {
            empRow[dom.Field<String>("DomainName")] = rnd.Next(0, 2) == 0;
        }
        tblData.Rows.Add(empRow);
        empRow = tblData.NewRow();
        empRow["EmployeeID"] = 2;
        empRow["EmployeeName"] = "Eric";
        foreach (DataRow dom in tblDomain.Rows)
        {
            empRow[dom.Field<String>("DomainName")] = rnd.Next(0, 2) == 0;
        }
        tblData.Rows.Add(empRow);
        empRow = tblData.NewRow();
        empRow["EmployeeID"] = 3;
        empRow["EmployeeName"] = "Alain";
        foreach (DataRow dom in tblDomain.Rows)
        {
            empRow[dom.Field<String>("DomainName")] = rnd.Next(0, 2) == 0;
        }
        tblData.Rows.Add(empRow);

        GridView1.DataSource = tblData;
        GridView1.DataBind();
    }

    // show how to retrieve all checkbox values and the according EmployeeID
    protected void BtnSave_Click(object sender, EventArgs e)
    {
        if (GridView1.Rows.Count == 0) return;
        var checkBoxColumns = GridView1.Columns.Cast<DataControlField>()
            .Select((bf,index) => new{Field=bf, Index=index})
            .Where(f => f.Field.GetType() == typeof(TemplateField) && ((TemplateField)f.Field).ItemTemplate.GetType() == typeof(GridViewCheckBoxTemplate))
            .ToArray();

        foreach (GridViewRow row in GridView1.Rows)
        {
            int EmployeeID = int.Parse(((HiddenField)row.FindControl("HiddenEmpID")).Value);
            foreach (var f in checkBoxColumns)
            {
                String domain = f.Field.HeaderText;
                bool isChecked = row.Controls[f.Index].Controls.OfType<CheckBox>().First().Checked;
            }
        }
    }
}

以下是自定义ITemplate

public class GridViewCheckBoxTemplate : ITemplate
{
    ListItemType _templateType;
    string _columnName;

    public GridViewCheckBoxTemplate(ListItemType type, string colname)
    {
        _templateType = type;
        _columnName = colname;
    }

    void ITemplate.InstantiateIn(System.Web.UI.Control container)
    {
        switch (_templateType)
        {
            case ListItemType.Header:
               break;
            case ListItemType.Item:
                var chb1 = new CheckBox();
                chb1.DataBinding += new EventHandler(CB_DataBinding);
                container.Controls.Add(chb1);
                break;
            case ListItemType.EditItem:
                //As, I am not using any EditItem, I didnot added any code here.
                break;
            case ListItemType.Footer:
                break;
        }
    }

    void CB_DataBinding(object sender, EventArgs e)
    {
        CheckBox chb = (CheckBox)sender;
        GridViewRow container = (GridViewRow)chb.NamingContainer;
        object dataValue = ((DataRowView)container.DataItem)[_columnName];
        chb.Checked = dataValue != DBNull.Value && (bool)dataValue;
    }
}