基于另一个组合框的组合框项目从 SQL 服务器数据库中选择的项目数据

Combobox items based on another combobox selected items data from SQL Server database

我有两个组合框,其中第一个包含我从 SQL 服务器数据库填充的类别。诀窍是让第二个组合框仅显示数据库中与第一个组合框中所选类别相关联的项目。

这是我的 SQL 代码:

IF @ActionType = 'FetchDataCBOCity'  
BEGIN  
    SELECT DISTINCT ID_City, Name_City 
    FROM City
END

IF @ActionType = 'FetchDataCBOState'  
BEGIN  
    SELECT ID_State, Name_State 
    FROM State 
END

这是我的 C# 代码:

ConnectionTCP.CboFetchData(new List<string> { "FetchDataCBOCity", spName }, "ID_City", "Name_City", comboBox1);
ConnectionTCP.CboFetchData(new List<string> { "FetchDataCBOState", spName }, "ID_State", "Name_State", comboBox2);


 // CBO Fetch Data in db
        public static void CboFetchData( List<string> dataList, string valueMember, string displayMember, ComboBox cbo )
        {
            try
            {
                string phrase = "CBOFETCHDATA" + ">";
                foreach (var data in dataList)
                {
                    phrase += data + ">";
                }

                byte[] message = Encoding.ASCII.GetBytes(phrase.TrimEnd('>'));
                stream.Write(message, 0, message.Length);

                var buffer = getData(tcpClient);

                cbo.DataSource = DataFormatter.DeserializeData(buffer);
                cbo.ValueMember = valueMember;
                cbo.DisplayMember = displayMember;
            }
            catch (Exception e)
            {
                MessageBox.Show("Error: " + e.Message, Client.nameApp, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

谢谢

我想,最简单的方法是将 DataSet 与相关的 DataTable 一起使用,但您可以创建相关的数据源

// Declare combo items
public class ParentInfo
{
    int Id {get; set;}
    string Display {get; set;}
}

public class ChildInfo
{
    int Id {get; set;}
    int ParentId {get; set;}
    string Display {get; set;}
}

// Load lists
List<ParentInfo> _parents;
List<ChildInfo> _children;
// . . . 
// Set parent combo, this one is not changing
cboParents.ValueMemeber = "Id";
cboParents.DisplayMemeber = "Display";
cboParents.DataSourse = _parents;

// . .  . . . 
// Change children for different parents
void OnParent_SelectedIndexChanged( . .  . .)
{
    if (cboParents.SelectedInfex = -1)
    {
        cboChildren.DataSource = null;
        return;
    }
    cboChildren.ValueMemeber = "Id";
    cboChildren.DisplayMemeber = "Display";
    ParentInfo currentP = (ParentInfo)cboParents.SelectedItem;
    cboChildren.DataSourse = _children.Where(c => c.ParentId == currentP.Id).ToList();

}