0
我有兩個listboxes.the留下一個從該代碼的約束和值都到了詞典:
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();
}
我想移動選擇的項目使用此字典的第二個(右列表框2)。「ID」是tha值,「PLAYER」是顯示的文本。我想使用兩個按鈕。一個將項目發送到右側的列表框2,一個將選定的項目移回到第一個列表框1。
任何建議?A嘗試下面的代碼,但不工作.ADD()是用於移動項目的類,REMOVE()用於移回項目。
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);
}
}
}
圖片顯示了使用從梅德代碼的結果,但我需要只顯示文本,並保存在某個地方的ID(也許在一個ArrayList或字典),因爲我需要獲得所有的ID並將它們轉移到另一個winform中的新列表框中
將以下代碼添加到Dmitry的代碼中,該應用程序正在運行完美。
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();
}
}
}
用一種新的形式button7一個新的列表框需要的所有項目從listbox2(正確的),並有兩個ID(鍵)和value.Many感謝梅德!
是的這是工作。這將移動項目,因爲它顯示在新的形象。我只想顯示文本並將ID保存到其他地方。可能在一個數組列表或字典中,因爲我需要一個新按鈕來獲取所有ID並將它們傳送到另一個WINFORM中的新列表框。 – Apollon
已更新示例。唯一的變化是在'ListItem.ToString'方法中。現在只會顯示文字。 – Dmitry
Thanks.Now是否有可能獲得列表框2的所有ID並在另一個winform中填充新的列表框? – Apollon