最近给师兄写了个一个程序,在winform 中利用c# 操作access 数据库,完成数据的增删查改。废话不说直接贴code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data.Common;
using System.Windows.Forms;
using System.IO;
using System.Globalization;
using System.Threading;
using System.Runtime.InteropServices;namespace WindowsFormsApplication1
{//public partial class Form1 : BaseFormAutopublic partial class Form1 : Form{private string ConStr;OleDbConnection con;string currentdir = System.Environment.CurrentDirectory;private string ImgPath = System.Environment.CurrentDirectory + "\\tulip.jpg";private string recordID = "";int a = 10;public Form1(){InitializeComponent();//base.GetAllInitInfo(this.Controls[0]);set_default_values();//global variablelistView1.View = View.Details;listView1.Clear();listView1.HeaderStyle = ColumnHeaderStyle.Clickable;listView1.FullRowSelect = true;listView1.GridLines = true;listView1.Columns.Add("ID", 70, HorizontalAlignment.Center);listView1.Columns.Add("ST", 60, HorizontalAlignment.Center);listView1.Columns.Add("INVENTOR", 60, HorizontalAlignment.Center);listView1.Columns.Add("DATE", 80, HorizontalAlignment.Left);listView1.Columns.Add("NUAP", 40, HorizontalAlignment.Center);listView1.Columns.Add("AW1", 60, HorizontalAlignment.Center);listView1.Columns.Add("AW2", 60, HorizontalAlignment.Center);listView1.Columns.Add("AW3", 60, HorizontalAlignment.Center);listView1.Columns.Add("AW4", 60, HorizontalAlignment.Center);listView1.Columns.Add("AW5", 60, HorizontalAlignment.Center);listView1.Columns.Add("AW6", 60, HorizontalAlignment.Center);listView1.Columns.Add("AW7", 60, HorizontalAlignment.Center);listView1.Columns.Add("AW8", 60, HorizontalAlignment.Center);listView1.Columns.Add("API2/1", 60, HorizontalAlignment.Center);listView1.Columns.Add("API3/1", 60, HorizontalAlignment.Center);listView1.Columns.Add("API4/1", 60, HorizontalAlignment.Center);listView1.Columns.Add("API5/1", 60, HorizontalAlignment.Center);listView1.Columns.Add("API6/1", 60, HorizontalAlignment.Center);listView1.Columns.Add("API7/1", 60, HorizontalAlignment.Center);listView1.Columns.Add("API8/1", 60, HorizontalAlignment.Center);listView1.Columns.Add("Other", 60, HorizontalAlignment.Center);listView1.Columns.Add("img", 100, HorizontalAlignment.Center);findTime.ShowCheckBox = true;findTime.Value = DateTime.Now;listView1.Visible = true;//init the database when init the form// init_database();init_database();update_list_view();update_text_rnum();bool createdNew;Mutex m = new Mutex(true, "YourAppName", out createdNew);if (!createdNew){// app is already running…MessageBox.Show("Only one instance of this application is allowed at a time.");return;}}private void Form1_Load(object sender, EventArgs e){}//connect date baseprivate void button1_Click(object sender, EventArgs e){db_open();if (con.State == ConnectionState.Open){//MessageBox.Show("Access数据库的连接成功!", "Access数据库的连接");}else{//MessageBox.Show("Access数据库的连接失败!", "Access数据库的连接");}db_close();update_list_view();set_default_values();}//查询private void button2_Click(object sender, EventArgs e){db_open();string str = text_id.Text;//MessageBox(text_aw1.Text);con.Close();}//退出界面private void button3_Click(object sender, EventArgs e){this.Close();}//insert a record to databaseprivate void button4_Click(object sender, EventArgs e){db_open();//String i = textBox2.Text;check_impty();StringBuilder sb = new StringBuilder();sb = get_sql_exp("INSERT");picBox.Image.Save(System.Environment.CurrentDirectory + "\\temp.png", System.Drawing.Imaging.ImageFormat.Png);ImgPath = System.Environment.CurrentDirectory + "\\temp.png";FileStream fs = new FileStream(ImgPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);try{//FileStream fs = new FileStream(ImgPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//File.Delete(ImgPath);byte[] imagebytes = new byte[fs.Length];BinaryReader br = new BinaryReader(fs);imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));//MessageBox.Show(sb.ToString());string sb1 = sb.ToString();OleDbCommand cmd = new OleDbCommand(sb1, con);cmd.Parameters.Add("img", OleDbType.Binary);cmd.Parameters["img"].Value = imagebytes;cmd.ExecuteNonQuery();//fs = null;//System.GC.Collect();//MessageBox.Show("One Record Insert Successfully!!!");//fs.Close();//File.Delete(ImgPath);}catch (Exception ex){MessageBox.Show("Error found  when insert date into datebase!!!\nError:\n" + ex.Message);//fs.Close();//File.Delete(ImgPath);}fs.Close();File.Delete(ImgPath);db_close();update_list_view();update_text_rnum();}//delete all record in UVADB//private void button5_Click(object sender, EventArgs e)//{//    var result = MessageBox.Show("Are you sure to delete all records?", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);//    if (result == DialogResult.OK)//    {//        db_open();//        StringBuilder sql = new StringBuilder();//        sql.Append("delete * from UVADB");//        OleDbCommand cmd = new OleDbCommand(sql.ToString(), con);//        try//        {//            cmd.ExecuteNonQuery();//        }//        catch (Exception ex)//        {//            MessageBox.Show(ex.Message);//        }//        db_close();//        update_list_view();//    }//}//测试private void button6_Click(object sender, EventArgs e){}//STprivate void textBox1_TextChanged(object sender, EventArgs e){}//IDprivate void textBox2_TextChanged(object sender, EventArgs e){string str = text_nuap.Text;int b = str.IndexOf("-");bool abc = Convert.ToBoolean(str.IndexOf("-"));if (str != "" && !(str.IndexOf("-") > 0)){checkNumber(str);try{int a = Convert.ToInt16(str.ToString());if (a < 0 || a > 8){MessageBox.Show("Please input a number beteen 1 and 8!!!");}else{}}catch (Exception re){MessageBox.Show(re.Message);}}}private void label22_Click(object sender, EventArgs e){}//init date baseprivate void init_datebase(){db_open();if (con.State == ConnectionState.Open){//MessageBox.Show("Access数据库的连接成功!", "Access数据库的连接");}else{MessageBox.Show("Access数据库的连接失败!", "Access数据库的连接");}db_close();}//open the datebase connectionprivate void db_open(){ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=data.accdb;Jet OLEDB:Database Password=admin;"; //创建OleDbConnection对象 con = new OleDbConnection(ConStr);try{con.Open();}catch (Exception re){MessageBox.Show("Database file open failed!!!" + re.Message);}}//close the datebase connectionprivate void db_close(){con.Close();}private void button2_Click_1(object sender, EventArgs e){}private void dateTimePicker1_ValueChanged(object sender, EventArgs e){findTime.Format = DateTimePickerFormat.Custom;findTime.CustomFormat = "yyyy/MM/dd";string dt = findTime.Value.ToShortDateString();//MessageBox.Show(dt.ToString());}//verify whether the content of string is a numberprivate void checkNumber(string text){if (text != ""){try{Convert.ToInt64(text);}catch{MessageBox.Show("Please input a number!!!");return;}}}private void text_id_TextChanged_1(object sender, EventArgs e){string str = text_id.Text;checkNumber(str);if (str.Length <= 10){}else{MessageBox.Show("Please input a right number less than 10");}}private void text_id_KeyPress(object sender, KeyPressEventArgs e){if (e.KeyChar == 13){string str = text_id.Text;checkNumber(str);if (str.Length == 9){}else{MessageBox.Show("Please input a right number");}}else{}}//open the image in butten above the imageboxprivate void button2_Click_2(object sender, EventArgs e){OpenFileDialog ofd = new OpenFileDialog();ofd.InitialDirectory = "C:\\Users\\Public\\Pictures\\Sample Pictures";ofd.Filter = "所有图片文件|*.*|JPEG(*JPG)|*.jpg|位图文件(*BMP)|*.BMP";ofd.RestoreDirectory = true;ofd.FilterIndex = 1;String fName;if (ofd.ShowDialog() == DialogResult.OK){fName = ofd.FileName;Image myImage = Image.FromFile(fName, true);picBox.SizeMode = PictureBoxSizeMode.StretchImage;picBox.Image = myImage;ImgPath = ofd.FileName;// MessageBox.Show(ImgPath);}}//get the value from the textboxprivate void get_textbox_value(){}//set the default valuesprivate void set_default_values(){text_id.Text = DateTime.Now.ToString("yyyyMMdd")+"00" ;text_st.Text = "ZWM";text_inventor.Text = "Tang";text_nuap.Text = "1";findTime.Value = DateTime.Now;text_aw1.Text = "0";text_aw2.Text = "0";text_aw3.Text = "0";text_aw4.Text = "0";text_aw5.Text = "0";text_aw6.Text = "0";text_aw7.Text = "0";text_aw8.Text = "0";text_api21.Text = "0";text_api31.Text = "0";text_api41.Text = "0";text_api51.Text = "0";text_api61.Text = "0";text_api71.Text = "0";text_api81.Text = "0";text_other.Text = "OUCMDZ";//Image myImage = Image.FromFile(ImgPath, true);ImgPath = System.Environment.CurrentDirectory + "\\tulip.jpg";picBox.SizeMode = PictureBoxSizeMode.StretchImage;picBox.Image = Image.FromFile(ImgPath, true);}//to set sql expression in one functionprivate StringBuilder get_sql_exp(string exp){StringBuilder sb = new StringBuilder();switch (exp){case "CREATE":sb.Append("CREATE TABLE UVADB (ID  varchar(10),ST text(20),INVENTER varchar(20)," +"FindTime date,NUAP integer,AW1 Single,AW2 Single,AW3 Single," +"AW4 Single,AW5 Single,AW6 Single,AW7 Single,AW8 Single," +"API21 Single,API31 Single,API41 Single,API51 Single,API61 Single," +"API71 Single,API81 Single,Other text(128),img OleObject)");//return sb;break;case "INSERT":sb.Append("insert into  UVADB(ID,ST,INVENTER,FindTime,NUAP,AW1,AW2,AW3,AW4,AW5,AW6,AW7,AW8,API21,API31,API41,API51,API61,API71,API81,Other,img) values(\"");sb.Append(text_id.Text + "\",\"");sb.Append(text_st.Text + "\",\"");sb.Append(text_inventor.Text + "\",format('");if (findTime.Checked == true){sb.Append(findTime.Value.ToShortDateString() + "','yyyy/mm/dd'),");}else{sb.Append(findTime.MinDate.ToString() + "','yyyy/mm/dd'),");}sb.Append(text_nuap.Text + ",");sb.Append(text_aw1.Text + ",");sb.Append(text_aw2.Text + ",");sb.Append(text_aw3.Text + ",");sb.Append(text_aw4.Text + ",");sb.Append(text_aw5.Text + ",");sb.Append(text_aw6.Text + ",");sb.Append(text_aw7.Text + ",");sb.Append(text_aw8.Text + ",");sb.Append(text_api21.Text + ",");sb.Append(text_api31.Text + ",");sb.Append(text_api41.Text + ",");sb.Append(text_api51.Text + ",");sb.Append(text_api61.Text + ",");sb.Append(text_api71.Text + ",");sb.Append(text_api81.Text + ",\"");// sb.Append(text_other.Text + "\")");sb.Append(text_other.Text + "\",");sb.Append("@img)");break;case "UPDATE":sb.Append("UPDATE UVADB SET ");//sb.Append(text_id.Text + "\",\"");sb.Append("ID=\""+text_id.Text+"\",");sb.Append("ST = \"" + text_st.Text + "\",");sb.Append("INVENTER = \"" + text_inventor.Text + "\",");if (findTime.Checked == true){sb.Append("FindTime = format('" + findTime.Value.ToShortDateString() + "','yyyy/mm/dd'),");}else{sb.Append("FindTime = format('" + findTime.MinDate.ToShortDateString() + "','yyyy/mm/dd'),");}sb.Append("NUAP = " + text_nuap.Text + ",");sb.Append("AW1 = " + text_aw1.Text + ",");sb.Append("AW2 = " + text_aw2.Text + ",");sb.Append("AW3 = " + text_aw3.Text + ",");sb.Append("AW4 = " + text_aw4.Text + ",");sb.Append("AW5 = " + text_aw5.Text + ",");sb.Append("AW6 = " + text_aw6.Text + ",");sb.Append("AW7 = " + text_aw7.Text + ",");sb.Append("AW8 = " + text_aw8.Text + ",");sb.Append("API21 = " + text_api21.Text + ",");sb.Append("API31 = " + text_api31.Text + ",");sb.Append("API41 = " + text_api41.Text + ",");sb.Append("API51 = " + text_api51.Text + ",");sb.Append("API61 = " + text_api61.Text + ",");sb.Append("API71 = " + text_api71.Text + ",");sb.Append("API81 = " + text_api81.Text + ",");// sb.Append(text_other.Text + "\")");sb.Append("Other = \"" + text_other.Text + "\", ");sb.Append("img =@img");// sb.Append("@img),");sb.Append(" WHERE ID = \"" + recordID + "\"");break;default:break;}return sb;}// update the listviewprivate void update_list_view(){db_open();StringBuilder sb = new StringBuilder();sb.Append("select *  from UVADB");OleDbCommand cmd = new OleDbCommand(sb.ToString(), con);OleDbDataReader dbreader = cmd.ExecuteReader();listView1.Items.Clear();while (dbreader.Read()){ListViewItem Item = new ListViewItem();Item.SubItems.Clear();Item.SubItems[0].Text = dbreader.GetValue(0).ToString();//读取数据库中字段 for (int i = 1; i < dbreader.FieldCount; i++){string value = dbreader.GetValue(i).ToString();string valueresult = "";if (i == 3){valueresult = value.Substring(0, value.Length - 7);}else{valueresult = value;}Item.SubItems.Add(valueresult);//显示}listView1.Items.AddRange(new ListViewItem[] { Item });}//int a = dbreader.Depth;//listView1.Items[a].EnsureVisible();db_close();set_listview_selected();}//init the databaseprivate void init_database(){string cur_path = System.Environment.CurrentDirectory;//string df_path = System.Environment.CurrentDirectory + "\\default.accdb";string sourceFile = System.IO.Path.Combine(cur_path, "default.accdb");string targetFile = System.IO.Path.Combine(cur_path, "data.accdb");if (!System.IO.File.Exists(targetFile)){System.IO.File.Delete(db_path);//CopyDir(df_path, db_path);try{System.IO.File.Copy(sourceFile, targetFile);}catch (Exception re){}}ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=data.accdb;Jet OLEDB:Database Password=admin;"; //创建OleDbConnection对象 con = new OleDbConnection(ConStr);try{con.Open();}catch (Exception re){MessageBox.Show("Database file open failed!!!" + re.Message);}string sb = "select * from UVADB";string uniq = "alter table UVADB add unique (ID)";OleDbCommand cmd = new OleDbCommand(sb, con);try{cmd.ExecuteNonQuery();}catch{StringBuilder sb1 = get_sql_exp("CREATE");OleDbCommand cmd1 = new OleDbCommand(sb1.ToString(), con);OleDbCommand cmd2 = new OleDbCommand(uniq, con);cmd1.ExecuteNonQuery();cmd2.ExecuteNonQuery();}con.Close();}private void listView1_MouseClick(object sender, MouseEventArgs e){//MessageBox.Show("hello world");}//send message shen click delete buttonprivate void button_delete_Click(object sender, EventArgs e){db_open();//MessageBox.Show(listView1.FocusedItem.SubItems[0].Text);string id = text_id.Text;string sb = "delete *  from UVADB  where ID= \"" + id + "\"";OleDbCommand cmd = new OleDbCommand(sb, con);try{cmd.ExecuteNonQuery();}catch (Exception re){MessageBox.Show("Delete record from dataBase failed!!!\nError:\n" + re.Message);}db_close();update_list_view();update_text_rnum();}//send message when the focus changed in listboxprivate void listBox1_SelectedIndexChanged(object sender, EventArgs e){if (listView1.FocusedItem != null && listView1.SelectedIndices.Count > 0){db_open();//MessageBox.Show(listView1.FocusedItem.SubItems[0].Text);string id = listView1.FocusedItem.SubItems[0].Text;string sb = "select *  from UVADB  where ID= \"" + id + "\"";OleDbCommand cmd = new OleDbCommand(sb, con);OleDbDataReader dbreader = cmd.ExecuteReader();if (dbreader.Read()){//convert and update the findtimeDateTime dt;DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo();dtFormat.ShortDatePattern = "yyyy/mm/dd";dt = Convert.ToDateTime(dbreader.GetValue(3).ToString(), dtFormat);findTime.Value = dt;//update the others parameterstext_id.Text = dbreader.GetValue(0).ToString();recordID = dbreader.GetValue(0).ToString();text_st.Text = dbreader.GetValue(1).ToString();text_inventor.Text = dbreader.GetValue(2).ToString();text_nuap.Text = dbreader.GetValue(4).ToString();text_aw1.Text = dbreader.GetValue(5).ToString();text_aw2.Text = dbreader.GetValue(6).ToString();text_aw3.Text = dbreader.GetValue(7).ToString();text_aw4.Text = dbreader.GetValue(8).ToString();text_aw5.Text = dbreader.GetValue(9).ToString();text_aw6.Text = dbreader.GetValue(10).ToString();text_aw7.Text = dbreader.GetValue(11).ToString();text_aw8.Text = dbreader.GetValue(12).ToString();text_api21.Text = dbreader.GetValue(13).ToString();text_api31.Text = dbreader.GetValue(14).ToString();text_api41.Text = dbreader.GetValue(15).ToString();text_api51.Text = dbreader.GetValue(16).ToString();text_api61.Text = dbreader.GetValue(17).ToString();text_api71.Text = dbreader.GetValue(18).ToString();text_api81.Text = dbreader.GetValue(19).ToString();text_other.Text = dbreader.GetValue(20).ToString();Byte[] bytedata = new Byte[0];bytedata = (byte[])(dbreader.GetValue(21));MemoryStream strdata = new MemoryStream(bytedata);picBox.Image = Image.FromStream(strdata);}db_close();}}//update the record in databaseprivate void button_update_Click(object sender, EventArgs e){db_open();//String i = textBox2.Text;StringBuilder sb = new StringBuilder();sb = get_sql_exp("UPDATE");try{picBox.Image.Save(System.Environment.CurrentDirectory + "\\temp.png", System.Drawing.Imaging.ImageFormat.Png);ImgPath = System.Environment.CurrentDirectory + "\\temp.png";FileStream fs = new FileStream(ImgPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//File.Delete(ImgPath);byte[] imagebytes = new byte[fs.Length];BinaryReader br = new BinaryReader(fs);imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));//MessageBox.Show(sb.ToString());string sb1 = sb.ToString();OleDbCommand cmd = new OleDbCommand(sb1, con);cmd.Parameters.Add("img", OleDbType.Binary);cmd.Parameters["img"].Value = imagebytes;cmd.ExecuteNonQuery();fs.Close();File.Delete(ImgPath);//    //fs = null;//    //System.GC.Collect();//    //MessageBox.Show("One Record Insert Successfully!!!");}catch (Exception ex){MessageBox.Show("Error fired  when update datebase!!!\nError:\n" + ex.Message);}db_close();update_list_view();}//search in databaseprivate void button_search_Click(object sender, EventArgs e){//test_to_sql("NUAP", "3-5");db_open();string sb = "select *  from UVADB where ";string[] keys = new string[] { "ID", "ST", "INVENTER", "NUAP", "AW1", "AW2", "AW3", "AW4", "AW5", "AW6", "AW7", "AW8", "API21", "API31", "API41", "API51", "API61", "API71", "API81", "Other" };string[] txts = new string[] { text_id.Text, text_st.Text, text_inventor.Text, text_nuap.Text, text_aw1.Text, text_aw2.Text, text_aw3.Text, text_aw4.Text, text_aw5.Text, text_aw6.Text, text_aw7.Text, text_aw8.Text, text_api21.Text, text_api31.Text, text_api41.Text, text_api51.Text, text_api61.Text, text_api71.Text, text_api81.Text, text_other.Text };for (int i = 0; i < keys.Length; i++){string sqlres = text_to_sql(keys[i], txts[i]);if (sqlres != "" && sqlres != "ERROR"){sb = sb + sqlres + " and ";}else if (sqlres == "ERROR"){break;}else{continue;}}if (sb == "select *  from UVADB where "){if (text_to_sql("FindTime", findTime.Value.ToShortDateString()) == ""){sb = "select * from UVADB";MessageBox.Show("Will search all records in database when all value are empty!!!");}else{sb = sb + text_to_sql("FindTime", findTime.Value.ToShortDateString());}}else{//sb = sb.Substring(0, sb.Length - 5);if (text_to_sql("FindTime", findTime.Value.ToShortDateString()) == ""){}else{sb = sb + text_to_sql("FindTime", findTime.Value.ToShortDateString());}}string ab1=sb.Substring(sb.Length-5);if(sb.Substring(sb.Length-5)==" and "){sb = sb.Substring(0, sb.Length - 5);}try{OleDbCommand cmd = new OleDbCommand(sb, con);OleDbDataReader dbreader = cmd.ExecuteReader();listView1.Items.Clear();while (dbreader.Read()){ListViewItem Item = new ListViewItem();Item.SubItems.Clear();Item.SubItems[0].Text = dbreader.GetValue(0).ToString();//读取数据库中字段 for (int i = 1; i < dbreader.FieldCount; i++){string value = dbreader.GetValue(i).ToString();string valueresult = "";if (i == 3){valueresult = value.Substring(0, value.Length - 7);}else{valueresult = value;}Item.SubItems.Add(valueresult);//显示}listView1.Items.AddRange(new ListViewItem[] { Item });}int a = dbreader.Depth;listView1.Items[a].EnsureVisible();}catch (Exception re){MessageBox.Show("Database search failed!!" + re.Message);}db_close();}//reset all the text boxesprivate void button_reset_MouseClick(object sender, MouseEventArgs e){text_id.Text = "";text_st.Text = "";text_inventor.Text = "";text_nuap.Text = "";text_aw1.Text = "";text_aw2.Text = "";text_aw3.Text = "";text_aw4.Text = "";text_aw5.Text = "";text_aw6.Text = "";text_aw7.Text = "";text_aw8.Text = "";text_api21.Text = "";text_api31.Text = "";text_api41.Text = "";text_api51.Text = "";text_api61.Text = "";text_api71.Text = "";text_api81.Text = "";text_other.Text = "";}//reset all the text boxesprivate void button_reset_Click(object sender, EventArgs e){text_id.Text = "";text_st.Text = "";text_inventor.Text = "";text_nuap.Text = "";text_aw1.Text = "";text_aw2.Text = "";text_aw3.Text = "";text_aw4.Text = "";text_aw5.Text = "";text_aw6.Text = "";text_aw7.Text = "";text_aw8.Text = "";text_api21.Text = "";text_api31.Text = "";text_api41.Text = "";text_api51.Text = "";text_api61.Text = "";text_api71.Text = "";text_api81.Text = "";text_other.Text = "";picBox.Image = null;findTime.ShowCheckBox = true;}// to generate the search sql expressionprivate string text_to_sql(string keyname, string txt){//string test = txt;string sqlexp = "";if (txt != "" && keyname != ""){if (keyname == "ID" || keyname == "ST" || keyname == "INVENTER" || keyname == "Other"){//sqlexp = keyname + "=\"" + txt + "\"";sqlexp = keyname + " Like \"%" + txt + "%\"";}else if (keyname == "FindTime"){if (findTime.Checked == true){sqlexp = keyname + "=format('" + findTime.Value.ToShortDateString() + "','yyyy/mm/dd')";}else{return sqlexp;}}else{a = txt.IndexOf("-");if (txt.IndexOf("-") > 0){try{int indx = txt.IndexOf("-");string fromvalue = txt.Substring(0, indx);string tovalue = txt.Remove(0,indx+1);double fromv = Convert.ToDouble(fromvalue);double tov= Convert.ToDouble(tovalue);if (Convert.ToDouble(fromvalue) >= Convert.ToDouble(tovalue)){MessageBox.Show(keyname + " input a wrong range!!!");}else{sqlexp = keyname + ">=" + fromvalue + " and " + keyname + "<=" + tovalue;}}catch (Exception re){MessageBox.Show(keyname + " input a wrong format!!!" + re.Message);sqlexp = "ERROR";}}else{sqlexp = keyname + "=" + txt;}}}return sqlexp;}private void picBox_DoubleClick(object sender, EventArgs e){OpenFileDialog ofd = new OpenFileDialog();ofd.InitialDirectory = currentdir;ofd.Filter = "所有图片文件|*.*|JPEG(*JPG)|*.jpg|位图文件(*BMP)|*.BMP";ofd.RestoreDirectory = true;ofd.FilterIndex = 1;String fName;if (ofd.ShowDialog() == DialogResult.OK){fName = ofd.FileName;Image myImage = Image.FromFile(fName, true);picBox.SizeMode = PictureBoxSizeMode.StretchImage;picBox.Image = myImage;ImgPath = ofd.FileName;// MessageBox.Show(ImgPath);}}private void picBox_Click(object sender, EventArgs e){}//set the last of listview is selectedprivate void set_listview_selected(){if (listView1.Items.Count != 0){listView1.FullRowSelect = true;//listView1.Items[0].Selected= true;listView1.GetItemAt(0, 0);//listView1.Items[0].Focused = true;}}//check the value of control is emptyprivate void check_impty(){if (text_id.Text == "") text_id.Text = "0";if (text_st.Text == "") text_st.Text = "0";if (text_inventor.Text == "") text_inventor.Text = "0";if (text_nuap.Text == "") text_nuap.Text = "0";if (text_aw1.Text == "") text_aw1.Text = "0";if (text_aw2.Text == "") text_aw2.Text = "0";if (text_aw3.Text == "") text_aw3.Text = "0";if (text_aw4.Text == "") text_aw4.Text = "0";if (text_aw5.Text == "") text_aw5.Text = "0";if (text_aw6.Text == "") text_aw6.Text = "0";if (text_aw7.Text == "") text_aw7.Text = "0";if (text_aw8.Text == "") text_aw8.Text = "0";if (text_api21.Text == "") text_api21.Text = "0";if (text_api31.Text == "") text_api31.Text = "0";if (text_api41.Text == "") text_api41.Text = "0";if (text_api51.Text == "") text_api51.Text = "0";if (text_api61.Text == "") text_api61.Text = "0";if (text_api71.Text == "") text_api71.Text = "0";if (text_api81.Text == "") text_api81.Text = "0";if (text_other.Text == "") text_other.Text = "0";// text_id.Text = "";//text_st.Text = "";//text_inventor.Text = "";//text_nuap.Text = "";//text_aw1.Text = "";//text_aw2.Text = "";//text_aw3.Text = "";//text_aw4.Text = "";//text_aw5.Text = "";//text_aw6.Text = "";//text_aw7.Text = "";//text_aw8.Text = "";//text_api21.Text = "";//text_api31.Text = "";//text_api41.Text = "";//text_api51.Text = "";//text_api61.Text = "";//text_api71.Text = "";//text_api81.Text = "";//text_other.Text = "";}private void groupBox1_Enter(object sender, EventArgs e){}private void Form1_Load_1(object sender, EventArgs e){}private void text_aw1_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_aw1.Text, e);}//verify the the whether the textbox input is digitprivate void digit_check(string textin, KeyPressEventArgs e){//判断按键是不是要输入的类型。if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)e.Handled = true;//小数点的处理。// int abc = (int)e.KeyChar;if((int)e.KeyChar==45){if (textin.Length == 0){e.Handled = true;   //'-'不能在第一位}else{e.Handled = false;}}if ((int)e.KeyChar == 46)                           //小数点{if (textin.Length == 0){e.Handled = true;   //小数点不能在第一位}else{float f;float oldf;bool b1 = false, b2 = false;b1 = float.TryParse(text_rnum.Text, out oldf);b2 = float.TryParse(text_rnum.Text + e.KeyChar.ToString(), out f);if (b2 == false){if (b1 == true)e.Handled = true;elsee.Handled = false;}}}}private void text_aw2_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_aw2.Text, e);}private void text_aw3_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_aw3.Text, e);}private void text_aw4_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_aw4.Text, e);}private void text_aw5_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_aw5.Text, e);}private void text_aw6_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_aw6.Text, e);}private void text_aw7_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_aw7.Text, e);}private void text_aw8_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_aw8.Text, e);}private void text_api21_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_api21.Text, e);}private void text_api31_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_api31.Text, e);}private void text_api41_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_api41.Text, e);}private void text_api51_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_api51.Text, e);}private void text_api61_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_api61.Text, e);}private void text_api71_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_api71.Text, e);}private void text_api81_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_api81.Text, e);}private void text_nuap_KeyPress(object sender, KeyPressEventArgs e){digit_check(text_nuap.Text, e);}//get the record number in database and show in text_rnumprivate void update_text_rnum(){db_open();//MessageBox.Show(listView1.FocusedItem.SubItems[0].Text);string sb = "select count(*)  from UVADB";OleDbCommand cmd = new OleDbCommand(sb, con);OleDbDataReader dbreader = cmd.ExecuteReader();dbreader.Read();text_rnum.Text = dbreader.GetValue(0).ToString();db_close();}//verify the default whether the accdb file is in install dirprivate void check_db_file(){}private void CopyDir(string srcPath, string aimPath){try{// 检查目标目录是否以目录分割字符结束如果不是则添加之 //if (aimPath[aimPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)//{//    aimPath += System.IO.Path.DirectorySeparatorChar;//}// 判断目标目录是否存在如果不存在则新建之 //if (!System.IO.Directory.Exists(aimPath))//{//    System.IO.Directory.CreateDirectory(aimPath);//}// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组 // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法 // string[] fileList = Directory.GetFiles(srcPath); //string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);// 遍历所有的文件和目录 //foreach (string file in fileList)//{//    // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 //    if (System.IO.Directory.Exists(file))//    {//        CopyDir(file, aimPath + System.IO.Path.GetFileName(file));//    }// 否则直接Copy文件 //else//{System.IO.File.Copy(srcPath, aimPath, false);//}//}}catch (Exception e){throw;}}}
}




												

