数据读取器的 C# 命令执行错误

标签 c# c#-4.0

当我运行下面的代码时,编译器给出错误:“对象引用未设置到对象的实例”。请您告诉我在这段代码中犯了什么错误。

   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/

相关文章:

c# - 使用 ASP.NET MVC 构建基本网页

c# - 什么时候可以说发生了方法组转换?

c# - 与 DBMS 中的索引相关的 "pinning"到底是什么?

c# - "Where"和 "Select"在 LINQ 中如何工作?

c#-4.0 - 如何在 C# 中动态生成在 DataGridView 内选中的复选框?

c#-4.0 - 使用命名参数是否有额外的运行时成本?

c# - 从文本框中获取特定值到 GridView ?

jquery - 无法从 C# 中的 jQuery 对话框获取值?

c# - OrderBy().ThenBy() 错误输出

c# - 在 asp.net 中使用嵌套转发器