我有一个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();
}
使用该DataGridView.FirstDisplayedScrollingRowIndex
属性。它设置该行的索引,该行是DataGridView上显示的第一行。
在您的情况下,由于您正在更改DataSource
,可能已添加了新行。您不能使用已选择的行索引。您必须标识先前选择的行(使用任何唯一标识符)并获取其索引,并将上述属性设置为此索引号。
除了重置DataSource
,还可以使用合并查询的表与现有表DataTable.Merge
,并使用刷新网格DataGridView.Refresh
。
或者,您可以再次填充原始数据表。
DataTable origTable = dataGridView1.DataSource as DataTable;
sda.Fill(origtable);
dataGridView1.Refresh();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句