利用winform 操作access 数据库相关推荐

  1. access labsql 出错_在LabVIEW中利用LabSQL操作ACCESS数据库

    在 LabVIEW 中利用 LabSQL 操作 ACCESS 数据库 有时候想想, 网上关于这方面的资料很多, 我就不必再写这方面的东西了, 可是又想, 我遇到的问题, 还是要 google , ba ...

  2. C# 操作ACCESS数据库

    看到CSDN上不断兄弟姐妹提问关于c#操作Access的问题,于是本人利用闲暇将c#操作Access的方法加以总结,主要解决的问题有: 创建mdb 创建table 读取table内容 查询table中 ...

  3. python不可以操作access数据库_Python操作Access数据库基本操作步骤分析

    Python编程语言的出现,带给开发人员非常大的好处.我们可以利用这样一款功能强大的面向对象开源语言来轻松的实现许多特定功能需求.比如Python操作Access数据库的功能实现等等.在Python操 ...

  4. pyodbc操作Access数据库

    现在各种各样的数据库层出不穷,什么MySQL.PostgreSQL.MongoDB这些都是比较火的,还有一些稍微小众一点的数据库就更多了.相比之下,微软Office套件里面附带的Access数据库究落 ...

  5. 技术图文:如何利用 C# 向 Access 数据库插入大量数据?

    背景 通常我们在做数据分析与处理之前,需要把从网站爬取的数据或者从 甲方 系统中导出的数据存入到自己的数据库中.如果数据量小,直接利用 SQL的 Insert 语句逐条插入就好.可是数据量上万条之后, ...

  6. C#操作Access数据库

    本教程介绍了如何通过ADO.NET的OleDb相关类来操作Access数据库的相关步骤. 1     软件环境 开发平台:Microsoft Visual Studio 2010 数据库:Micros ...

  7. 一个封装了的ADO类,功能非常强大,并做了一个DEMO演示如何操作ACCESS数据库

    呵呵,说实在的,这个类俺是从外国论坛上下载的,自己研究了下如何使用并做了一个DEMO,演示如何操作ACCESS数据库.希望给那些没有接触数据库编程的初学者一点启发吧.有任何问题请及时与我联系^_^.程 ...

  8. MFC+ODBC操作Access数据库pdf版

    <MFC+ODBC操作Access数据库pdf版> 下载地址: 网盘下载 转载于:https://www.cnblogs.com/long12365/p/9731370.html

  9. golang odbc mysql_go语言通过odbc操作Access数据库的方法

    本文实例讲述了go语言通过odbc操作Access数据库的方法.分享给大家供大家参考.具体如下: 这里需要用到go-odbc库,下载地址为:https://github.com/weigj/go-od ...

