当我运行下面的代码时,编译器给出了错误:“对象引用未设置为对象的实例”。请问你能说出我在这段代码中犯了哪些错误。
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();
}
}
答案 0 :(得分:1)
只是预感,但Mcodeddl或Mcodeddl.SelectedItem为空。
(假设)下拉控件中可能没有选定的项目。
在带有错误的代码之前对Mcodeddl.SelectedItem对象添加空检查以防止发生这种情况。
答案 1 :(得分:1)
var code = Mcodeddl.SelectedItem.Text; // you may need to check Mcodeddl.SelectedItem != null here, if you not set default selected item
if (string.IsNullOrEmpty(code)) return; // return if code type empty, or show message. depending on your requirement
using (SqlConnection connection = new SqlConnection(connectionString)) // using statement will dispose connection automatically
{
connection.Open();
using (SqlCommand command = new SqlCommand("select Request_Type from dbo.component where Material_Code= @MaterialCode", connection))
{
command.Parameters.AddWithValue("@MaterialCode", code); // use parameters
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var request = reader["Request_Type"];
TextBox4.Text = request != DBNull.Value ? request.ToString().Trim() :string.Empty;// check null before ToString
}
}
}
}
catch (Exception e)
{
Response.Write(e.Message);
}