如何在运行时添加新列,然后将其绑定到gridview?

时间:2013-12-09 11:38:37

标签: c# html asp.net sql gridview

如何在运行时将新列添加到gridview

这里提供日复一日的产品。使用日期作为标题列(列数不是默认值,它取决于产品提供的天数。例如:8表示将创建八列)并在项目模板(正文)中绑定数量。

**i want to display like this** 

            Totalqty Suppliedqty 01/12/13 01/12/13 01/12/13 01/12/13 01/12/13 01/12/13

    VacPan    50        25           8        5        4        1        2        3

    VacPan 
    Stub-in   100       50          10        8        7        8        7        10
    Kit           

3 个答案:

答案 0 :(得分:0)

根据您在运行时的需要使用新列创建自定义/修改的数据源,并将网格绑定到它。继续这些路线。

答案 1 :(得分:0)

每次您需要根据天数创建新数据源,然后将其绑定到gridview

答案 2 :(得分:0)

为出勤报告制作功能

public void BindAttendance()
    {

        ClearGrid();
        fyid =Convert.ToInt32(ddlYear.SelectedValue);
        dt.Clone();
        try
        {
            Session["datatable"] = null;
            dt = obj.AttendanceReport_Employee(fyid, Convert.ToInt32(ddlMonth.SelectedValue),Convert.ToString(EmpID));
            if (dt.Rows.Count > 0)
            {
                divGrd.Visible = true;
                btnExcel.Visible = true;
                btnPrint.Visible = true;
                gvAttendanceReport.Visible = true;
                int count = dt.Columns.Count;
                this.gvAttendanceReport.DataSource = dt;
                this.gvAttendanceReport.DataBind();
                int i = 0;            
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        DataColumn col = new DataColumn();
                        col = dt.Columns[j];
                        BoundField field = new BoundField();
                        field.DataField = col.ColumnName;
                        string text = col.ColumnName;
                        if (i != 0 && i != 1 && col.ColumnName!="Total Present" && col.ColumnName!="Total Absent" && col.ColumnName!="Total HalfDay" && col.ColumnName!="Total Late" && col.ColumnName!="Total Holiday")
                        {
                            field.HeaderText = text.Substring(0, 2);
                        }
                        else
                        {
                            field.HeaderText = text;
                        }

                        gvAttendanceReport.Columns.Add(field);
                        i++;                       
                    }               

                gvAttendanceReport.AutoGenerateColumns = false;
                gvAttendanceReport.DataSource = dt; //a DataTable of your choice
                gvAttendanceReport.DataBind();
                Session["datatable"] = dt;


            }
            else
            {

                btnExcel.Visible = false;
                btnPrint.Visible = false;
            }
        }
        catch(Exception ex)
        {
           gvAttendanceReport.DataSource = dt;
           gvAttendanceReport.DataBind();

           btnExcel.Visible = false;
           btnPrint.Visible = false;
        }

    }