[英]How to populate combobox from database C#?
I want to fill my combobox with names from a database. 我想用数据库中的名字填充我的组合框。 Is it possible that in 1 combobox 2 columns will fill to it?
是否有可能在1个组合框2列中填充它? For example: I have 2 columns,
Name
and Position
. 例如:我有2列,
Name
和Position
。 I want to put the name in the combobox with the corresponding position. 我想把名字放在具有相应位置的组合框中。
example: 例:
Name Position
---------------------------------------------
jack President
jill President
maria Vice President
john Secretary
here's my code: 这是我的代码:
{ {
DataTable table = new DataTable();
using (SqlConnection sqlConn = new SqlConnection("my connection"))
{
using (SqlDataAdapter da = new SqlDataAdapter(@"SELECT Name, Position FROM CandidateTable", sqlConn))
da.Fill(table);
}
comboBox1.DataSource = table;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Position";
} }
NOTE: i want to fill my combobox with the name of jack and jill only bcoz they have the same Position. 注意:我想用jack和jill的名字填充我的组合框只有bcoz他们有相同的位置。 and the other names are in another combobox also.. not in president combobox.. i want to have a combobox that separate position.. you get my english?
其他名字也在另一个组合框中..不是在总统组合框中..我想要一个单独位置的组合框..你得到我的英文?
You'll need to concatenate the two fields either from database or from your Model 您需要从数据库或模型中连接两个字段
SELECT (name + ' - ' + Position) AS NameAndPosition from Employee
OR 要么
public class Employee
{
public string Name {get; set; }
public string Position {get; set; }
public string NameAndPosition
{
return String.Format("{0} - {1}", Name, Position);//
}
}
In your combobox, the display field would be NameAndPosition
在组合框中,显示字段为
NameAndPosition
It is not possible to have two columns in the combobox. 组合框中不可能有两列。 However, there are several javascripts available that will build a kind of custom interface to do that.
但是,有几个javascripts可用于构建一种自定义界面来实现这一点。
Here is a link to one of them 这是其中一个的链接
http://blog.pengoworks.com/index.cfm/2008/4/3/Preview-jQuery-Multicolumn-Dropdown-Plugin http://blog.pengoworks.com/index.cfm/2008/4/3/Preview-jQuery-Multicolumn-Dropdown-Plugin
Another option is, you can select both Name and position as one field and display it in the dropdown like 另一个选项是,您可以选择名称和位置作为一个字段,并在下拉列表中显示它
'select [Name] + " - " + [Position"] from table xxx'
This way, you will have both, name and position in the drop down. 这样,您将在下拉列表中同时拥有名称和位置。
use this codes , im sure you will get your answer... 使用此代码,我相信你会得到你的答案......
string query = "SELECT unitId,unitName FROM unit";
DataSet ds = new DataSet();
sqlopen();//a function for check open or close sql connection
// you must set already sqlConnection for sqlCon parameter
SqlCommand cmd = new SqlCommand(query, sqlCon);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "tbl");
cbEdit.DataSource = ds.Tables["tbl"];
cbEdit.DisplayMember = "unitName";
cbEdit.ValueMember = "unitId";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.