我有一个绑定到SQLite数据库的datagridview。现在,我希望修改datagridview中的一些字段。
有4个TEXT列 - 时间戳,消息,类型,哈希。 现在我找到一行,我想右键单击它..它应该有选项 - “包含”..所以,当我在上下文菜单中单击包含时,我的DGV的Type列应该从“include”更改为以前是什么...(我不希望它被启用编辑..我只是想让它在程序内更改)我如何获得我点击的索引并访问该特定单元格来修改它?
答案 0 :(得分: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";
答案 1 :(得分: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的选定行属性 - 你也可以将它存储在类级别字段中,但我不认为非常整洁。