简体   繁体   English

如何从另一个组合框填充相同形式的组合框?

[英]How to populate a combo box from another combo box in the same form?

Two comboBox and a table called MAINCATE is created. 将创建两个comboBox和一个名为MAINCATE的表。

I have a code , but stuck to determine what SQLQuery should i use to get the second combo box filled , determined by the first combo box. 我有一个代码,但是要确定要使用哪个SQLQuery来填充第二个组合框,该组合由第一个组合框确定。

I just need a little help on how to fill in the second combobox based on mainCate picked by the first combobox.. 我只需要一些帮助,以根据第一个组合框选择的mainCate填充第二个组合框。

i need to do something like.. if combobox 1 mainCate is "Food" , then combo box 2 should show "Raw , cooked , fruits and vegetables" 我需要做类似..如果组合框1 mainCate是“食物”,则组合框2应该显示“未加工,煮熟的水果和蔬菜”

This is what is inside of the MAINCATE table - ( http://i.imgur.com/qR90Z2B.png ) 这就是MAINCATE表的内部-( http://i.imgur.com/qR90Z2B.png

And this is my code :- 这是我的代码:-

DataSet ds1;
DataSet ds2;

public User()
{
    InitializeComponent();
}

private void User_Load(object sender, EventArgs e)
{

    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
    conn.Open();

    SqlDataAdapter daMain = new SqlDataAdapter("SELECT * FROM MAINCATE", conn);
    ds1 = new DataSet();
    daMain.Fill(ds1, "Maincate");
    mainCatU.DisplayMember = "mainCate";
    mainCatU.ValueMember = "mainCate";
    mainCatU.DataSource = ds1.Tables["MAINCATE"];
    mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
    mainCatU.Enabled = true;

    SqlDataAdapter daSub = new SqlDataAdapter("SELECT >What should i do here?<", conn);
    ds2 = new DataSet();
    daSub.Fill(ds2, "Subcate");
    subCatU.DisplayMember = "Subcat1";
    subCatU.ValueMember = "Subcat";
    subCatU.DataSource = ds2.Tables["MAINCATE"];
    subCatU.DropDownStyle = ComboBoxStyle.DropDownList;
    subCatU.Enabled = true;
    conn.Close();
}

private void mainCatU_SelectionChangeCommitted(object sender, EventArgs e)
{
    //have no idea if a code should be here..
}

or should i do something like this? 还是我应该做这样的事情?

SqlCommand cmd = new SqlCommand("select Subcat1,Subcat2,Subcat3,Subcat4 from MAINCATE where mainCate=@mainCate;", con);

========================================= =========================================

@philip - putting this on page load repalcing my code above - it didnt work.. @philip-将其放在页面加载中,将我的代码重新放在上面-它没有用。

string result = mainCatU.SelectedItem.ToString();

            SqlDataAdapter daSub = new SqlDataAdapter("SELECT * FROM MAINCATE where mainCate = " + result , conn);
            ds2 = new DataSet();
            daSub.Fill(ds2, "Subcate");
            subCatU.DisplayMember = "Subcat1";
            subCatU.ValueMember = "Subcat1";
            subCatU.DataSource = ds1.Tables["MAINCATE"];
            subCatU.DropDownStyle = ComboBoxStyle.DropDownList;
            subCatU.Enabled = true;

even tried 甚至尝试过

SqlDataAdapter daSub = new SqlDataAdapter("SELECT * FROM MAINCATE where mainCate=@result", conn);

I think this is what your looking for: 我认为这是您要寻找的:

Fill the first combo box with your current code. 用您的当前代码填充第一个组合框。

Then to fill the second combo box you need to hook up the first combo box selectionchangecommitted. 然后,要填充第二个组合框,您需要将第一个组合框选择更改提交。 However why not just use the standard event? 但是,为什么不只使用标准事件呢?

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //Here use if statements to capture what value is set
        if (comboBox1.SelectedIndex = 1)
        //If selected value is Vehicles
        {
            //Then SELECT * FROM MainCate WHERE MainCate = 'Vehicles'
            //This is possibly incorrect as I don't know how your DBTable is structured

            //Same code as before
            //Set this data to the second combobox
        }
    }

