Zen*_*eno 8 c# datasource datagridview visual-studio winforms
我在Visual Studio(C#)中创建了一个使用datagridview的应用程序.现在,当我分配该datagridview的DataSource时,它会自动选择第一行,并执行我的代码进行选择.由于我经常重新分配该数据源,因此这是不可取的.有没有办法改变它,所以它不会自动进行第一次选择,只依赖于用户的选择?
谢谢!
回应Darshan Joshi的评论:除了自动生成的代码之外,datagridview上唯一改变的是将AutoGenerateColumns设置为false,并设置DataSource属性.我在我的selectionchanged委托中放置了一个MessageBox.Show,它似乎甚至在每次设置数据源时都被调用三次.就在数据加载之前,两次之后.
我无法在加载时将selected设置为false,因为数据源是在某些用户操作之后设置的,而不是在初始化时设置的.
你应该在事件之后调用:ClearSelection:DataBindingComplete
我遇到了同样的问题,这是我的解决方案。
棘手的部分是找到在哪里清除选择...我们只能在 DataGridView 设置选择后清除选择。起初,选择仅准备在 Form.Load 事件中清除,但在 DataGridView.DataSource 的后续设置中,选择在 DataSource 分配后即可直接清除。
public class DataGridView_AutoSelectSuppressed : DataGridView
{
private bool SuppressAutoSelection { get; set; }
public DataGridView_AutoSelectSuppressed() : base()
{
SuppressAutoSelection = true;
}
public new /*shadowing*/ object DataSource
{
get
{
return base.DataSource;
}
set
{
SuppressAutoSelection = true;
Form parent = this.FindForm();
// Either the selection gets cleared on form load....
parent.Load -= parent_Load;
parent.Load += parent_Load;
base.DataSource = value;
// ...or it gets cleared straight after the DataSource is set
ClearSelectionAndResetSuppression();
}
}
protected override void OnSelectionChanged(EventArgs e)
{
if (SuppressAutoSelection)
return;
base.OnSelectionChanged(e);
}
private void ClearSelectionAndResetSuppression()
{
if (this.SelectedRows.Count > 0 || this.SelectedCells.Count > 0)
{
this.ClearSelection();
SuppressAutoSelection = false;
}
}
private void parent_Load(object sender, EventArgs e)
{
ClearSelectionAndResetSuppression();
}
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
14350 次 |
| 最近记录: |