Durga Dutt
Durga Dutt

Reputation: 4113

Binding of Datasource to Listbox

I want to bind a OleDbDataReader to a Listbox . I have got reader with database values and i use following code for binding

List<String> cat_name = new List<string>();
        while (reader.Read())
        {
            cat_name.Add(reader["cat_name"].ToString());
        }

        ProductMainCategory.DataSource = cat_name;
        ProductMainCategory.DataBind(); 

i am getting category_id and cat_name from database. This code is setting only Listbox Text field with cat_name but i also want to fill dataValue property of Listbox. Please suggest me some good way to do this with best way .

Upvotes: 0

Views: 1935

Answers (1)

VinayC
VinayC

Reputation: 49245

You should be using List of some type such as KeyValuePair or Tuple or your own class to store both values. For example,

var categories = new List<KeyValuePair<string, string>>();
while (reader.Read())
{
   categories.Add(new KeyValuePair<string, string>(reader["category_id "].ToString(), reader["cat_name"].ToString()));
}
ProductMainCategory.DataSource = Categories;
ProductMainCategory.DataValueField = "Key";
ProductMainCategory.DataTextField = "Value";
ProductMainCategory.DataBind(); 

Upvotes: 1

Related Questions