I was just wondering how to either tick or untick a check box according to the value True
or False
in a GridView
. Similar to writing the value in a TextBox
textBox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
but for
checkBox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
if True = Tick
, if False = Untick
checkBox1.Checked = true;
or
checkBox1.Checked = false;
Full code would be something like:
if (dataGridView1.SelectedRows[0].Cells[0].Value.ToString() == "TRUE")
{
checkBox1.Checked = true;
}
else if(dataGridView1.SelectedRows[0].Cells[0].Value.ToString() == "FALSE")
{
checkBox1.Checked = false;
}
You can't do the code you wrote because the data you pulled from the data grid view is a string and .Checked
requires a boolean.
You need to convert the result to boolean. In
Gridview.CellValueChangedEvent
add code
checkBox1.Checked = (dataGridView1.SelectedRows[0].Cells[0].Value.ToString().ToUpper() == "TRUE");
bool isChecked;
bool.TryParse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString(), out isChecked);
checkBox1.Checked = isChecked;
This means if your string ever changes to "True" or "true" it will still be able to Parse it as a boolean instead of just doing a string check against "TRUE" which could easily break futher down the line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.