无法将DataTable绑定到GridView

时间:2012-10-17 08:53:49

标签: c# asp.net

嘿伙计们我刚刚开始编程,而且我遇到了一个问题。单击button1时,我创建的新数据表不会显示在GridView2中。虽然它填充了“计划”表中的数据(检查dtPlanning在注释中填充了TextBoxes)。

简而言之:我希望将DataTable规划纳入新的DataTable dtPlanning并在gridview中显示它。

代码背后:

protected void Button1_Click(object sender, EventArgs e)
{
    DataTable dtPlanning = new DataTable();
    dtPlanning.Columns.Add("Courseday", typeof(int));
    dtPlanning.Columns.Add("Part", typeof(string));
    dtPlanning.Columns.Add("Design", typeof(string));
    dtPlanning.Columns.Add("Lesson", typeof(string));

    //DataRow dr = planning.Rows[1];  
    //TextBox2.Text = (dr["Daynumber"]).ToString();
    //TextBox3.Text = (dr["Part"]).ToString();
    //TextBox4.Text = (dr["Design"]).ToString();
    //TextBox5.Text = (dr["Lesson"]).ToString();

    for (int i = 0; i < dtPlanning.Rows.Count; i++)
    {
        DataRow dr = dtPlanning.NewRow();
        foreach (DataRow datarow in planning.Rows)
        {
            dtPlanning.Rows.Add(datarow);
        }
    }
    GridView2.DataSource = dtPlanning;
    GridView2.DataBind();
}

源代码:

<asp:GridView ID="GridView2" runat="server">

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

逻辑上,dtPlanning.Rows.Count = 0因为这个表刚刚初始化了! 其次,您不能Add从一个表到另一个表,用户Import

for (int i = 0; i < planning.Rows.Count; i++)
{
    dtPlanning.ImportRow(planning.Rows[i]);
}

我想知道您为什么不使用表格planning

答案 1 :(得分:0)

你必须:

  1. 向DataSet添加新的DataTable
  2. 向DataTable添加新列
  3. 和GridView2.DataSource = YourNameDataSet.Tables [index_of_DataTable_in_DataSet] .DefaultView;
相关问题