0%

【C#】GridView動態加入textbox

GridView原本產出的資料如下圖

[![](http://2.bp.blogspot.com/-Spka-CC-RXA/UQne4vnVBtI/AAAAAAAAA1c/vq-CaRzXOyI/s1600/%E6%9C%AA%E5%91%BD%E5%90%8D.png)](http://2.bp.blogspot.com/-Spka-CC-RXA/UQne4vnVBtI/AAAAAAAAA1c/vq-CaRzXOyI/s1600/%E6%9C%AA%E5%91%BD%E5%90%8D.png)
需求是將*號的部分變成TextBox且可輸入的字數要跟*號的個數相同,程式碼如下:

在GridView RowDataBound事件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
for(int i = 0 ; i = < e.Row.Cells.Count; i++)
{
if(e.Row.Cells[i].Text.Contains("*"))
{
int count = e.Row.Cells[i].Text.Count(f => f== '*');
int firstIndex = e.Row.Cells[i].Text.IndexOf('*');

e.Row.Cells[i].Text = e.Row.Cells[i].Text.Replace("*","").Insert(firstIndex, "<input maxlength="+ count +" runat='server' size='5' type='text' value='' />");
}
}
}
}

  1. 先算出*號的個數
  2. 找到*號第一次出現的位置
  3. 將*號全部Replace並在第一次出現的位置插入<input type=’text’ />
    結果如下
    [![](http://2.bp.blogspot.com/-e8AUIv9UIiU/UQnhfaf2eUI/AAAAAAAAA1w/cKFgnpj4UIE/s1600/%E6%9C%AA%E5%91%BD%E5%90%8D.png)](http://2.bp.blogspot.com/-e8AUIv9UIiU/UQnhfaf2eUI/AAAAAAAAA1w/cKFgnpj4UIE/s1600/%E6%9C%AA%E5%91%BD%E5%90%8D.png)