如何在asp.net和C#中填充dropdownlist [英] how to fill dropdownlist in asp.net and c#
本文介绍了如何在asp.net和C#中填充dropdownlist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,
我编写了以下代码来填充下拉列表"ddlstuid".
下面的代码给我一个错误:"ddlstuid的最佳重载方法匹配有一些无效的参数".请告诉我如何使用c#代码在asp.net中填充下拉列表.
Hello,
I have written the following code to fill the dropdownlist ''ddlstuid''.
The following code gives me an error: "The best overloaded method match for ddlstuid has some invalid arguments". Pls tell me how else can i fill a dropdownlist in asp.net using c# code.
SqlConnection myconn;
SqlCommand cmd;
string str = "Data Source=TIMSCDR\\SQLEXPRESS;Initial Catalog=IAP;Integrated Security=True";
SqlDataReader dr;
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"]);
}
}
myconn.Close();
}
catch (Exception e1)
{
Label45.Text = "Error ocurred" + e1;
}
推荐答案
ddlstuid.Items.Add(dr["stuid"].tostring());
Convert this into the String
有多种方法可以做到这一点:
1)您可以使用DataAdapter和DataTable:
There are a number of ways to do this:
1) You could use a DataAdapter and DataTable:
SqlDataAdapter da = new SqlDataAdapter("SELECT stuid FROM attendance", myconn);
DataTable dt = new DataTable();
da.Fill(dt);
ddlstuid.Items.Clear();
ddlstuid.DataSource = dt;
2)您可以构造一个列表并使用它:
2) You could construct a list and use that:
try
{
cmd = new SqlCommand("select stuid from attendance", myconn);
myconn.Open();
ddlstuid.Items.Clear();
dr = cmd.ExecuteReader();
List<object> list = new List<object>();
if (dr != null)
{
while (dr.Read())
{
list.Add(dr["stuid"]);
}
}
myconn.Close();
ddlstuid.DataSource = list;
}
catch (Exception e1)
{
Label45.Text = "Error ocurred" + e1;
}
就个人而言,我更喜欢前者...
Personally, I prefer the former...
您需要将dr ["stuid"])转换为字符串,如下所示:
dr ["stuid"]).toString()
you need to convert dr["stuid"]) into string as:
dr["stuid"]).toString()
这篇关于如何在asp.net和C#中填充dropdownlist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文