[英]Selected value to stay selected in Datagridview after updating in database c#?
我有一個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();
您只需在刷新后設置CurrentCell即可:
var ptCurrentCell = this.DataGridView1.CurrentCellAddress();
-刷新數據
Refresh();
-現在重置當前單元格
this.DataGridView1.CurrentCell = this.DataGridView1.Rows(ptCurrentCell.Y).Cells(ptCurrentCell.X);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.