";指定的强制转换无效”;WinForm应用程序出错

本文关键字:无效 WinForm 应用 程序出错 转换 quot | 更新日期: 2023-09-27 18:26:40

我使用的是Microsoft Visual Studio Community 2015版。关于这个问题有很多问题,但我的问题并没有完全涵盖在内。基本上,我在Windows窗体应用程序(C#)中使用MySql(phpmyadmin-wamp)数据库。我正在创建一个简单的windows表单应用程序来获取输入、更新/删除数据、在数据网格视图中显示元素和搜索任何记录。我在更新记录时遇到问题。编译器不断地给我同样的错误,即;"指定的强制转换无效"。我的代码如下:.

private void button_update(object sender, EventArgs e)
{
try
   { 
    MySqlConnection cn = new MySqlConnection("server=localhost;port=3306;database=hyder;uid=root;Encrypt=false;AllowUserVariables=True;Usecompression=True;");
    int id = (int)dataGridView1.SelectedRows[0].Cells[0].Value;
    cn.Open();
    MySqlCommand cmd = new MySqlCommand();
    cmd.Connection = cn;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "update record set r_name='" + textBox1.Text + "',r_address='" + textBox2.Text + "',r_phone='" + textBox3.Text + "',r_comment='" + textBox4.Text + "' where r_id='" + id;
    cmd.ExecuteNonQuery();
    MessageBox.Show("Record Updated!");
    cn.Close();
 }
catch (Exception x) { MessageBox.Show("Error:" + x.Message); }
}

此代码有什么问题?

";指定的强制转换无效”;WinForm应用程序出错

尝试更换

int id = (int)dataGridView1.SelectedRows[0].Cells[0].Value;

带有

int id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value);