最新文章

  1. lvm 逻辑卷 和 网络管理
  2. 新的开始,连菜鸟都算不上的程序媛
  3. 命令行查看网卡使用的驱动+跳板机命令行设置静态地址
  4. 【讨论】从吉日的一段话说起+寻找WinForm架构的最佳实践
  5. 零基础学python用哪本书好-零基础学习python推荐几本书?
  6. composer 设置代理
  7. xshell怎么连接linux服务器,教你怎么使用xshell远程连接linux服务器
  8. 使用ReportLab绘制PDF
  9. Udacity课程脉络-统计学基础(二)- t分布
  10. 开源 免费 java CMS - FreeCMS2.8 会员头像设置
  11. 某电商平台数据分析报告(2)
  12. PLUS模型教程1:认识PLUS模型
  13. 2021第十三届中国最佳酒店大奖榜单揭晓:年度最佳酒店、最佳顶级奢华酒店、最佳城市地标酒店...
  14. windows开始菜单打不开,搜索打不开
  15. 现代信号处理——时频分析与时频分布(时频分布的基本理论)
  16. maven工程私服仓库配置(阿里云仓库)
  17. 三.栈与栈的实例——汉诺塔
  18. shell用for循环编辑显示形状格式(99乘法表,三角,梯形,平行四边形,菱形等)
  19. 9981难的哈尔滨的辛酸之旅
  20. 深入浅出 Laravel 路由执行原理

热门文章

  1. Paper:《Disc and Drum Brake Dynamometer Squeal Noise Test Procedure》翻译及其解读
  2. TCP连接被意外重置的原因
  3. Flink使用lambda表达式报错:InvalidTypesException:could not be determined automatically, due to type erasure.
  4. 基于FPGA的DDS参考设计
  5. 任正非:5G关系着公司的生死存亡,不惜代价要赢!
  6. BigDecimal 往左移动两位小数_人教版小学数学四年级下册 小数点位置移动引起小数大小的变化 教案、课件,公开课视频...
  7. 全球与中国通用级聚苯乙烯(GPPS)市场深度研究分析报告
  8. PWN passcode [pwnable.kr]CTF writeup题解系列5
  9. 系统设计模板该怎么写
  10. Microsoft visual c++2017 X64 Minimum Runtime等vc++运行库问题的解决记录