So, I am new to C#, Visual studio etc, however I have a bit of experience with SQL Server. I Have a table, that contains Data (Obviously), and what I am trying to do is retrieve that data and display it in a drop down list so that a client can select which one they want. The problem I have is, the list only displays one specific field of data.
For instance, I have a table called Vehicle details, containing "Make, Model, age... etc". however when I set up the function in the drop down box it only lets me select one specific column I.E Make or Model.
Is there a way i can retrieve a whole column from SQL server and display it as one list. I.E Option one is Ford, Focus, 5. The next option is Ford, Fiesta, 10.
Is it because this line of code is a single option? this.comboBox1.DisplayMember = "Make"; When i try to edit it in the GUI it basically tells me no.
Any help would be appreciated.
The idea is when a customer selects their option and presses a submit button it will fire the information over the sql server.
Cheers
CodePudding user response:
There is indeed only one DisplayMember
, but that member can be anything you like. For example, if you're binding the combo box to a list of objects, give the object a property that displays what you want:
public class MyClass
{
public string Make { get; set; }
public string Model { get; set; }
public string Display { get { return $"{Make} - {Model}"; } }
}
Then you can bind to that property:
comboBox1.DisplayMember = "Display";
Similarly, if your results are something like a DataTable
bound to the results of a SQL query, your query can also return a calculated result:
SELECT
Make,
Model,
Make ' - ' Model AS Display
FROM
--...
Whatever you're binding the control to, give it the calculated result that you're looking for. The control itself is very generic, but you have specific control over your objects/data and can include in them all of the logic you like.
CodePudding user response:
If you want to get a drop down menu to display a Row of data, you can refer to the following code:
string connStr = "Enter your own connect string";
string sql = "select * from Book";//Enter your own sql statement
private void button1_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
SqlConnection conn = new SqlConnection(connStr);
using (conn)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = sql;
cmd.Connection = conn;
conn.Open();
SqlDataReader read = cmd.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
comboBox1.Items.Add(read["Id"].ToString() "," read["Name"].ToString());
//You can refer to change this line of code to: comboBox1.Items.Add(read["Make"].ToString() ", " read["Model"].ToString() ", " read["age"].ToString());
}
}
conn.Close();
}
}