问题描述
Hello Friends,
我正在创建一个应用程序,我有一个问题,请帮助我们。
我正在使用c#后面的代码在gridview中创建短信文本框。
和行数和列数取决于一个下拉列表,因此数字和列会有所不同。现在在gridview非常细胞创建文本框。
我得到了解决方案。如何为此创建文本。
以下是代码
Hello Friends,
I am creating one application and I have one problem, Please help me guys.
I am creating texting textbox in gridview from code behind c#.
and number of rows and columns are depend on one dropdown so number and columns will vary. Now in gridview very cell create textbox.
I got solution for this. How to create text for this.
following is code
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for(int i =0; i < e.Row.Cells.Count; i++)
{
TextBox txt = new TextBox();
e.Row.Cells[i].Controls.Add(txt);
}
}
}
现在我将在每个单元格的每个文本框中添加一些值gridview和我想将所有值保存到数据库。
我尝试了以下代码,
Now i will add some values in every textbox of every cell of gridview and I want to save thease all values to database.
I tried some code as follows,
protected void btnSave_Click(object sender, EventArgs e)
{
for (var row = 0; row < GridView1.Rows.Count; row++)
{
for (int col = 0; col < GridView1.Rows[row].Cells.Count; col++)
{
TextBox txt = (TextBox)GridView1.Rows[row].Cells[col].Controls[0];
string texboxvalue= txt.Text;
}
}
}
但是我没有从文本框中获取数据而且这个代码给出如下任何例外
But I am not getting data from textbox and it this code giving any exception as follows
"Specified argument was out of the range of valid values.
Parameter name: index"
所以请帮我解决这个问题问题。
我的尝试:
So please help me to solve this problem.
What I have tried:
protected void btnSave_Click(object sender, EventArgs e)
{
for (var row = 0; row < GridView1.Rows.Count; row++)
{
for (int col = 0; col < GridView1.Rows[row].Cells.Count; col++)
{
TextBox txt = (TextBox)GridView1.Rows[row].Cells[col].Controls[0];
string texboxvalue= txt.Text;
}
}
}
推荐答案
int i = 0;
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txt = new TextBox() { ID = "txtDynamic" + i++ };
e.Row.Cells[0].Controls.Add(txt);
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
var Column1TextBoxes = Request.Form.AllKeys.Where(k => k.Contains("txtDynamic")).ToList();
for (int i = 0; i < Column1TextBoxes.Count; i++)
{
string value = Request.Form[Column1TextBoxes[i]]; // Textbox values
}
}
同样,您可以在运行时创建多个控件,并使用控件的名称获取值。
注意: 回发
之后你必须重新绑定 GridView
使用更新的值,否则您将无法保留数据。
Similarly you can create multiple controls on run time and get the values by using the name of the controls.
Note: After Postback
you will have to rebind the GridView
with the updated values, else you wont be able to retain the data.
这篇关于如何从gridview获取从后面的代码动态创建的文本框值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!