I have two listboxes.the left one is bound from this code and the values goes to a dictionary:
public void Roster_Shown(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=Basketball;Integrated Security=True;User ID=apo;Password=nia2");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT PLAYERS.ID, PLAYERS.NO, PLAYERS.SURNAME, PLAYERS.FIRSTNAME, CAST(PLAYERS.NO AS VARCHAR) + ' - ' + PLAYERS.SURNAME + ', ' + PLAYERS.FIRSTNAME AS PLAYER FROM PLAYERS INNER JOIN TEAMS ON PLAYERS.TEAM_ID = TEAMS.ID WHERE (TEAMS.NAME ='" + ht + "')ORDER BY PLAYERS.NO", con);
DataTable dt = new DataTable();
sda.Fill(dt);
listBox1.DataSource = dt;
listBox1.DisplayMember = "PLAYER";
listBox1.ValueMember = "ID";
dictionary = new Dictionary<string,string>();
for (int i = 0; i < dt.Rows.Count; i++)
dictionary.Add(dt.Rows[i]["ID"].ToString(), dt.Rows[i]["PLAYER"].ToString());
con.Close();
}
I want to move the selected items to the second(right listbox2) using this dictionary.The "ID" is tha value and the "PLAYER" is the shown text. I want to use two buttons.One to send items to the right listbox2 and one to move back the selected items to the first listbox1.
Any suggestion?A Try the follow code but is not working.ADD() is the class for moving items and REMOVE() is for move back the items.
private void button1_Click(object sender, EventArgs e)
{
ADD();
}
private void ADD()
{
listBox2.DataSource = new BindingSource(Roster_Shown.dictionary, null);
listBox2.DisplayMember = "ID";
listBox2.ValueMember = "PLAYER";
}
private void button2_Click(object sender, EventArgs e)
{
REMOVE();
}
private void REMOVE()
{
int c = listBox2.Items.Count - 1;
for (int i = c; i >= 0; i--)
{
if (listBox2.GetSelected(i))
{
listBox1.Items.Add(listBox2.Items[i]);
listBox2.Items.RemoveAt(i);
}
}
}
Image shows the result using the code from Dmitry,but I need to show only the text and to save somewhere the id(maybe in an arraylist or dictionary) because I will need to get all the ids of the second list and transfer them to a new listbox in another winform
Adding the following code to Dmitry's code the app is working perfect.
public void button7_Click(object sender, EventArgs e)
{
if (listBox2.Items.Count > 4)
{
if (listBox4.Items.Count > 4)
{
Game game = new Game();
foreach (ListItem item in listBox2.Items)
{
dictionaryHome.Add(item.Id, item.Name);
game.listBoxHome.DisplayMember = dictionaryHome.Values.ToString();
game.listBoxHome.ValueMember = dictionaryHome.Keys.ToString();
game.listBoxHome.DataSource = (from Values in dictionaryHome.Values select Values).ToList();
//int itemId = item.Id;
}
this.Hide();
game.Show();
}
}
}
with button7 a new listbox in a new form takes all the items from listbox2(right one)and have both id(key) and value.Many thanks to Dmitry!!!