我动态创建我需要的控件 这是代码
public void cmdButton1_OnClick(object sender, EventArgs e)
{
Label myLabel = new Label();
myLabel.ID = "lblNameL" + i.ToString();
myLabel.Text = "Трите имена на латиница ";
TextBox myTextBox1 = new TextBox();
myTextBox1.ID = "txtNameL" + i.ToString();
Page.FindControl("form1").Controls.Add(myLabel);
Page.FindControl("form1").Controls.Add(myTextBox1);
Label mylabel2 = new Label();
mylabel2.ID = "lblNameK" + i.ToString();
mylabel2.Text = "Трите имена на кирилица";
TextBox myTextBox2 = new TextBox();
myTextBox2.ID = "txtNameK" + i.ToString();
Page.FindControl("form1").Controls.Add(mylabel2);
Page.FindControl("form1").Controls.Add(myTextBox2);
}
在这里,我尝试执行sql查询,以便我可以将文本框txbNameK
的内容插入到表Tourist
中,异常位于行cmd.Parameters.add
public void cmdInsert_OnClick(object sender, EventArgs e)
{
TextBox tx888 = (TextBox)FindControl("txtNameK" + i.ToString());
TextBox tx99 = (TextBox)FindControl("txtNameL" + i.ToString());
string insertSQL = "INSERT INTO Tourist ( Name_kir, Name_lat) VALUES (@Name_kir, @Name_lat, )";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=Pubs;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("@Name_kir",tx888);
cmd.Parameters.AddWithValue("@Name_lat", tx99);
int added = 0;
try
{
con.Open();
added = cmd.ExecuteNonQuery();
lblResult.Text = added.ToString() + "records added";
}
catch (Exception ex)
{
lblResult.Text = ex.Message;
}
finally
{
con.Close();
}
}
}
答案 0 :(得分:1)
两件事:
TextBox tx888 = (TextBox)FindControl("txtNameK" + i.ToString()); TextBox tx99 = (TextBox)FindControl("txtNameL" + i.ToString()); if(tx888 == null) return; if(tx99 == null) return;
上面将检查您的文本框是否为空 另一件事是:
cmd.Parameters.AddWithValue("@Name_kir",tx888.Text); cmd.Parameters.AddWithValue("@Name_lat", tx99.Text);
答案 1 :(得分:0)
只要null对象尝试访问任何值,就会发生对象引用异常。 例如..
以下代码可以正常使用。
Exception ex = new Exception()
Textbox1.Text = ex.Message;
以下代码将引发异常
Exception ex= null; //one and the same thing
Textbox1.Text = ex.Message; //Object reference not set....exception will be raised since ex is null
这是您的代码中发生的事情。尝试放置断点并进行调试。对于最佳实践,请始终按照Prashant的建议检查对象是否为空。