Niah
Niah

Reputation: 11

C# code to Display a Query Result in a List Box in windows forms

I am working on a software in which i need to display the search query results in a listbox. mine is a medical software and im trying to display the list of medicines in the listbox. im using c# for coding under Windows Visual studio 10 platform. please help me wid this. regards

Im using Sql server management studio as backend. im using a button which when clicked will fire an event performing a query. the query is select * from Table_name i want to show the query list in the listbox..

Upvotes: 1

Views: 4301

Answers (2)

daniloquio
daniloquio

Reputation: 3902

Within the button_click event:

  1. Configure a SqlCommand with CommandType=Text and CommandText="your query".
  2. Execute the SqlCommand with ExecuteReader.
  3. Convert the resulting SqlDataReader in a DataTable with dataTable.Load(dataReader);
  4. Make that datatable your ListBox's Data Source (libYourListBox.DataSource = dataTable).
  5. Define your list box's DisplayMember to the name of the column that holds the medicine's name.
  6. Define your list box's ValueMember to the id or code of the medicin.

That should work.

Upvotes: 2

JAiro
JAiro

Reputation: 5999

try something like this:

 SqlDataAdapater adp=new SqlDataAdapter(querystr,"set connection string");
 DataTable dt=new DataTable();
 adp.Fill(dt);
 List.DataSource=dt;
 List.DisplayMember=dt.Columns[0].ColumnName;

Upvotes: 0

Related Questions