【问题标题】:Combo box not getting filled组合框未填充
【发布时间】:2013-07-30 19:04:19
【问题描述】:

我有这个函数用来填充我的组合框,但它没有被填充。我也没有收到任何错误。

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();

可能是什么问题?请帮忙!! 谢谢..

已经得到答案了.. :)

foreach(string str in showStudent())
{
comboBox.Items.Add(str);
}

【问题讨论】:

  • 您是否验证了阅读器实际上正在返回结果?
  • 是的。我做到了。它提供了正确的结果。

标签: c# list combobox using fill


【解决方案1】:

如果阅读器返回结果,您应该设置 ComboBox 的成员“DisplayMember”和“ValueMember”,以告知组合框应使用哪一列显示文本以及项目的值。

像这样:

comboBox.DisplayMember = "RollNo"
comboBox.ValueMember= "RollNo"

你可以在设置DataSource之后直接放。告诉我们是否有帮助。

【讨论】:

  • 其实我只想通过上面的函数来做到这一点。你能告诉我如何使用返回上述值的函数来填充组合框吗?
【解决方案2】:

查看此示例并尝试使用您的代码

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"));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2013-06-22
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多