简体   繁体   中英

How to fetch data from SQL database to combo box - C#

I have a radio button & combo box like this:

在此输入图像描述

If the user chooses the radio button either single or double, the combo box automatically fetch the data (room number which is single-type if I choose single-type). I already have stored procedure like this.

create procedure viewRoom
@IDBranch varchar(5),
@NoTypeRoom varchar(5)

as

select NoRoom
from MsRoom
where NoTypeRoom = @NoTypeRoom
and IDBranch = @IDBranch
and AvailabilityRoom>0 

What should I do, so the fetched data can be shown in the combo box every time I choose the radio button?

you will have to use cmd.CommandType=CommandType.StoredProcedure

SqlCommand cmd  = new SqlCommand("viewRoom", conn);
cmd.CommandType=CommandType.StoredProcedure;
da=new SqlDataAdapter(cmd);
ds=new DataSet();
da.Fill(ds);
for(int i=0;i<ds.Tables[0].Rows.Count;i++)
cmbItems.items.add(ds.Tables[0].Rows[i][0].tostring()); //way to put table in combo

Try to use this kind of code.

Hope this helps you.

You can Populate Combobox like this:

comboBox1.DisplayMember = "YourColmName";
comboBox1.ValueMember = "YourFied"; //Field which you want set the value of combobox 
comboBox1.DataSource = PopulateCombo(NoTypeRoom,IDBranch) // variables

Here in this case may be your Value and label are same, but in other case you need to specify


Public DataTable PopulateCombo(string NoTypeRoom,string IDBranch)
{
SqlCommand cmd = new SqlCommand("viewRoom", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@NoTypeRoom", NoTypeRoom);
cmd.Parameters.AddWithValue("@IDBranch", IDBranch);
SqlDataAdapter dap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dap.Fill(ds);
return ds.Tables[0];  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM