为我的办公室开发应用程序,在我的应用程序中有一个链接到mysql数据库的datagrid视图。本地用户可以使用datagridview更新数据库,但他们无法删除任何重新编码。我想实现一个方法,用户在datagridview中选择完全原始并删除它,以及尽快删除数据库记录。我设法使用下面的代码选择和删除datagridview行,但它不更新数据库
private void button60_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
}
}
这是我通常用于在datagrid视图中查看数据库数据的连接字符串。我没有很好的知识将这两者结合起来。有人请告诉我如何做到这一点
我的连接字符串
private void showdatagrid() {
string constring = string.Format("datasource='{0}';username=******;port=3306;password=***********;Connect Timeout=20000;Command Timeout=28800", dbserverip.Text);
MySqlConnection conwaqDatabase = new MySqlConnection(constring);
MySqlCommand cmdwaqDatabase = new MySqlCommand(" select * from warit.loans ; ", conwaqDatabase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdwaqDatabase;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
dataGridView1.DataSource = bsource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
答案 0 :(得分:0)
试试这段代码
private void button60_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
{
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
int loannumber = dataGridView1.Rows[oneCell.RowIndex].Cells['index of loannumber column in datagridview'].Value; // assuming loannmber is integer
string username = dataGridView1.Rows[oneCell.RowIndex].Cells['index of username column in datagridview'].Value; // assuming username is string
/* Now create an object of MySqlConnection and MySqlCommand
* and the execute following query
*/
string query = string.Format("DELETE FROM table_name WHERE loannumber = {0} AND username = '{1}'", loannumber, username);
}
}
}
答案 1 :(得分:0)
string connection = "server = URL; uid = user; pwd = password; database = database;";
using (MySqlConnection conn = new MySqlConnection(connection)) {
conn.Open();
string idLocRemv = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string removeVolCred = "DELETE FROM TableName WHERE ID = " + idLocRemv;
using (MySqlCommand command = new MySqlCommand(removeVolCred, fbcConn)) {
command.ExecuteNonQuery();
}
conn.Close();
}
应用必要的异常处理程序。 (最后尝试抓住)
此外,您需要在之后重新加载DataGridView。