如何在页面加载时填充下拉列表 [英] how to fill dropdownlist on page load
本文介绍了如何在页面加载时填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我收到以下错误,以使以下代码填充下拉列表"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.
推荐答案
public void bind()
{
sqldataadapter da =新sqldataadapter(从tname中选择*",cn);
datatable dt = new datatable();
da.fill(dt);
ddlstuid.datasource = dt;
ddlstuid.datatextfield ="colnale";
ddlstuid.datavaluefield ="colname";
ddlstuid.databind();
}
在页面加载中
{
if(!ispostback)
{
bind();
}
}
public void bind()
{
sqldataadapter da=new sqldataadapter("select * from tname",cn);
datatable dt=new datatable();
da.fill(dt);
ddlstuid.datasource=dt;
ddlstuid.datatextfield="colnale";
ddlstuid.datavaluefield="colname";
ddlstuid.databind();
}
in page load
{
if(!ispostback)
{
bind();
}
}
您似乎没有为"myconn"分配任何内容.尝试添加
You don''t appear to assign anything to "myconn". Try adding
cmd = new SqlCommand("select stuid from attendance", myconn);
myconn = new SqlConnection(str); // --- Add this line
myconn.Open();
别忘了将其放在finally
块中.
^ ]
引用此链接
http://www.java2s.com/Tutorial/ASP.NET/0360__ADO.net-Database/ReaddatafromSQLserverandfillaspdropdownlistC.htm[^]
Refer this link
这篇关于如何在页面加载时填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文