2

当我运行下面的代码时,编译器给了我错误:“对象引用未设置为对象的实例”。请你能告诉我在这段代码中犯了哪些错误。

   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();
            }
        }
4

2 回答 2

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);
}
于 2012-05-29T05:02:26.410 回答
1

只是预感,但 Mcodeddl 或 Mcodeddl.SelectedItem 为空。

(假设)下拉控件中可能没有选定的项目。

在有错误的代码之前对 Mcodeddl.SelectedItem 对象添加一个空检查,以防止这种情况发生。

于 2012-05-29T04:28:00.823 回答