首先声明:private CurrencyManager cmAmend;
初始化:
this.dataGrid1.DataSource = table;
da.TableMappings.Add("wjb","table");//把表映射到数据库
cmAmend = (CurrencyManager)BindingContext[table];
cmAmend.PositionChanged +=new EventHandler(cmAmend_PositionChanged);
/*导航控制*/
private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
if(e.Button.ImageIndex == 0)//首记录
{
cmAmend.EndCurrentEdit();
this.dataGrid1.CurrentRowIndex = 0;
cmAmend.Position = 0;
this.positionid = this.dataGrid1.CurrentRowIndex; }
if(e.Button.ImageIndex == 1)//上记录
{
cmAmend.EndCurrentEdit();
this.dataGrid1.CurrentRowIndex -= 1;
cmAmend.Position = this.dataGrid1.CurrentRowIndex;
this.positionid = this.dataGrid1.CurrentRowIndex;
this.toolBar1.Buttons[0].Enabled = true;
this.toolBar1.Buttons[1].Enabled = true;
this.toolBar1.Buttons[2].Enabled = true;
this.toolBar1.Buttons[3].Enabled = true;
if(this.dataGrid1.CurrentRowIndex == 0)
{
this.toolBar1.Buttons[0].Enabled = false;
this.toolBar1.Buttons[1].Enabled = false;
}
}
if(e.Button.ImageIndex == 2)//下记录
{
cmAmend.EndCurrentEdit();
this.dataGrid1.CurrentRowIndex += 1;
cmAmend.Position = this.dataGrid1.CurrentRowIndex;
this.positionid = this.dataGrid1.CurrentRowIndex;
if(this.dataGrid1.CurrentRowIndex == cmAmend.Count - 1)
{
this.toolBar1.Buttons[2].Enabled = false;
this.toolBar1.Buttons[3].Enabled = false;
}
}
if(e.Button.ImageIndex == 3)//尾记录
{
cmAmend.EndCurrentEdit();
this.dataGrid1.CurrentRowIndex = cmAmend.Count - 1;
cmAmend.Position = this.dataGrid1.CurrentRowIndex;
this.positionid = this.dataGrid1.CurrentRowIndex;
}
if(e.Button.ImageIndex == 4)//新增记录
{
cmAmend.EndCurrentEdit();
DataRow dr = table.NewRow();
table.Rows.Add(dr);
this.dataGrid1.CurrentRowIndex = cmAmend.Count - 1;
cmAmend.Position = this.dataGrid1.CurrentRowIndex;
this.positionid = this.dataGrid1.CurrentRowIndex;
}
if(e.Button.ImageIndex == 5)//删除
{
if(MessageBox.Show("你确定要删除吗?","删除提示",MessageBoxButtons.OKCancel) == DialogResult.OK)
{
cmAmend.RemoveAt(cmAmend.Position);
if(this.dataGrid1.CurrentRowIndex == cmAmend.Count - 1)
{
this.toolBar1.Buttons[2].Enabled = false;
this.toolBar1.Buttons[3].Enabled = false;
}
this.positionid = this.dataGrid1.CurrentRowIndex;
}
}
if(e.Button.ImageIndex == 6)//提交修改
{
cmAmend.EndCurrentEdit();
if(cmAmend.Count > 0)
{
cb = new SqlCommandBuilder(da);
da.Update(table);
MessageBox.Show("修改成功!");
}
}
if(e.Button.ImageIndex == 7)//撤消
{
table.RejectChanges();
}
if(e.Button.ImageIndex == 8)//退出
{
this.Close();
}
}