级联组合框来自数据库

时间:2014-07-06 22:25:14

标签: c# mysql

我有两个组合框:

ComboBox1 - 显示我的数据库中的名称,按预期工作

ComboBox2 - 应显示与Combobox1中该名称相关的年龄, 另外,我有一个文本框,应该显示与ComboxBox1(名称)和ComboxBox2(年龄)相关联的Son的名称

MySQL DataSet:

Name | Age | Son's Name
mark | 23  | john
mark | 22  | dell
mark | 30  | jack
joe  | 20  | joel
joe  | 22  | jason

例如,当我打开comboxBox1并选择" Mark"时,ComboBox2应该显示年龄[23,22,30]。那么当我选择一个年龄(比方说22)时,文本框应显示" dell"

Image of Application

void Fillcombo() {
    string constring = "datasource=localhost;port=3306;username=root;password=root";
    string Query = " select * from  database.check WHERE fathername  IS NOT NULL ;";
    MySqlConnection conDataBase = new MySqlConnection(constring);
    MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
    MySqlDataReader myReader;

    try
    {
        conDataBase.Open();
        myReader = cmdDatabase.ExecuteReader();

        while (myReader.Read())
        {
            string sname = myReader.GetString("fathername");
            comboBox1.Items.Add(sname);
        }
    }
}

///// and i dont know what to write in combobox1 and combobox2 //////

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}

1 个答案:

答案 0 :(得分:0)

没有额外的代码,我有伪代码来帮助你:

FatherComboBox.SelectedIndexChanged += new System.EventHandler(FatherComboBox_SelectedIndexChanged);

private void FatherComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
    ComboBox comboBox = (ComboBox) sender;

    string FathersName = (string) combo.SelectedValue;

    //Code to populate childrens ages in ages combo box
}

AgesComboBox.SelectedIndexChanged += new System.EventHandler(AgesComboBox_SelectedIndexChanged);

private void AgesComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
    ComboBox comboBox = (ComboBox) sender;

    string Age = (string) ComboBox.SelectedValue;

    //Code to select from database where age and fathers name == values given
    textbox.Text = queryResults
}