C# C在使用MySqlDataAdapter作为数据源时保留对DataGrid的选择
我的目标是在数据刷新后保留选择 这是我当前如何将数据加载到数据网格视图中的代码 这就是我刷新的方式 问题: 刷新数据后如何保持选择 我试过这个: 但这对我不起作用。这是因为DataGridView有一个点是空的,没有数据,并且由于这两行代码而引发错误C# C在使用MySqlDataAdapter作为数据源时保留对DataGrid的选择,c#,C#,我的目标是在数据刷新后保留选择 这是我当前如何将数据加载到数据网格视图中的代码 这就是我刷新的方式 问题: 刷新数据后如何保持选择 我试过这个: 但这对我不起作用。这是因为DataGridView有一个点是空的,没有数据,并且由于这两行代码而引发错误 int cell1 = (this.agentsDataGridView.CurrentCell.RowIndex); int cell2 = (this.agentsDataGridView.CurrentCell.ColumnIndex)
int cell1 = (this.agentsDataGridView.CurrentCell.RowIndex);
int cell2 = (this.agentsDataGridView.CurrentCell.ColumnIndex);
无效/未选择。您可能应该使用实际数据而不是索引来选择刷新后要选择的行,因为行可能已被添加或删除,或者行的顺序可能无法确定。我建议:
public void RefreshGrid(int selectedID)
{
try
{
// MySQL connection string
using (var conn = new MySqlConnection(ConnectionString.ConnString))
{
using (var mySqlDataAdapter = new MySqlDataAdapter("select id, customer from table;", conn))
{
using (var dataSet = new DataSet())
{
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
labelOrderData.DataSource = DS.Tables[0];
labelOrderData.Columns[0].HeaderText = "ID";
labelOrderData.Columns[1].HeaderText = "Customer";
labelOrderData.Columns[0].Visible = false;
}
}
foreach(DataGridViewRow row in labelOrderData.Rows)
{
if((int)row.Cells[0].Value == selectedID)
{
row.Selected = true;
break;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Refresh - Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
然后在刷新按钮中单击事件:
private void refreshBtn_Click(object sender, EventArgs e)
{
int selectedID = -1;
if (labelOrderData.SelectedRows.Count > 0)
{
selectedID = (int)labelOrderData.SelectedRows[0].Cells[0].Value;
}
RefreshGrid(selectedID);
}
该代码假定您的ID永远不能小于零,并且ID是唯一的整数。如果它们是其他的东西,比如字符串,那么根据需要进行调整,它仍然可以工作。每次执行查询时,您都在创建一个新的数据集。如果只创建一次数据集,适配器将向现有数据集追加数据。在表单加载时调用RefreshGrid将不会work@LV98... ? 我发布的答案中没有表格,所以我不确定你的观点是。。。。?但是,我仍然不明白如果从Form_Load调用它为什么会不起作用。你说它不起作用是什么意思?
public void RefreshGrid(int selectedID)
{
try
{
// MySQL connection string
using (var conn = new MySqlConnection(ConnectionString.ConnString))
{
using (var mySqlDataAdapter = new MySqlDataAdapter("select id, customer from table;", conn))
{
using (var dataSet = new DataSet())
{
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
labelOrderData.DataSource = DS.Tables[0];
labelOrderData.Columns[0].HeaderText = "ID";
labelOrderData.Columns[1].HeaderText = "Customer";
labelOrderData.Columns[0].Visible = false;
}
}
foreach(DataGridViewRow row in labelOrderData.Rows)
{
if((int)row.Cells[0].Value == selectedID)
{
row.Selected = true;
break;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Refresh - Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void refreshBtn_Click(object sender, EventArgs e)
{
int selectedID = -1;
if (labelOrderData.SelectedRows.Count > 0)
{
selectedID = (int)labelOrderData.SelectedRows[0].Cells[0].Value;
}
RefreshGrid(selectedID);
}