C#中用DateGridView显示数据库如下,如果要加一个按钮,名为保存,一按按钮可以保存DateGridView中的数据

2025-02-27 11:48:06
推荐回答(2个)
回答1:

右击控件,添加列,将类型设置为datagridviewbuttoncolumn。页眉也自己设置,一般是删除或者是修改。
这是按钮点击事件的代码,你可以参考下
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (Form1.type == 0)
{
if (e.ColumnIndex == 0)
{
this.Height = 471;
textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
textBox3.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
textBox4.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
textBox5.Text = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString();
textBox6.Text = dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString();
comboBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[7].Value.ToString();
}
else if (e.ColumnIndex == 1)
{
if (MessageBox.Show("确实要删除吗?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
try
{
String ss = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
scn.Open();
SqlCommand scm = new SqlCommand("delete from BookInf where BookId='" + ss + "'");
scm.Connection = scn;
int i = scm.ExecuteNonQuery();
if (i != 0)
{
MessageBox.Show("删除成功!", "提示");
}
else
{
MessageBox.Show("删除失败!", "提示");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
SqlDataAdapter sdd = new SqlDataAdapter("select * from BookInf", scn);
DataTable dt = new DataTable();
sdd.Fill(dt);
dataGridView1.DataSource = dt;
scn.Close();
}
}
}
}
}

回答2:

楼上 人家说要实现保存的功能 你却给个删除。不过方法可以 改下SQL语句就OK了。