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

Just a hunch, but either Mcodeddl or Mcodeddl.SelectedItem is null.

There is probably no selected item in the (assuming) dropdown control.

Add a null check on the Mcodeddl.SelectedItem object before the code with the error to prevent that from happening.

于 2012-05-29T04:28:00.823 に答える
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 に答える