【发布时间】:2014-04-15 12:57:25
【问题描述】:
我有一个这样的数据库(查看DataGridView):
如上图所示,DataGridView 中有复选框。我希望当复选框被选中时,消息框显示一些文本。
我怎样才能做到这一点?
我尝试的是,每当我选中复选框时,消息框永远不会出现,并且在我运行程序时会选中 2014 年 1 月列的第一行,但是当我取消选中并再次检查时,消息框不会出现。
这是我正在使用的代码:
private void Amount(object sender, DataGridViewCellEventArgs e)
{
DataTable _dt = (DataTable)dataGridView1.DataSource;
foreach(DataGridViewRow _row in _dt.Rows)
{
if (Convert.ToBoolean(_row.Cells["4"].Value) == true)
{
MessageBox.Show("Checked");
}
}
}
我把它叫进来了:
dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(this.Amount);
我通过数据库手动添加了复选框,这是我的访问数据库的样子:
非常感谢您的回答!谢谢!
更新:
下面的代码是我修改的来自Sir Daniloloko的代码,我使用List<int>,因为我要检查的ColumnIndex大于1:
dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(this.Amount);
List<int> _columnIndexes;
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void Amount(object sender, DataGridViewCellEventArgs e)
{
_columnIndexes = new List<int>(new int[] { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 });
foreach (int index in _columnIndexes)
{
if (e.ColumnIndex == index)
{
var value = ((DataGridView)sender).Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
if (value != null)
{
if (Convert.ToBoolean(value) == true)
{
MessageBox.Show("Checked. \n" + "Column Number: " + e.ColumnIndex + "", "Checked");
}
else
{
MessageBox.Show("Not Checked. \n" + "Column Number: " + e.ColumnIndex + "", "Not Checked");
}
}
}
}
}
但是从上面的代码来看,当我在DataGridView(运行时)中选中或取消选中复选框时,仍然没有显示MessageBox.Show("Not Checked"); 或MessageBox.Show("Checked");。我想要的是MessageBox 在我选中或取消选中复选框后立即显示,而不是在我点击Enter 或Update 按钮时显示MessageBox(取决于我的复选框)未选中或选中)
非常感谢!
对不起,让你们更困惑了。
已解决:
我忘了在Form_Load 中声明dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(this.DirtyStateChanged);。
非常感谢你们,很抱歉让你们感到困惑。
问候。
【问题讨论】:
-
你如何订阅复选框
Checked事件? -
它看起来没有被选中,它可能不为空。对于这种情况,您没有 MessageBox。顺便说一句,您没有使用 _dt 。您显然需要使用像 CellValueChanged 这样的 DataGridView 事件。
-
数据绑定后运行代码,而不是网格控件加载事件后运行代码
-
您必须将一个事件
CheckChanged关联到每个复选框,然后当您单击它时,您可以“MessageBox.Show("Checked");"或MessageBox.Show("Unchecked");取决于。 -
Cell[3] 看起来像 StudentLastName。
标签: c# winforms datagridview