引用:
using System.Data.OleDb;
using System.Data;
建立连接:
private OleDbConnection Getconnection()//建立连接
{ //string Constr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Administrator\Documents\测试.accdb";
string path_startup = System.Windows.Forms.Application.StartupPath;// +@"\Data\测试.accdb";
string Constr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path_startup + @"\Data\测试.accdb";//当前文件下的路径
OleDbConnection myCon = new OleDbConnection(Constr);
return myCon;
}
建立查询:
private void query_CX(DataGridView dt)//查询语句
{
OleDbConnection myCon = Getconnection();
try
{
myCon.Open();
string sql = "select * from 表1";
OleDbDataAdapter myda = new OleDbDataAdapter(sql, myCon);
DataSet myds = new DataSet();
myda.Fill(myds, "表1");
dt.DataSource = myds.Tables[0];
}
catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
finally
{
myCon.Close();
}
}
datagridview添加序号:
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
Rectangle myRec = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dataGridView1.RowHeadersWidth - 5, e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dataGridView1.RowHeadersDefaultCellStyle.Font, myRec, dataGridView1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}
datagridview支持在线编辑数据:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
OleDbConnection myCon = Getconnection();
myCon.Open();
string mystr1 = dataGridView1.Columns[e.ColumnIndex].HeaderText.ToString() + "=" + "'" + dataGridView1.CurrentCell.Value.ToString() + "'";
string mystr2 = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
string sql_update = "update 表1 set " + mystr1 + "where id=" + mystr2;
try
{
OleDbCommand myCom = new OleDbCommand(sql_update, myCon);
myCom.ExecuteNonQuery();
}
catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
finally
{
myCon.Close();
}
}
支持隔行标色:
private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
if (e.RowIndex > dataGridView1.Rows.Count - 1) return;
Color oldForeColor = new Color();
Color oldBackColor = new Color();
var row=dataGridView1.Rows[e.RowIndex];
if(row==dataGridView1.CurrentRow)
{
if(row.DefaultCellStyle.ForeColor!=Color.White)
{
oldForeColor = row.DefaultCellStyle.ForeColor;
row.DefaultCellStyle.ForeColor = Color.White;
}
if (row.DefaultCellStyle.BackColor != Color.White)
{
oldBackColor = row.DefaultCellStyle.BackColor;
row.DefaultCellStyle.BackColor = Color.Blue;
}
else
{
row.DefaultCellStyle.ForeColor = oldForeColor;
row.DefaultCellStyle.BackColor = oldBackColor;
}
}
}