How to handle the CheckBox in MouseClick events?

I have a Problem Guys, I hope you help me..

I want to display the selected data row to my textbox and checkbox and I having a Problem with the CheckBox and the error Cannot implicity convert type string to bool

I set my Checkbox to true or false after saving to the Database so it will show in my Datagridview only True or False not Checked and the Checkbox is the Option if it is undergo that Case...

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)

    {
        foreach (Control control in this.Controls)
        {
            if (control is CheckBox)
                ((CheckBox)(control)).Checked = true;

        }

        foreach (Control control in this.Controls)
        {
            if (control is CheckBox)
                ((CheckBox)(control)).Checked = false;
        }
    }

And in my Mouse Click Event

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)

    {
        txtFam.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
        txtName.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
        txtSevereheadache.Checked =dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
        txtBlurringvision.Checked = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
        txtAbdominal.Checked = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
        txtSeverevomiting.Checked = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
        txtBreathingdifficulty.Checked = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();
        txtConvulsion.Checked = dataGridView1.SelectedRows[0].Cells[7].Value.ToString();
        txtEdema.Checked = dataGridView1.SelectedRows[0].Cells[8].Value.ToString();
        txtVaricosities.Checked = dataGridView1.SelectedRows[0].Cells[9].Value.ToString();
        txtFeverchills.Checked = dataGridView1.SelectedRows[0].Cells[10].Value.ToString();
        txtPain.Checked = dataGridView1.SelectedRows[0].Cells[31].Value.ToString();

You are trying to assign a string value to a boolean property. Eg

txtSevereheadache.Checked = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();

First use debug and see what is the type of dataGridView1.SelectedRows[0].Cells[2].Value , it is probably enough for you to cast Value to bool . So:

txtSevereheadache.Checked = (bool) dataGridView1.SelectedRows[0].Cells[2].Value;


If for some reason dataGridView1.SelectedRows[0].Cells[2].Value is not of type bool , you should parse the string to boolean using Boolean.Parse method. See it on MSDN.

So, something like:

txtSevereheadache.Checked = Boolean.Parse(dataGridView1.SelectedRows[0].Cells[2].Value.ToString());


For differences between Convert.ToBoolean(string) and Boolean.Parse(string) see this thread.

链接地址: http://www.djcxy.com/p/71166.html

上一篇: 更新时如何刷新数据网格视图? C#窗口

下一篇: 如何处理MouseClick事件中的CheckBox?