基于另一个组合框的组合框项目将SQL Server数据库中选定的项目数据组合在一起



我有两个组合框,第一个组合框中有我从SQL Server数据库中填充的类别。诀窍是让第二个组合框只显示DB中与第一个组合框中所选类别相关联的项目。

这里是我的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();
}

相关内容

  • 没有找到相关文章

最新更新