基于TextBox输入动态生成GridView行
本文关键字:GridView 动态 TextBox 输入 基于 | 更新日期: 2023-09-27 18:14:33
我目前有一个gridview
没有行,只有标题。我有一个ASP控件textbox
与OnTextChange
事件。所以每次我输入一个数字到textbox
,我的网格视图将生成基于它的行数。在行内,将有一个dropdownlist
例如,在我的textbox
中,我输入数字2
,在gridview中将生成2行。
我目前正在使用ASP。净
文本框:
[ 2 ]
GridView:
----------------------------------------------------
| S/N | | |
----------------------------------------------------
| 1 | [dropdownlist] | [dropdownlist] |
|--------------------------------------------------|
| 2 | [dropdownlist] | [dropdownlist] |
--------------------------------------------------
下面是一段代码片段。在GridView中,你可以使用<TemplateField>
来创建你想要的布局。之后,您可能需要查看OnRowDataBound
事件来填充下拉列表。
protected void Button1_Click(object sender, EventArgs e)
{
int rowCount = 0;
//get the number from the textbox and try to convert to int
try
{
rowCount = Convert.ToInt32(TextBox1.Text);
}
catch
{
}
//set the new rowcount as a viewstate so it can be used after a postback
ViewState["rowCount"] = rowCount;
//start the function to fill the grid
fillGrid();
}
private void fillGrid()
{
int rowCount = 0;
//get the current row count from the viewstate
if (ViewState["rowCount"] != null)
{
rowCount = Convert.ToInt32(ViewState["rowCount"]);
}
//create a new DataTable with three columns.
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Created", typeof(DateTime));
//loop to add the row to the table
for (int i = 0; i < rowCount; i++)
{
table.Rows.Add(0, "Name_" + i.ToString(), DateTime.Now.AddMinutes(i));
}
//bind the table to the grid
GridView1.DataSource = table;
GridView1.DataBind();
}