分两种,固定的和从数据库中动态读取的
先说固定的,大致如下,combobox3是包含这些下拉菜单的那个组件
comboBox3.Items.Clear();//先清空组件中的选项
comboBox3.Items.Add("荤菜");//这样combox3中的下拉菜单选项就是荤菜,素菜,汤粥,面食和套餐,五个选项
comboBox3.Items.Add("素菜");
comboBox3.Items.Add("汤粥");
comboBox3.Items.Add("面食");
comboBox3.Items.Add("套餐");
下面这种是从数据库中动态读取的,因为我做的这个程序两个下拉菜单是有关联的所以看起来会有点复杂
string connString = @"Data Source = .;Initial Catalog = Restaurant;Integrated Security=True";//连数据库
string sql="";//不这样写下面comm实例化括号里会报错
if (comboBox3.Text.Trim() == "荤菜")
{
comboBox4.Items.Clear();//一定要先清空啊,不然每次的都积在一起,下拉菜单越来越长
sql = string.Format("select Bname from B");从表中找到菜品的名字所在的列
}
if (comboBox3.Text.Trim() == "素菜")
{
comboBox4.Items.Clear();
sql = string.Format("select Cname from C");
}
if (comboBox3.Text.Trim() == "汤粥")
{
comboBox4.Items.Clear();
sql = string.Format("select Dname from D");
}
if (comboBox3.Text.Trim() == "面食")
{
comboBox4.Items.Clear();
sql = string.Format("select Aname from A");
}
if (comboBox3.Text.Trim() == "套餐")
{
comboBox4.Items.Clear();
sql = string.Format("select Pid from ABCD");
}
SqlConnection conn = new SqlConnection(connString);
try
{
conn.Open();//这段往下是重点,可直接复制
SqlCommand comm = new SqlCommand(sql, conn);
SqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
comboBox4.Items.Add(dr[0]);//combobox4是显示下拉菜单的组件,dr是读数据的对象,dr[0]是他读到的第一列,当然这种写法也只有一列
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "操作数据库出错", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
conn.Close();
}
十分感谢朱大哥教我这种方法,记下来,不然会忘- -
今天又是满怀困惑写bug的一天啊- -
有问题敬请指正呀~