2012-11-13 51 views
0

這裏是我的表單的圖像。使用datagridview和下拉列表操作

這應該是這樣做的。
1.用戶將選擇要重命名的項目。 (例如用戶選擇「string1」)
2.從下拉列表中選擇新的項目名稱(例如,用戶選擇「新的字符串1」)
注意:下拉列表中的所選項目將是新名稱「 string1「
3.單擊按鈕(點擊按鈕後,這將自動創建已作出的更改)。

enter image description here

現在的問題是:
我怎樣才能在DataGridView中從選定項目上的下拉更改項目名稱?

這裏是我的一些代碼。

public void loadgrid() 
     { 
      DataGridViewCheckBoxColumn checkboxColumn = new DataGridViewCheckBoxColumn(); 
      checkboxColumn.Width = 25; 
      dataGridView1.Columns.Add(checkboxColumn); 

      DataGridViewTextBoxColumn textboxcolumn = new DataGridViewTextBoxColumn(); 
      textboxcolumn.Width = 150; 
      dataGridView1.Columns.Add(textboxcolumn); 

      dataGridView1.Rows.Add(new object[] { false, "string1" }); 
      dataGridView1.Rows.Add(new object[] { false, "string2" }); 
     } 

爲Button1

private void button1_Click(object sender, EventArgs e) 
     { 
      int x = 0; 
      foreach (DataGridViewRow row in dataGridView1.Rows) 
      { 
       DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0]; 
       chk.TrueValue = true; 
       if(chk.Value == chk.TrueValue) // there no chk.Check on datagridview just chk.Selected 
       { 
        //code here 
        //this will test if the checkbox has been checked. 
        //the selected item on the dropdown will be the 
        //new name of the item on the datagridview 
       } 
      } 
       x = x + 1; 
     } 

回答

0

我認爲這會幫助,如果你想改變行的所有字符串與選中的複選框:

   foreach (DataGridViewRow row in dataGridView1.Rows) 
       { 
        if (!row.IsNewRow) 
        { 
         DataGridViewCheckBoxCell chk1 = (DataGridViewCheckBoxCell)row.Cells[0]; 
         if (chk1 != null && chk1.Value!=null && (bool)chk1.Value) // there no chk.Check on datagridview just chk.Selected 
         { 
          string newString = string.Empty; 
          if (comboBox1.SelectedItem != null) 
          { 
           newString = comboBox1.SelectedItem.ToString(); 
           row.Cells[dataGridView1.Columns.Count - 1].Value = newString; 
          } 
         } 
        } 
       } 

如果你想改變字符串只在檢查CheckBox的選定行中可以使用此代碼:

   if(dataGridView1.SelectedRows.Count>0) 
       { 
        DataGridViewRow row = dataGridView1.SelectedRows[0]; 
        if (!row.IsNewRow) 
        { 
         DataGridViewCheckBoxCell chk1 = (DataGridViewCheckBoxCell)row.Cells[0]; 
         if (chk1 != null && chk1.Value!=null && (bool)chk1.Value) // there no chk.Check on datagridview just chk.Selected 
         { 
          string newString = string.Empty; 
          if (comboBox1.SelectedItem != null) 
          { 
           newString = comboBox1.SelectedItem.ToString(); 
           row.Cells[dataGridView1.Columns.Count - 1].Value = newString; 
          } 
         } 
        } 
       } 

,如果你要設置所有選定行(如果可能的話在你DataGridView控制,那麼就遍歷SelectedRows財產

+0

感謝。我會試試看。 – user1647667

+0

布爾有錯誤。 – user1647667

+0

我在發佈前檢查了代碼,它工作正常。你的錯誤究竟在哪裏? –