我想在asp.net
中动态创建文本框值这是我在此代码文本框中创建的代码,但是当我在文本中输入值并从动态创建的文本框中检索值时,它会给出错误
对象引用未设置为对象的实例
以下是我的代码......
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Generate initial textboxes
GenerateButton_Click(sender, e);
}
}
protected void GenerateButton_Click(object sender, EventArgs e)
{
//Generate textboxes
int z = int.Parse(HowManyToGenerateTextBox.Text);
Panel1.Controls.Clear();
for (int i = 0; i < z; i++)
{
TextBox s = new TextBox();
s.ID = "tb" + i.ToString();
Session[s.ID] = s;
Panel1.Controls.Add(s);
}
}
protected void CalculateButton_Click(object sender, EventArgs e)
{
//Calculate sum
int sum = 0;
for (int i = 0; i < Session.Count; i++)
{
TextBox txt = (TextBox)Panel1.FindControl("tb" + i.ToString());
ResultLabel.Text = txt.Text;
if (ResultLabel.Text != null)
sum += int.Parse(ResultLabel.Text);
}
ResultLabel.Text = sum.ToString();
}
答案 0 :(得分:1)
我认为问题出在这一行
for (int i = 0; i < Session.Count; i++)
会话始终包含其他参数
在Session.Count
方法中将z
与GenerateButton_Click
进行比较。我想他们是不同的
答案 1 :(得分:0)
Hello Friend以下是答案
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
GenerateButton_Click(sender, e);
}
public TextBox[] s;
protected void GenerateButton_Click(object sender, EventArgs e)
{
int z = Convert.ToInt32(HowManyToGenerateTextBox.Text);
Panel1.Controls.Clear();
Array.Resize(ref s, z);
for (int i = 0; i < z; i++)
{
s[i] = new TextBox();
s[i].ID = "tb" + i.ToString();
s[i].Text = "tb" + i.ToString();
Session[s[i].ID] = s;
Panel1.Controls.Add(s[i]);
}
}
protected void CalculateButton_Click(object sender, EventArgs e)
{
ResultLabel.Text = s[0].Text;
}
这也是代码 http://www.codeproject.com/Questions/854773/How-to-get-dynamically-created-textbox-value