0

I have been working with a local database using C# windows forms. I wanted to know how to populate a listBox (or basically retrieve any particular piece of info from the DB and set it to a variable). It seems obvious that I would need to use a query to gather a particular piece of info, but i dont know how to do this.

Example: Person Table has the following columns - ID, FirstName, LastName, Age

How do I populate a ListBox with each persons First Name in the Database?

Kind of like listBox1.Items.Add(Query: Select FirstName from Person) or string variable1 = (Query: SelectFirstName from Person Where ID = 1);

3
  • 1
    Do not use hardcoded database queries in your code - they lead to a maintenance nightmare.
    – xxbbcc
    Nov 11, 2014 at 21:04
  • You should get in the habit of making things as re-usable/scalable as you can. As an example, we use a table in our DB to store values for drop downs with key indicators and have a stored procedure that returns the specific values for a drop down using those key indicators. This allows you to change the values of your drop down without having to recompile your application
    – Jfabs
    Nov 11, 2014 at 21:10
  • It's hard to explain, but I am not exactly hard-coding the way you think. The application uses "Profiles" so the data displayed will look different depending on the profile selected. However, in order to create a profile, a table needs to be updated so it has the profile name. That way when the application starts up, you can choose from whichever profile you want. However, I need to be able to access the table. So i need to be able to grab info from a column to save to a variable. Any ideas?
    – GenDis
    Nov 11, 2014 at 21:14

2 Answers 2

0

Retrieve the database data into a data table and set the following properties:

var dataTable = new DataTable();
// fill the data table 

listBox.ItemsSource = dataTable.DefaultView;
listBox.DisplayMemberPath = "FirstName";
listBox.SelectedValuePath = "ID";
0

You need 3 to 4 steps to do that.
1 - ConnectionString 2 - SQlCommand 3 - DataReader 4 - DataSet

//If you're working on a very big project which requires a bunch of SQL table, the ConnectionString is usually done on the App.Config (Windows Form) or Web.Config (WebForm/MVC).

//For the connection string, please click on the link below for some basic information: https://www.connectionstrings.com/sql-server-2008/

2)
private string sql = "SELECT ID, FirstName, LastName, Age FROM Person WHERE ....."
3)
public SQLReader something
{
return this.DataReader(sql);
}

4)
public Dataset SomeData
{
Dataset data = new DataSet()
try
{
 this.DataAdapter(sql).Fill(data, "Person");
}
 catch
 {
 data = null;
 }
 return data;
}
}
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.