Winforms datagrid默认值

时间:2010-10-16 19:58:22

标签: winforms datagridview

这让我很生气:

我正在使用datagridview(绑定到数据集),文本框绑定到数据集(这意味着键入文本框的所有内容都会反映在datagridview中)。 datagridview实际上仅用于显示值(用户无法编辑单元格中的任何内容)。

所以:当用户按下添加新记录按钮(由visual studio使用绑定导航器等自动创建)时,我想以编程方式选择这个新行(记住:用户无法用鼠标选择)和插入一些值。

我尝试使用

DefaultValuesNeeded 

事件,但只有当用户选择带星号指示符的行时才会触发(不允许用户执行此操作)。

我如何模拟这种行为?我应该采取另一种方法吗?

提前致谢!!

2 个答案:

答案 0 :(得分:2)

正在寻找我目前这样做的替代方案,只是想让你了解我所知道的几种方式。当使用*(新行)或使用BindingNavigator时,这两个都将设置默认值。

private void CityBindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
    // Simply set the default value to the next viable ID, will automatically set the value when needed.
    locationDataSet.CITY.CITY_IDColumn.DefaultValue = CityTableAdapter.GetNewID(); // ++maxID;
}

或者

private void CityDataGridView_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
    // Gets called when datagridview's */NewRow is entered.
    e.Row.Cells[0].Value = CityTableAdapter.GetNewID(); // ++maxID;
}

private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
{
    // BindingNavigator button's AddNewItem automatic tie-in to bindingSource's AddNew() is removed
    // This sets the current cell to the NewRow's cell to trigger DefaultValuesNeeded event
    CityDataGridView.CurrentCell = CityDataGridView.Rows[CityDataGridView.NewRowIndex].Cells[1];
}

我真的希望用这个......

private void CityBindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
    // Cast your strongly-typed bindingsource List to a DataView and add a new DataRowView 
    DataRowView rowView = ((DataView)CityBindingSource.List).AddNew();
    var newRow = (LocationDTSDataSet.CITYRow)rowView.Row;
    newRow.CITY_ID = CityTableAdapter.GetNewID();
    newRow.CMMT_TXT = "Whatever defaults I want";
    e.NewObject = rowView;
}

但是当使用BindingNavigator或任何基于代码的bindingSource.AddNew()添加时,它只会产生一个空白行。希望有人找到更好的方法,但到目前为止这对我有用。

答案 1 :(得分:1)

修订:

那么Datatable's TableNewRow事件怎么样?如果在BindingNavigator创建新行时触发,那么就可以填充该对象了。