Populating ComboBox from DataSet in C#
In essence, there's nothing simpler than populating a ComboBox from a DataSet.
It's done as follows:
SqlConnection connRC = new SqlConnection(MainParams.ConStr);
string command = "SELECT Kod, Nam FROM Produkt ORDER BY Nam";
SqlDataAdapter da = new SqlDataAdapter(command, connRC);
DataSet ds = new DataSet();
connRC.Open();
da.Fill(ds);
connRC.Close();
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = "Nam";
comboBox1.ValueMember = "Kod";
However, it works slowly with large selections — awfully slow!
There are two ways out of this:
SqlConnection con = new NpgsqlConnection(MainParams.ConnectionString);
SqlCommand com = new NpgsqlCommand("select * from Users order by NAME", con);
con.Open();
SqlDataReader reader;
reader = com.ExecuteReader();
while (reader.Read())
{
try
{
string result = reader.GetString(1);
comboBox1.Items.Add(result);
comboBox1.Text = result;
}
catch { }
}
con.Close();
1. Populate the ComboBox from a DataReader by iterating row by row, as it surprisingly becomes much faster.
Here's how:
2. Populate through a DataSet, but only once when the application starts and not touch it without necessity, load the entire selection into the DataSet and then play with it through filters. (Personally, I like this method a bit more).
Comments (0)
No comments yet.