2012-10-17 47 views
0

嘿,我剛剛開始編程,我遇到了一個問題。當button1被點擊時,我創建的新Datatable不會在GridView2中顯示。雖然它充滿了來自「計劃」表的數據(檢查dtPlanning在註釋中填充了文本框)。無法將DataTable綁定到GridView

所以簡而言之:我想將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"> 

謝謝您的幫助。

+0

dtPlanning是空的,但這不是所有的代碼 – codingbiz

+0

檢查planning.Rows計數和數據 – andy

+0

你想用這個來實現什麼? – codingbiz

回答

0

邏輯上,dtPlanning.Rows.Count = 0,因爲此表剛剛初始化! 其次,你不能Add從一個表中的一行到另一個,用戶Import

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

我不知道你爲什麼不只是使用表planning

+0

因爲我想添加更多的行和checkfunctions來創建完整的新表。我只使用計劃表內的信息。 – Dave

0

您必須:

  1. 添加到DataSet中的新的DataTable
  2. 添加到數據表中的新列
  3. 而GridView2.DataSource = YourNameDataSet.Tables [index_of_DataTable_in_DataSet] .DefaultView;