【问题标题】:Can't bind DataTable to GridView无法将 DataTable 绑定到 GridView
【发布时间】:2012-10-17 08:53:48
【问题描述】:

大家好,我刚刚开始编程,但遇到了问题。单击 button1 时,我创建的新数据表不会显示在 GridView2 中。虽然它填充了“计划”表中的数据(检查 dtPlanning 是否填充了注释中的文本框)。

简而言之:我想将 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">

感谢您的帮助。

【问题讨论】:

  • dtPlanning 为空,除非这不是您的全部代码
  • 检查计划。行数和数据
  • 你想用这个实现什么?

标签: c# asp.net


【解决方案1】:

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

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

我想知道你为什么不直接使用表planning

【讨论】:

  • 因为我想添加更多行和检查函数来创建一个全新的表。我只使用计划表中的信息。
【解决方案2】:

你必须:

  1. 向 DataSet 添加一个新的 DataTable
  2. 向 DataTable 添加新列
  3. 还有 GridView2.DataSource=YourNameDataSet.Tables[index_of_DataTable_in_DataSet].DefaultView;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-30
    • 2014-12-22
    • 2011-08-27
    • 2016-09-19
    • 1970-01-01
    • 2014-08-18
    • 2013-11-02
    • 1970-01-01
    相关资源
    最近更新 更多