基于TextBox输入动态生成GridView行

时间:2016-10-24 15:07:04

标签: c# asp.net visual-studio dynamic

我目前有gridview没有行,只有标题。我有一个带有textbox事件的ASP控件OnTextChange。因此,每当我在textbox中输入一个数字时,我的gridview将根据它生成行数。在行内,将有一个dropdownlist

例如,在我的textbox中,我输入了数字2,将在gridview中生成2行。

我目前正在使用ASP.NET

文本框:

[  2 ]

GridView的:

----------------------------------------------------
| S/N |                      |                     |
----------------------------------------------------
|  1  |   [dropdownlist]     |     [dropdownlist]  |
|--------------------------------------------------|
|  2  |   [dropdownlist]     |     [dropdownlist]  |
 -------------------------------------------------- 

1 个答案:

答案 0 :(得分:0)

这是一个可以帮助您入门的代码段。在GridView中,您可以使用<TemplateField>创建所需的布局。之后,您可能希望查看OnRowDataBound事件以填充DropDownLists。

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();
}