资源描述:
《数据库应用(dataGridView控件)》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、创建连接数据库的例子,应用到dataGridVicw控件:usingSystem;usingSystem・Collections・Generic;usingSystem・ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem・Linq;usingSystem・Text;usingSystem・Windows.Forms;usingSystem.Data・SqlClient;namespaceDataTnsertTntoWindowsFormsApppublicpartialclassForml:FormpublicF
2、orml()InitializeComponent();privateSqlConnectionSqlCon;privatestringstate二null;〃连接数据库/privatevoidbuttonlClick(objectsender,EventArgse)stringstrServer二textBox1.Text・Trim();stringstrDatabase二textBox2.Text・Trim();stringstrUser=textBox3.Text・Trim();stringstrPwd=textBox4.Text・Trim();stringConStr=stri
3、ng.Format(z,server={0};database=tl);userid二{2};pwd二{3}strServer,strDatabase,strlser,strPwd);SqlCon=newSqlConnection(ConStr);SqlCon.Open();state=SqlCon・State・ToString();if(state=="Open")MessageBox.Show("数据库连接成功!");button1.Enabled二false;}button2.Enabled=true;elseMessageBox.Show(“数据库连接失败!”);//根据表•名进
4、行的查询,、privatevoidbutton4Click(objectsender,EventArgse)stringstrTableName二textBox9.Text・Trim();state二SqlCon.State.ToStringO;if(state=="Open")stringstrsql=string・Formal("select*from{0)z/,strTableName);using(SqlDataAdaptersda=newSqlDataAdapter(strsql,SqlCon))tryDataSetds=newDataSet();sda.Fill(ds,"ta
5、bic");}this.dataGridViewl.DataSource=ds.Tables[0].DefaultView;catch{return;elseMessageBox.Show(^当前的连接状态:"+state);buttonl.Enabled=true;//关闭数据库的连接z、privatevoidbutton2Click(objectsender,EventArgse)state二SqlCon.State・ToStringO;if(state=="Open")SqlCon.Close0;SqlCon.Dispose0;MessageBox.Show(连接已成功被关闭!“)
6、;}buttonl.Enabled=true;else、MessageBox.Show(z,当前的状态为关闭状态!”);button2.Enabled二false;〃数据添加z、privatevoidbutton3Click(objectsender,EventArgse)stringstrSno=textBoxS.Text・Trim();stringstrName二tcxtBox6.Text・Trim();stringstrSex=textBox7.Text・Trim();intiAge=int.Parse(textBox8.Text・Trim());state二SqlCon.Stat
7、e・ToStringO;if(state=="Open")OSQ3s{r,s,g刃n{r>1V?s}11ZJlnr・1rsLA9fh*nog.sormat(insertintostudent,strName,strScx,iAge);SqlCon);SqlCommandcmd=newSq1Command(select*fromstudent,cmd・CommandTcxt二strsql;try}inti=cmd.ExecuteNon