[英]How to populate combobox from database C#?
我想用數據庫中的名字填充我的組合框。 是否有可能在1個組合框2列中填充它? 例如:我有2列, Name
和Position
。 我想把名字放在具有相應位置的組合框中。
例:
Name Position
---------------------------------------------
jack President
jill President
maria Vice President
john Secretary
這是我的代碼:
{
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";
}
注意:我想用jack和jill的名字填充我的組合框只有bcoz他們有相同的位置。 其他名字也在另一個組合框中..不是在總統組合框中..我想要一個單獨位置的組合框..你得到我的英文?
您需要從數據庫或模型中連接兩個字段
SELECT (name + ' - ' + Position) AS NameAndPosition from Employee
要么
public class Employee
{
public string Name {get; set; }
public string Position {get; set; }
public string NameAndPosition
{
return String.Format("{0} - {1}", Name, Position);//
}
}
在組合框中,顯示字段為NameAndPosition
組合框中不可能有兩列。 但是,有幾個javascripts可用於構建一種自定義界面來實現這一點。
這是其中一個的鏈接
http://blog.pengoworks.com/index.cfm/2008/4/3/Preview-jQuery-Multicolumn-Dropdown-Plugin
另一個選項是,您可以選擇名稱和位置作為一個字段,並在下拉列表中顯示它
'select [Name] + " - " + [Position"] from table xxx'
這樣,您將在下拉列表中同時擁有名稱和位置。
使用此代碼,我相信你會得到你的答案......
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.