Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind ListBox with multiple fields

I am using VS2010 for c#. I have some data there in a table

Scores(team1,team2,battingteam,bowlingteam,score) I am using bindingSource to bind it with my listBox. The problem is that i can show only one member in DisplayMember property of listbox (e.g. team1 or team2 only). I want to do something like

team1 + " vs " + team2 + ": " + battingteam +" Score: " + score

how to do that?

like image 936
SMUsamaShah Avatar asked Dec 04 '22 12:12

SMUsamaShah


2 Answers

First, you can leave your DisplayMember with one property, let's say:

ListBox1.DisplayMember = "team1";

Now, go to your form in a [Design] mode, right click on the ListBox -> Properties.

In the top of the Properties window, click on Events (lightning icon),

look for Format in the events list below (under Property Changed) and type there some event name, let's say: ListBox1Format , and press Enter. You will see this:

private void ListBox1Format(object sender, ListControlConvertEventArgs e)
{

}

And now write these following lines inside:

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;
}

That's it ;)

like image 199
Eliran Kuta Avatar answered Dec 06 '22 02:12

Eliran Kuta


I don't know in which data type you have your data ... but for example if you have them in DataTable returned from db you can create List<string> object and iterate datatable rows and create items in list object with formatting data as you want and by end bind list object to your listbox directly as below

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;
like image 35
Amr Badawy Avatar answered Dec 06 '22 00:12

Amr Badawy