2010-10-16 67 views
0

这让我发疯:的WinForms数据网格默认值

我使用一个DataGridView(绑定到数据集)和文本框绑定到数据集(这意味着一切都输入到文本框反映在datagridview的)。 datagridview实际上仅用于显示值(用户无法编辑单元格中的任何内容)。因此:当用户按下添加新记录按钮(由视觉工作室使用绑定导航器等自动创建),我想以编程方式选择这个新行(记住:用户没有能力用鼠标选择)并插入一些值。

我试图用

DefaultValuesNeeded 

事件,但这仅当用户选择用星号指标(什么是不允许用户做)的行射击。

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

在此先感谢!

回答

1

修订:

怎么样Datatable's TableNewRow事件,然后呢?如果在BindingNavigator创建一个新行时触发它,那么这是填充对象的机会。

+0

嗨,斯图亚特!感谢您的回应。由于文档正确地声明“由于无法将新的DataRowView添加到列表,因此绑定到DataView或DataTable时无法设置NewObject属性。”这是棘手的部分,让我头痛(我使用数据表与数据集)! – 2010-10-17 20:19:47

+0

看起来好多了!我会试试这个,让你知道!谢谢 – 2010-10-18 19:38:56

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(任何代码)时加入只是一排空白。希望有人找到更好的方法,但这对我来说迄今为止。