[Web/C#] GridView 動態加入控制項

  • 687
  • 0

GridView 動態加入控制項

開發環境:VS2013(C#)、Framework 4.5

 

目前有個需求

因載入的項目不固定所以無法先拉好欄位

但又需要在每列後方加入一欄TextBox

原想這應該是個簡單的功能

結果意外的卡了半天...

 

非常直覺的在RowCreated裡寫


        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TextBox tb1 = new TextBox();
                tb1.ID = "tb1";
                e.Row.Cells[2].Controls.Add(tb1);
            }        
        }

 

一執行之後發現...

這是怎麼回事??!!

Textbox怎麼沒出現?

參考網路上的範例也是都用相同的方法

怎麼會這樣?

 

神奇的是  如果我在RowDataBound也加 入相同的語法就會正常出現

且也能正確抓到值

但我還是覺得怪怪的

總覺得寫兩次是非常怪的事

於是又開始東翻西找的挖解答

然後找到了下面這段:


 if (e.Row.RowType == DataControlRowType.Header)
{
    TableCell tc = new TableCell();
    tc.Text = "C";
    e.Row.Cells.AddAt(2, tc);
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
    TextBox tb1 = new TextBox();
    tb1.ID = "tb1";
    TableCell tc = new TableCell();
    tc.Controls.Add(tb1);
    e.Row.Cells.AddAt(2, tc);
}

可以正常顯示及取值

唯一的缺點是標題沒有置中...

暫時先這樣解

如果有更好的解法煩請不吝指教~謝謝!