2011-06-16 73 views
2

我有一個綁定到SQLite數據庫的datagridview。現在,我想修改datagridview中的一些字段。datagridView編輯

有4個TEXT列 - 時間戳,消息,類型,散列。 現在我找到了一行,我想右鍵單擊它..它應該有選項 - 「包括」..所以,當我點擊包含在上下文菜單中,我的DGV的類型列應更改爲「包含」從以前的任何東西...(我不希望它被啓用編輯..我只是希望它在程序中更改)如何獲得我點擊並訪問該特定單元格以修改它的索引? ?

回答

1

此代碼你想要做什麼:

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 

     BindingList<User> users = new BindingList<User>(); 
     users.Add(new User(){Name = "Fred", Included = "False", Title="Mr"}); 
     users.Add(new User(){Name = "Sue", Included = "False", Title="Dr"}); 
     users.Add(new User(){Name = "Jack", Included = "False", Title="Mr"}); 

     dataGridView1.DataSource = users; 
    } 


    private void dataGridView1_MouseDown(object sender, MouseEventArgs e) 
    { 
     if (e.Button == System.Windows.Forms.MouseButtons.Right) 
     { 
      DataGridView.HitTestInfo hit = dataGridView1.HitTest(e.X, e.Y); 

      if (hit.rowIndex >= 0) 
      { 
       dataGridView1.ClearSelection(); 
       dataGridView1.Rows[hit.RowIndex].Selected = true; 
       contextMenuStrip1.Show(this.dataGridView1, new Point(e.X, e.Y)); 
      } 
     } 
    } 

    private void includeToolStripMenuItem_Click_1(object sender, EventArgs e) 
    { 
     // Included was the name of the column to change in my example code, 
     // you could also use the index of the column if you know it. 
     dataGridView1.SelectedRows[0].Cells["Included"].Value = "Included"; 
    } 
} 

public class User 
{ 
    public string Name { get; set; } 
    public string Title { get; set; } 
    public string Included { get; set; } 
} 

我想不出通知上下文菜單哪一行的一個更好的辦法是比實際使用所選行選擇DataGridView的屬性 - 你也可以將它存儲在一個類級別的字段中,但我認爲這不是很整潔。

+0

我試過這個..但我得到這個錯誤_Index超出範圍。必須是非負數且小於集合的大小。 參數名稱:index_和'dataGridView1.SelectedRows [0] .Cells [「包含」]。Value =「包含」;'細胞內的「包含」在這裏意味着什麼? – techmanc 2011-06-16 20:19:06

+0

@techmanc包含的是您要編輯的列的名稱。如果您知道它,也可以使用該列的索引。 我也編輯了代碼來照顧索引錯誤 - 這可能是由於右鍵單擊標題。 – 2011-06-16 20:22:06

+0

編輯代碼到底在哪裏處理錯誤?右鍵單擊標題中的?我仍然收到錯誤! :( – techmanc 2011-06-16 20:29:37

1
private void dataGridView_DoubleClick(object sender, EventArgs e) 
{ 
    var grid = (DataGridView)sender; 
    var point = grid.PointToClient(Cursor.Position); 
    var hit = grid.HitTest(p.X, p.Y);  
    MessageBox.Show(string.Format("{0}/{1}", hit.ColumnIndex, hit.RowIndex)); 
} 

代碼沒有經過編譯測試,但理論上這應該可以完成這項工作。


dataGridView.Rows[rowIndex].Cells[cellIndex].Value = "something";

+0

我可以得到我點擊的位置的索引。現在我該如何編輯DGV的單元格? – techmanc 2011-06-16 20:13:40

+1

我已經更新了我的答案,但將來您應該熟悉MSDN上的文檔。這不是很難 - http://msdn.microsoft.com/en-US/library/system.windows.forms.datagridviewrow.cells(v=vs.80).aspx – 2011-06-16 20:36:51