首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# WinForms:ComboBox 選項透過 Button 新增至 RichTextBox 並支援刪除

     編輯:程式設計綜合問答

需求分析

雙向互動介面:ComboBox 選項 → Button 添加 → RichTextBox 顯示 → 另一 Button 刪除任意行。

核心實現代碼

// 添加按鈕點擊
private void btnAdd_Click(object sender, EventArgs e) {
    if (comboBox1.SelectedItem != null) {
        richTextBox1.AppendText(comboBox1.SelectedItem.ToString() + Environment.NewLine);
    }
}

// 刪除按鈕點擊:刪除游標所在行
private void btnDelete_Click(object sender, EventArgs e) {
    int lineIndex = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart);
    if (lineIndex >= 0 && lineIndex < richTextBox1.Lines.Length) {
        var lines = richTextBox1.Lines.ToList();
        lines.RemoveAt(lineIndex);
        richTextBox1.Lines = lines.ToArray();
    }
}

關鍵 API 說明

  • ComboBox.SelectedItem:獲取當前選中項目物件。
  • RichTextBox.AppendText:高效追加文字不觸發完整重繪。
  • GetLineFromCharIndex + Lines 集合操作:精確定位並移除指定行。

體驗優化建議

  1. 添加前檢查重複項目,避免重複添加。
  2. 刪除前彈出確認對話框(MessageBox.Show)。
  3. 使用 ContextMenuStrip 實現右鍵選單刪除,更符合直覺操作。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved