基本流程
1,MySQL数据表设置自增列,主键,not null,例如定义:Inspect_ID
2,在WPF DataGrid xaml中绑定对应的Inspect_ID列,设为首列,只读,隐藏
3,设置DataGrid的SelectionUint为FullRow属性
4,在窗体加载事件中绑定 DATA_GRID.SelectedValuePath = “Inspect_ID”;
5,设置一个静态变量,作为更新数据库的判定条件,进入单元格编辑状态,赋初值,结束编辑状态,取值进行比较
6,将回车换行改为回车移入下一个单元格
7,实现Ds.Tables[0].RowChanged、Ds.Tables[0].ColumnChanged、DATA_GRID.PreviewKeyDown、DATA_GRID.BeginningEdit、DATA_GRID.CellEditEnding 五个事件处理程序
最终实现效果:无需换行,编辑完单元格,立即更新数据库
public static string preValue { get; set; }
public string Table { get; set; } //当前表名
public static DataSet Ds { get; set; }
public static int CurrentPage { get; set; } //当前分页
public static int PageTotal { get; set; } //总页数
private void InspectRecordLoaded(object sender, RoutedEventArgs e)
{
//生成当前分页的DataSet,此处取最后一页
CurrentPage = SqlHelper.PageSize(Table);
PageTotal = CurrentPage;
Ds = SqlHelper.MakeData(Table, CurrentPage);
Ds.Tables[0].RowChanged += new DataRowChangeEventHandler(Data_Rowchanged);
Ds.Tables[0].ColumnChanged += new DataColumnChangeEventHandler(Data_Columnchanged);
((this.FindName("DATA_GRID")) as DataGrid).ItemsSource = Ds.Tables[0].DefaultView;
DATA_GRID.SelectedValuePath = "Inspect_ID";
DATA_GRID.PreviewKeyDown += new KeyEventHandler(DATA_GRID_PreviewKeyDown);
DATA_GRID.BeginningEdit += new EventHandler<DataGridBeginningEditEventArgs>(DATA_GRID_BeginningEdit);
DATA_GRID.CellEditEnding += new EventHandler<DataGridCellEditEndingEventArgs>(DATA_GRID_CellEditEnding);
}
private void DATA_GRID_PreviewKeyDown(object sender, KeyEventArgs e)
{
var uie = e.OriginalSource as UIElement;
if (e.Key == Key.Enter)
{
uie.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
e.Handled = true;
}
}
private void Data_Columnchanged(object sender, DataColumnChangeEventArgs e)
{
UpdateDatabase(e.Column.Table);
}
private void Data_Rowchanged(object sender, DataRowChangeEventArgs e)
{
UpdateDatabase(e.Row.Table);
}
private void DATA_GRID_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
preValue = (e.Column.GetCellContent(e.Row) as TextBlock).Text;
}
private void DATA_GRID_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
string newValue = (e.EditingElement as TextBox).Text;
if (newValue != preValue && DATA_GRID.SelectedValue != null)
{
//取得单元格的行索引和列索引
int editRowIndex = e.Row.GetIndex();
int editColumnIndex = e.Column.DisplayIndex;
//主动设置该单元格对应的Ds.Tables[0]所在行为已修改状态,触发RowChanged事件
Ds.Tables[0].Rows[editRowIndex].SetModified();
(e.EditingElement as TextBox).Text = newValue;
}
}
public static void UpdateDatabase(DataTable table)
{
MySqlConnection mySqlCon = SqlHelper.GetMySqlConnection();
try
{
mySqlCon.Open();
string sql = "select * from e_1";
MySqlDataAdapter mySqlAdap = new MySqlDataAdapter(sql, mySqlCon);
MySqlCommandBuilder cb = new MySqlCommandBuilder(mySqlAdap);
cb.GetUpdateCommand();
mySqlAdap.Update(table);
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
table.RejectChanges();
}
finally
{
if (mySqlCon.State == ConnectionState.Open)
{
mySqlCon.Close();
}
}
}