4

I am a C# beginner. What I am trying to do is pull data from a column in a SQL database and write it to a listbox. Basically, I want the data in the part_num column of my table to be displayed dynamically in the listbox.

I have seen:

this.listParts.Items.AddRange(new object[] {"Part1", "Part2"});

But how would I go about replacing “Part1” and “Part2” with dynamically generated values from SQL?

public mainForm()
{
    InitializeComponent();
    SqlConnection conn = new SqlConnection(
        "Data Source=DBELL;Initial Catalog=part_table;Integrated Security=True");
    conn.Open();
    DataSet ds = new DataSet();
    SqlDataAdapter adapter = new SqlDataAdapter(
        "SELECT part_num from customParts", conn);
         adapter.Fill(ds);
    foreach (DataRow row in ds.Tables[0].Rows)
    {
        for (int i = 0; i < ds.Tables[0].Columns.Count; i++)

        this.listParts.Items.AddRange(new object[] {"Part1", "Part2"});
    }
}

Any help is appreciated!

1

1 Answer 1

10

Why not use the DataTable as DataSource:

public mainForm()
        {
            InitializeComponent();
            SqlConnection conn = new SqlConnection("Data Source=DBELL;Initial Catalog=part_table;Integrated Security=True");
            conn.Open();
            DataSet ds = new DataSet();
            SqlDataAdapter adapter = new SqlDataAdapter(
            "SELECT part_num from customParts", conn);
            adapter.Fill(ds);
            this.listParts.DataSource = ds.Tables[0]; 
            this.listParts.DisplayMember = "part_num"; 
        }

You should read up on DataSets or even better yet EntityFramework and data-binding.

Sign up to request clarification or add additional context in comments.

3 Comments

OK this seems much simpler, but when I deploy it I see "System.Data.DataRowView" rather then database values. Do I have to convert something to a string?
You don't need to. Simply specify the DisplayMember, e.g. DisplayMember="part_num".
Ahh, looks like I accidentally cutoff part of the code. All working now, really appreciate the help!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.