OK? 好? So look into implementing this, if you want to refactor this you could, rather than using IF statements you could parametrise - 因此,请考虑实现这一点,如果您想重构它,可以使用参数而不是使用IF语句-

 string result = comboBox1.SelectedItem.ToString();

 SELECT * FROM MainCate WHERE MainCate = result

Obviously this won't compile so don't copy then paste it, then come back saying it doesn't work. 显然,它将无法编译,因此请不要复制然后粘贴,然后回来说它不起作用。 It needs to be implemented like you did before, but rather than hardcode the result each time, use the parameter. 它需要像以前一样实现,但不要每次都对结果进行硬编码,而应使用参数。

Personally I wouldn't have this all in one class, however you may prefer this way. 就我个人而言,我不会在一堂课中拥有所有这些,但是您可能更喜欢这种方式。

Actually, you don't need another sql query,because you already get all maincate records from database.You can simply use dictionary to store this records. 实际上,您不需要其他sql查询,因为您已经从数据库中获取了所有maincate记录。您只需使用字典即可​​存储该记录。

First define a Dictionary<string,List<string>> 首先定义一个Dictionary<string,List<string>>

Define it here(!) 在这里定义它!

 DataSet ds1;
 DataSet ds2;
 Dictionary<string,List<string>> allRecords = new Dictionary<string,List<string>>();

Then: (i edit your code) 然后:(我编辑您的代码)

SqlDataAdapter daMain = new SqlDataAdapter("SELECT * FROM MAINCATE", conn);
ds1 = new DataSet();
daMain.Fill(ds1, "Maincate");

DataTable dt = ds1.Tables["MAINCATE"];
foreach (DataRow dr in dt.Rows)
{
   List<string> SubCats = new List<string> {
     dr["Subcat1"].ToString(), 
     dr["Subcat2"].ToString(),
     dr["Subcat3"].ToString(),
     dr["Subcat4"].ToString()
   };
 allRecords.Add(dr["mainCate"].ToString(),SubCats);
 mainCatU.Items.Add(dr["mainCate"].ToString());
}

mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
mainCatU.Enabled = true;

Then you need to handle mainCatU selectionchanged like this: 然后,您需要处理如下更改的mainCatU选择:

if(allRecords.ContainsKey(mainCatU.SelectedItem.ToString())) {
    subCatU.DataSource = allRecords[mainCatU.SelectedItem.ToString()];
}

ComboBox1, ComboBox2 -- you just want to populate ComboBox2 using ComboBox1 Select change. ComboBox1,ComboBox2-您只想使用ComboBox1选择更改来填充ComboBox2。 So, At first bind your ComboBox1. 因此,首先绑定您的ComboBox1。 Then cretae an event for ComboBox1: 然后为ComboBox1创建一个事件:

 private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
                {
                    string value1 = ComboBox1 .SelectedValue.ToString();
                    LoadComboBox2 ();        
                }

And Get your ComboBox1 selected value and use it to populate ComboBox2 . 然后获取您的ComboBox1选定值,并使用它来填充ComboBox2。

private void LoadComboBox2 ()
        {
            DataRow dr;

            SqlConnection con = new SqlConnection(@"Data Source=name;Initial Catalog=dbName;User ID=sa;Password=sa123");
            con.Open();
            SqlCommand cmd = new SqlCommand("select id,name from table where id=@ID", con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);

            dr = dt.NewRow();
            dr.ItemArray = new object[] { 0, "--Select--" };
            dt.Rows.InsertAt(dr, 0);

            ComboBox2 .ValueMember = "ID";

            ComboBox2 .DisplayMember = "Name";
            ComboBox2 .DataSource = dt;
            con.Close();

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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