看板 C_Sharp 關於我們 聯絡資訊
※ 引述《kevin8685 (最愛maki~!)》之銘言: : 以下是我修改過後的 : 刪除按鈕 : 目前有個問題 : 執行後 可以成功進行第一次刪除 : 但是第二次就會卡住.. : 重開程式後 還是一樣 : 第一次成功 第二次卡住 : private void button1_Click(object sender, EventArgs e) : { : dt.Clear(); : ListBox.SelectedIndexCollection sic = : this.listBox1.SelectedIndices; : StreamReader item = new StreamReader("product.txt", : Encoding.UTF8); : while (!item.EndOfStream) : { : string[] item2 = item.ReadLine().Split(' '); : dr = dt.NewRow(); : dr["Key"] = item2[0]; : dr["Value"] = item2[1] + " " + item2[2]; : dt.Rows.Add(dr["Value"], dr["Key"]); : } : item.Close(); : int count = listBox1.SelectedItems.Count; : if (count > 1) : { : if (sic.Count == 0) : { : MessageBox.Show("您沒有選取任何項目。"); : } : else : { : for (int i = 0; i < sic.Count; i++) : { : list.Add(sic[i]); : } : list.Sort(); : for (int j = 0; j < sic.Count; j++) : { : int a = list[list.Count - (j + 1)]; : dt.Rows.Remove(dt.Rows[a]); : MessageBox.Show(a.ToString()); : } : } : } : StreamWriter sw = new StreamWriter("product.txt"); : for (int i = 0; i < dt.Rows.Count; i++) : { : sw.WriteLine(dt.Rows[i]["Key"].ToString() + " " + : dt.Rows[i]["Value"].ToString()); : } : sw.Close(); : BindingSource bs = new BindingSource(); : bs.DataSource = dt; : listBox1.DataSource = bs; : listBox1.DisplayMember = "Value"; : listBox1.ValueMember = "Key"; : dt.AcceptChanges(); : } : 之所以把listBox1的項目存在記事本~是想要把它當成資料庫用? 可以在關閉程式後儲存? 個人認為在Form_Load階段把listBox1的項目讀進來就好了 不需要在按下刪除按鈕時又把記事本的內容讀進來 另外SelectedIndices和SelectedItems就這邊的需要來說~用其中一個就好了 以下是我改過可以跑的程式: if (sic.Count == 0) { MessageBox.Show("您沒有選取任何項目"); } else { //原本我也以為底下這個把選取項目指標存起來的動作是多餘的 //實作後才知道似乎是有這個必要 for (int i = 0; i < sic.Count; i++) { list.Add(sic[i]); } BindingSource bs1 = listBox1.DataSource as BindingSource; for (int j = sic.Count - 1; j >= 0; j--) { bs1.RemoveAt(list[j]); //假設在listBox1選取多項 //在移除項目之後,原本紀錄多項的sic會跟著變動,但不規則 //我觀察到的現象是選3個,移除1個後,卻只剩下1個...囧 //所以只好用list先把選到的指標存起來,在移除時取用 //原po似乎也觀察到不能從前面開始移除,否則移除1個過後 //剩下的指標就不正確了,所以要從後面開始移除 } //原po忘了清除這個全域變數list,下次再刪除就... //實際上我認為list的生命週期應該只活在這個事件 //不應該弄成全域變數,稍不注意就會造成未預期的結果 list.Clear(); } StreamWriter sw = new StreamWriter("product.txt"); DictionaryEntry a; for (int i = 0; i < listBox1.Items.Count; i++) { a = (DictionaryEntry)listBox1.Items[i]; sw.WriteLine(a.Key.ToString() + " " + a.Value.ToString()); } sw.Close(); 另外...要不是原po有寄程式碼給我 我想可能又會再上來問為什麼全部刪除再加入一個項目後就不能用了... 原因在於"加入"這個事件裡~寫入記事本那段~一開頭就給它Environment.Newline 那程式下次再執行~一開頭就跑到那段~自然就掛點了 這個的解法~個人會傾向於在寫入時就寫入正確的資料 而不會讓它寫入空白後~再寫一堆程式去防... By the way...其實這些東西~Trace一下就看得出來死在哪了... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 163.15.180.2 ※ 編輯: andymai 來自: 163.15.180.2 (06/15 19:36)
kevin8685:感謝A大!! 昨天還給我了不少幫助^^ 我會在努力XD 06/16 00:08