I want to fill my combobox with names from a database. Is it possible that in 1 combobox 2 columns will fill to it? For example: I have 2 columns, Name
and 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. 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
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.
Here is a link to one of them
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";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.