datagridView edits

本文关键字:edits datagridView | 更新日期: 2023-09-27 17:59:16

我有一个绑定到SQLite数据库的数据网格视图。现在,我想修改数据网格视图中的一些字段。

有4个TEXT列-时间戳、消息、类型、哈希。现在我找到一行,我想右键单击它。它应该有选项-"include"。。因此,当我单击上下文菜单中的include时,我的DGV的Type列应该从以前的内容更改为"include"。。。(我不希望它被启用来编辑。我只希望它在程序中更改。)我如何获得我单击的索引并访问特定的单元格来修改它??

datagridView edits

此代码可以执行您想要的操作:

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的selected row属性更好的方法来通知上下文菜单选择了哪一行——你也可以将其存储在类级字段中,但我认为这并不那么整洁。

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";