我如何在GridView中读取动态创建的文本框 [英] How can i read a dynamically created textbox in gridview
本文介绍了我如何在GridView中读取动态创建的文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在OnRowDataBound中添加了一些动态的文本框,当我尝试获取该值时,我得到的是null.
这是我的代码
I am adding few textbox dynamic in OnRowDataBound and when i try getting the value then i am getting null.
Here is my code
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int columnValue = Convert.ToInt32(ViewState["CountColumnValue"].ToString());
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 1; i <= columnValue; i++)
{
TextBox myTextBox = new TextBox();
myTextBox.ID = "myTextBox" + (i).ToString();
e.Row.Cells[i].Controls.Add(myTextBox);
}
}
}
protected void btnEnter_Click(object sender, EventArgs e)
{
ViewState["CountColumnValue"] = txtNumber.Text;
SetInitialRow();
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
int columnValue = Convert.ToInt32(ViewState["CountColumnValue"].ToString());
for (int i = 0; i < columnValue; i++)
{
dt.Columns.Add(new DataColumn("Column" + i, typeof(string)));
}
dr = dt.NewRow();
dr["RowNumber"] = 1;
for (int j = 0; j < columnValue; j++)
{
dr["Column" + j] = string.Empty;
}
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
protected void btnResult_Click(object sender, EventArgs e)
{
for (int i = 0; i < Gridview1.Rows[0].Cells.Count; i++)
{
GridViewRow grd = Gridview1.Rows[0];
string str = (grd.Cells[1].FindControl("myTextBox1") as TextBox).Text;
}
}
推荐答案
更改您所在国家/地区的固定索引
旧
chang eyour fix index in cells to your country
old
(grd.Cells[1].FindControl("myTextBox1") as TextBox).Text;
新
new
(grd.Cells[i].FindControl("myTextBox" + i) as TextBox).Text;
变化
*单元格[1]至单元格[i]
*从"myTextBox1"到"myTextBox" + i
changes
* Cells[1] to Cells[i]
* "myTextBox1" to "myTextBox" + i
请尽快给我答案.
在填充网格时,应添加此内容rowdatabound事件中出现这种情况,因为第一次rowdatabound以-ve索引值运行.
When your populate your grid you should add this condition in your rowdatabound event because 1st time rowdatabound runs with -ve index value.
if (e.Row.RowIndex != -1)
{
}
然后尝试执行此操作以从文本框中获取值:
and then try doing this for getting the values from the textboxes:
Foreach(Datarow dr in Gridview1.Rows)
{
TextBox txtDummy = new TextBox;
txtDummy = (TextBox)e.Row.FindControl("textBoxID goes here"));
string dummy = txtDummy.text;
}
对于ID,请参见页面的源代码,并查看其为您的动态文本框生成的id,它应该类似于" Gridview1_ctl02_textboxname_textbox"
For ID see the source of the page and see whats the id its generating for your dynamic textboxes, it should be something like "Gridview1_ctl02_textboxname_textbox"
这篇关于我如何在GridView中读取动态创建的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文