你如何阅读DataGridViewCheckBoxColumn的vaue? [英] How do you read the vaue of a DataGridViewCheckBoxColumn ?
问题描述
大家好;
我有一个带有DataGridView控件的Windows窗体,我想要读取的多个DataGridViewCheckBoxColumn类型列(选中或取消选中) 。一切都是无限的。
现在这当然应该是最简单的事情,但事情并没有发挥作用。例如,我有一个名为选项的列,我想查看是否选中了特定行的选项复选框。只是为了好玩,阅读价值并将其显示在一个消息框中:
我试过了
Hi all;
I have a Windows form with a DataGridView control, and there are several columns of type DataGridViewCheckBoxColumn that I want to read (checked or unchecked). Everything is unbounded.
Now this of course should be the simplest thing, but something isn''t working as it should. For example, I have a column called "Options", and I want to see if a particular row''s "Options" checkbox is checked or not. Just for fun, read the value and display it in a message box:
I''ve tried
if (dataGridView.Rows[dataGridView.CurrentCell.RowIndex].Cells[dataGridView.Columns["Options"].Index].Value != null)
{
// Do some stuff
MessageBox.Show(dataGridView.Rows[dataGridView.CurrentCell.RowIndex].Cells[dataGridView.Columns["Options"].Index].Value.ToString());
}
我也试过
and I''ve also tried
DataGridViewCheckBoxCell cbox = new DataGridViewCheckBoxCell();
cbox = dataGridView.Rows[dataGridView.CurrentCell.RowIndex].Cells[dataGridView.Columns["Options"].Index];
if (cbox.Value != null)
{
// Do some stuff
MessageBox.Show(cbox.Value.ToString());
}
无论何时选中或取消选中此框,值始终为
Whenever I check or uncheck the box, the value is always
null
因此显示MessageBox的代码永远不会运行。
我知道我遗漏了一些基本的东西,但我看不到它。为什么我一直在阅读
and so the code to show the MessageBox never runs.
I know I''m missing something basic, but I can''t see it. Why am I reading
null
,无论复选框状态如何?
all the time, regardless of the checkbox state?
推荐答案
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCheckBoxCell checkbox = (DataGridViewCheckBoxCell)dataGrid_ModelControls.CurrentCell;
bool isChecked = (bool)checkbox.EditedFormattedValue;
}
试试这个....
Try this ....
我刚试过你的代码:
I just tried your code:
private void button1_Click(object sender, EventArgs e)
{
dgvData.Rows.Add(true);
dgvData.Rows.Add(false);
dgvData.Rows.Add(true);
dgvData.Rows.Add(false);
}
private void button2_Click(object sender, EventArgs e)
{
if (dgvData.Rows[dgvData.CurrentCell.RowIndex].Cells[dgvData.Columns["chkBox"].Index].Value != null)
{
// Do some stuff
MessageBox.Show(dgvData.Rows[dgvData.CurrentCell.RowIndex].Cells[dgvData.Columns["chkBox"].Index].Value.ToString());
}
}
我得到的只是真实或假,正如我所料。
你确定它正在执行该代码吗?因为你通常不会得到一个MessageBox - 你会得到一个NullReferenceException,因为你调用ToString的值必须为null - 这不会起作用!
And all I get is "true" or "false", as I would expect.
Are you sure it is executing that code? Because you would not normally get a MessageBox - you would get a NullReferenceException as the value you are calling ToString on would have to be null - which won''t work!
这篇关于你如何阅读DataGridViewCheckBoxColumn的vaue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!