C# 组合框未填充
我有这个函数,我用它来填充我的组合框,但它没有被填充。我也没有得到任何错误C# 组合框未填充,c#,list,combobox,using,fill,C#,List,Combobox,Using,Fill,我有这个函数,我用它来填充我的组合框,但它没有被填充。我也没有得到任何错误 public List<string> showStudents() { List<string> list = new List<string>(); string rollno; command = connection.CreateCommand(); //command an
public List<string> showStudents()
{
List<string> list = new List<string>();
string rollno;
command = connection.CreateCommand(); //command and connection have been initialized earlier..
command.CommandText = "select RollNo from student";
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
rollno = reader["RollNo"].ToString();
list.Add(rollno);
}
reader.Close();
return list;
}
catch (Exception)
{
throw;
}
finally
{
connection.Close();
}
}
}
}
comboBox.DataSource=showStudents();
如果读取器返回结果,则应设置组合框的成员“DisplayMember”和“ValueMember”,以告知组合框应使用哪一列来显示文本和项的值 像这样:
comboBox.DisplayMember = "RollNo"
comboBox.ValueMember= "RollNo"
您可以在设置数据源后将其放在正确的位置。告诉我们它是否有用。请查看此示例并尝试使用您的代码
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("--Select--", "0"));
}
string Sql=“从JO.dbo.Comp中选择公司ID、公司名称”;
SqlConnection conn=新的SqlConnection(connString);
SqlCommand cmd=新的SqlCommand(Sql,conn);
cmd.CommandType=CommandType.Text;
SqlDataAdapter da=新的SqlDataAdapter(cmd);
数据集ds=新数据集();
da.填充(ds);
对于(int i=0;i
您是否验证了阅读器是否实际返回了结果?是的。是的。它提供了正确的结果。实际上我只想通过上面的函数来实现这一点。您能告诉我如何使用返回上述值的函数填充组合框吗?
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("--Select--", "0"));
}