您试过调试它吗? 我无法尝试它, 因为我不知道您何时会给 FillData 打电话, 除了表格的加载事件之外, 但我不认为这是您有问题的点。 我怀疑问题在于您总是跳过数据GridView1_ DataBinding Confollowlete 的选择部分, 因为 gSselect Plant 总是空的或者设置为第一行 。
发生这种情况通常是因为选择变更的解雇次数比您想象的要多许多倍, 特别是它被调用在 DataBinding Compllete 之前。 这意味着当您调用 FillData 时, 您应该“ 指示” 您的表格忽略选择变更的事件, 直到 DataBinding Compllete 被执行。 这可以做这样的拼写 :
public partial class frmPlant : Form
{
string gSelectedPlant;
bool ignoreSelChg = false; // <- added this bool
private void frmPlant_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = bindingSource1;
FillData();
dataGridView1.DataMember = "Table";
}
private void FillData()
{
ignoreSelChg = true; // <- set the bool, SelectionChanged won t do anything now
ds = _DbConnection.returnDataSet(_SQlQueries.SQL_PlantSelect);
bindingSource1.DataSource = ds.Tables[0];
}
public DataSet returnDataSet(string txtQuery)
{
conn.Open();
sqlCommand = conn.CreateCommand();
DB = new SQLiteDataAdapter(txtQuery, conn);
DS.Reset();
DB.Fill(DS);
conn.Close();
return (DS);
}
private void dataGridView1_Selectionchanged(object sender, EventArgs e)
{
if (ignoreSelChg) // <- don t do anything before DataBindingComplete
return;
if (dataGridView1.SelectedRows.Count > 0)
{
gSelectedPlant = dataGridView1.SelectedRows[0].Cells["PlantId"].Value.ToString();
}
}
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
int selectedIndex;
if (!string.IsNullOrEmpty(gSelectedPlant) && e.ListChangedType == ListChangedType.Reset)
{
ignoreSelChg = false; // <- reset the bool, SelectionChanged get executed again
if (ds.Tables.Count > 0)
{
selectedIndex = bindingSource1.Find("PlantId", gSelectedPlant);
if (selectedIndex <= 0)
selectedIndex = 0;
dataGridView1.Rows[selectedIndex].Selected = true;
}
else
{
gSelectedPlant = string.Empty;
}
}
}
}
您可以在此查看 Mark Rideout 的文章 : [http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/01f937af-d0d0-4de5-8919-088e88ec5af77/][1]