本文介绍了如何在页面加载时填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我收到以下错误,以使以下代码填充下拉列表"ddlstuid":

错误ocurredSystem.NullReferenceException:对象引用未设置为对象的实例.在IAP.Attendance.Page_Load(对象发送者,EventArgs e)处.

请告诉我如何清除上述错误.

代码:

Hello All,
I am getting this error for the following code to fill the dropdownlist ''ddlstuid'' :

Error ocurredSystem.NullReferenceException: Object reference not set to an instance of an object. at IAP.Attendance.Page_Load(Object sender, EventArgs e).

pls tell me how to remove the above error.

code:

SqlConnection myconn;
SqlCommand cmd;
string str = "Data Source=TIMSCDR\\SQLEXPRESS;Initial Catalog=IAP;Integrated Security=True";
SqlDataReader dr;

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        cmd = new SqlCommand("select stuid from attendance", myconn);
        myconn.Open();
        ddlstuid.Items.Clear();
        dr = cmd.ExecuteReader();
        if (dr != null)
        {
            while (dr.Read())
            {
                ddlstuid.Items.Add(dr["stuid"].ToString());
            }
        }
        myconn.Close();
    }
    catch (Exception e1)
    {
        Label45.Text = "Error ocurred" + e1;
    }



在此先感谢.



Thanks in Advance.

推荐答案


cmd = new SqlCommand("select stuid from attendance", myconn);
myconn = new SqlConnection(str); // --- Add this line
myconn.Open();

别忘了将其放在finally 块中.



这篇关于如何在页面加载时填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 10:33