当我运行下面的代码时,编译器给出错误:“对象引用未设置到对象的实例”。请您告诉我在这段代码中犯了什么错误。
public void text()
{
cn1.Open();
string s;
//error came here
s = "select Request_Type from dbo.component where Material_Code='" +
Mcodeddl.SelectedItem.Text + "' ";
//end
SqlCommand cd1 = new SqlCommand(s, cn1);
SqlDataReader rd;
try
{
rd = cd1.ExecuteReader();
while (rd.Read())
{
TextBox4.Text = rd["Request_Type"].ToString().Trim();
}
rd.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
cd1.Dispose();
cn1.Close();
}
}
最佳答案
只是预感,但 Mcodeddl 或 Mcodeddl.SelectedItem 为空。
(假设)下拉控件中可能没有选定的项目。
在出现错误的代码之前添加对 Mcodeddl.SelectedItem 对象的 null 检查,以防止发生这种情况。
关于数据读取器的 C# 命令执行错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10793043/