我的网页上有TextBox
和Button
。用户在TextBox
中输入一个数字,然后点击Button
,这会在TextBox
中创建(n + 1)Panel
个es。
正如您在代码中看到的那样,我已将[{1}}分配给ID
个实例,再次尝试使用TextBox
访问TextBox
个实例时,我保留获得FindControl()
仅最后NullReferenceException
(ID:f1),我在这里做错了什么?
最初TextBox
不是Button1.Text
。
代码
"Find"
页面的ASPX代码
protected void Button1_Click(object sender, EventArgs e)
{
if (Button1.Text.Equals("Find"))
{
for (int i = 0; i < size; i++)
{
TextBox tb = (TextBox)Panel1.FindControl("Number" + i);
n[i] = Convert.ToInt32(tb.Text);
}
localhost.Search s = new localhost.Search();
resultLabel = new Label();
TextBox tb1 = (TextBox)Panel1.FindControl("f1");
int fNumber = Convert.ToInt32(tb1.Text); // tb1 is null
if (s.LinearSearch(n, fNumber))
resultLabel.Text = "FOUND!";
else
resultLabel.Text = "NOT FOUND!";
form1.Controls.Add(resultLabel);
}
else
{
size = Convert.ToInt32(TextBox1.Text);
n = new int[size];
TextBox1.Enabled = false;
boxes = new TextBox[size];
for (int i = 0; i < size; i++)
{
Label l = new Label();
l.Text = "Number " + (i + 1) + " : ";
boxes[i] = new TextBox();
boxes[i].ID = "Number" + i;
Panel1.Controls.Add(l);
Panel1.Controls.Add(boxes[i]);
}
Label l1 = new Label();
l1.Text = "Find Number : ";
Panel1.Controls.Add(l1);
findBox = new TextBox();
findBox.ID = "f1";
Debug.Write("[!D] ID : "+findBox.ID);
Panel1.Controls.Add(findBox);
Button1.Text = "Find";
}
}
答案 0 :(得分:0)
尝试在整个页面中搜索ID f1
,而不是在面板中搜索。
TextBox tb1 = (TextBox)FindControl("f1");
在文本框中添加ID
<asp:TextBox ID="f1" runat="server"></asp:TextBox>
在你的aspx页面中没有f1 ID,因为在尝试获取元素的Text时你得到了空引用异常。
答案 1 :(得分:0)
每当您创建动态控件时,都需要在回发时重新创建它。希望这有帮助
protected void Button1_Click(object sender, EventArgs e)
{
CreateControls();
if (Button1.Text.Equals("Find"))
{
for (int i = 0; i < size; i++)
{
TextBox tb = (TextBox)Panel1.FindControl("Number" + i);
n[i] = Convert.ToInt32(tb.Text);
}
localhost.Search s = new localhost.Search();
resultLabel = new Label();
TextBox tb1 = (TextBox)Panel1.FindControl("f1");
int fNumber = Convert.ToInt32(tb1.Text); // tb1 is null
if (s.LinearSearch(n, fNumber))
resultLabel.Text = "FOUND!";
else
resultLabel.Text = "NOT FOUND!";
form1.Controls.Add(resultLabel);
}
else
{
Button1.Text = "Find";
}
}
protected void CreateControls()
{
var size = Convert.ToInt32(TextBox1.Text);
var n = new int[size];
TextBox1.Enabled = false;
var boxes = new TextBox[size];
for (int i = 0; i < size; i++)
{
Label l = new Label();
l.Text = "Number " + (i + 1) + " : ";
boxes[i] = new TextBox();
boxes[i].ID = "Number" + i;
Panel1.Controls.Add(l);
Panel1.Controls.Add(boxes[i]);
}
Label l1 = new Label();
l1.Text = "Find Number : ";
Panel1.Controls.Add(l1);
var findBox = new TextBox();
findBox.ID = "f1";
Debug.Write("[!D] ID : " + findBox.ID);
Panel1.Controls.Add(findBox);
}