从网上摘了一段代码,想实现,窗体表格datagridview的数据,修改时为蓝色,保存后为白色,但执行起来,保存时总保存不住数据,代码如下,请问大家给看看哪里不对呢,谢谢;
```c#
这段是原来就有的代码,正常执行,没问题,是查询按钮
private void button1_Click(object sender, EventArgs e)
{
//连接数据库
conn = new SqlConnection("server=localhost;database=Whyy;user=sa;password=whyy@2021");
conn.Open();
//查询条件
SqlString = "select * from w_Qctable1 where productname like '%" + textBox3.Text + "%' and batchNo like '%" + textBox1.Text + "%' and [date] >= '" + dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss") + "'and [date] <= '"</span> + dateTimePicker2.Value.<span class="hljs-constructor">ToString(<span class="hljs-string">"yyyy-MM-dd HH:mm:ss"</span>)</span> + <span class="hljs-string">"' order by date asc ";
//加载数据并显示
try
{
//查询条件和SqlConnection连接
SqlCommand cmd = new SqlCommand(SqlString, conn);
//数据适配器
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
//DataTable存储数据
DataTable dset = new DataTable();
sda.Fill(dset);
dataGridView1.DataSource = dset;
}
catch
{ }
finally
{
conn.Close();
}
以下为摘抄的代码,是用于保存datagridview修改的内容,但执行起来,总保存不住修改的内容;
private DataTable dset = new DataTable();
private SqlDataAdapter sda = new SqlDataAdapter();
private Boolean isUpdate = false;
private void 保存按钮_Click(object sender, EventArgs e)
{
if (isUpdate)
{
try
{
SqlCommand cmd = new SqlCommand(SqlString, conn);
SqlCommandBuilder SCB = new SqlCommandBuilder(sda);
sda.SelectCommand = cmd;
DataTable dset = new DataTable();
sda.Fill(dset);
dataGridView1.DataSource = dset;
sda.Update(dset);
isUpdate = false;
//SqlCommand cmd = new SqlCommand(SqlString, conn);
////数据适配器
//SqlDataAdapter sda = new SqlDataAdapter();
//sda.SelectCommand = cmd;
////DataTable存储数据
//DataTable dt = new DataTable();
//sda.Fill(dt);
//dataGridView1.DataSource = dt;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
MessageBox.Show("更新成功! ");
}
else
{
MessageBox.Show("没有更新内容! ");
}
for (int i = 0; i < dset.Rows.Count; i++)
for (int j = 0; j < dset.Columns.Count; j++)
{
dataGridView1[j, i].Style.BackColor = Color.White;//保存后变回白色
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
isUpdate = true;
dataGridView1[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Blue;//修改内容后变为蓝色
}
```