【发布时间】:2014-03-06 07:35:03
【问题描述】:
我有一个 dataGridView,它从数据库中获取所有数据。 我所做的是创建一个显示所有数据的方法,但问题是,在调用该方法后,滚动返回到我不想发生的顶部。我创建这个方法的目的是为了显示新添加的数据和更新颜色。
private void showAllData()
{
try
{
using (OleDbConnection conn = new OleDbConnection(GlobalVar.connectionString))
using (OleDbDataAdapter sda = new OleDbDataAdapter("SELECT * FROM tblTest", conn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
for (int x = 0; x < dataGridView1.RowCount; x++)
{
if (dataGridView1.Rows[x].Cells["Color"].Value == "Green")
dataGridView1.Rows[x].DefaultCellStyle.BackColor = Color.Green;
else
dataGridView1.Rows[x].DefaultCellStyle.BackColor = Color.Red;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
using (OleDbConnection conn = new OleDbConnection(GlobalVar.connectionString))
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO tblTest (Color) VALUES ('Red')", conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Update dataGridView1 BackColor
showAllData();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
using (OleDbConnection conn = new OleDbConnection(GlobalVar.connectionString))
using (OleDbCommand cmd = new OleDbCommand("UPDATE tblTest SET Color = 'Green' WHERE id = " + dataGridView1.SelectedRows[0].Cells[0].Value, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Update dataGridView1 BackColor
showAllData();
}
【问题讨论】:
标签: c# ms-access datagridview datatable oledb