与多个字段绑定列表框
我正在使用VS2010 for c#。我在桌面上有一些数据与多个字段绑定列表框
得分(team1,team2,battingteam,bowlingteam,score)我正在使用bindingSource将它与我的listBox绑定。问题是我只能在列表框的DisplayMember属性中显示一个成员(例如,仅限于team1或team2)。我想要做点像
team1 + " vs " + team2 + ": " + battingteam +" Score: " + score
该怎么做?
我不知道你有哪些数据类型的数据......但是例如,如果你有它们在DataTable
从db返回你可以创建List<string>
对象并迭代数据表行并在列表对象中创建具有格式化数据的项目只要你想和结束绑定列表对象的列表框直接如下
List<string> teams = new List<string>();
foreach (DataRow dataRow in teamsDataTable.Rows)
{
teams.Add(dataRow["team1"].ToString() + " vs " + dataRow["team2"].ToString() + ": " + dataRow["battingteam"].ToString() + " Score: " + dataRow["score"].ToString());
}
listBox1.DataSource = teams;
数据位于包含许多DataTable的DataSet中。每个dataTable都有一个tableAdapter,我用它来获取和填充数据 – SMUsamaShah 2010-06-24 10:43:28
我将尝试该方法 – SMUsamaShah 2010-06-24 10:44:19
您可以使用上面的方法,但通过用dataset.Table替换teamsDataTable.Rows .Rows – 2010-06-24 17:21:43
首先,你可以用一个财产留给你的DisplayMember,让我们说:
ListBox1.DisplayMember = "team1";
现在,去你的形式一个[设计]米ode, 右键单击列表框 - >属性。
在属性窗口的顶部,点击活动(闪电图标),
看看在下面的事件列表格式(属性更改下),然后键入有一些事件名称,比方说:ListBox1Format,和按Enter键。你会看到这一点:
private void ListBox1Format(object sender, ListControlConvertEventArgs e)
{
}
现在写这些下面的行内:
private void ListBox1Format(object sender, ListControlConvertEventArgs e)
{
// Assuming your class called Scores
string team1 = ((Scores)e.ListItem).team1.ToString();
string team2 = ((Scores)e.ListItem).team2.ToString();
string battingteam = ((Scores)e.ListItem).battingteam.ToString();
string score = ((Scores)e.ListItem).score.ToString();
e.Value = team1 + " vs " + team2 + ": " + battingteam +" Score: " + score;
}
就是这样;)
我也试图做类似与SQL的组合找到了和展示会员,这很简单。例如
string sql = "SELECT team1+ 'vs' + team2+ ':' +battingteam + 'Score:' + score";
sql += "AS newColumnNametbl from table";
ListBox lst = new ListBox();
lst.DataSource = ds; //datasource created
lst.DisplayMember = "newColumnNametbl";
我发现它更容易操作sql,然后写很多代码行。希望它有助于简化编码。
我认为C#级别的最佳解决方案是让KeyValuePair的代理,将多个值添加到键或值中,然后将其分配给列表框,如下所示: 假设我有学生类列表,这就是StudentsList,那么:
MyListBox.DrawMode = DrawMode.Normal;
List<KeyValuePair<string, string>> KeyValueList = new List<KeyValuePair<string, string>>();
foreach (Student Curritem in StudentsList)
{
KeyValueList.Add(
new KeyValuePair<string, string>(Curritem.FirstName + " Age: <" + Curritem.Age + ">",
Curritem.ID.ToString()));
}
MyListBox.DisplayMember = "Key";
MyListBox.ValueMember = "Value";
MyListBox.DataSource = KeyValueList;
MyListBox.Refresh();
你使用的是WinForms还是WPF? – Dennis 2010-06-23 00:45:11
我正在使用WinForms – SMUsamaShah 2010-06-23 01:09:46
,其格式为您的数据.. ?? – 2010-06-23 02:00:06