usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;usingSystem.Data.SqlClient;namespace_15._2datagridview binding Data Source { Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); } Private voidForm1_Load (Objectsender, EventArgs e) {Dgvbindmode.datasource= Bindmodesource (). tables[0];//datasets can contain more than one table, and the call needs to specify Dgvnonbindmode.datasource=Nonbindsource (); } PrivateDataSet Bindmodesource () {stringConstr ="server=.; Uid=sa;pwd=zqyo850619;database=csharpzxw"; SqlConnection Mycon=NewSqlConnection (CONSTR); DataSet myds=Newdataset ();//Declare a data setTry{mycon. Open (); stringsql ="Select Name,gender from mytable001"; SqlDataAdapter Myda=NewSqlDataAdapter (SQL, mycon);//Declare a data adapter, including the database query language and the connected data source information Myda. Fill (myDS,"mytable001");//Adapters load tables of data source types into datasets
} Catch(Exception ex) {MessageBox.Show (ex). Message); } finally{mycon. Close (); } returnmyds; } PrivateDataTable Nonbindsource () {DataTable myDT=NewDataTable (); myDT. Columns.Add ("name", Type.GetType ("System.String")); myDT. Columns.Add ("Gender", Type.GetType ("System.String")); string[,] mystr = {{"Zhang San","female"}, {"John Doe","male"}, {"Harry","male"}, {"Zhao Liu","female"}, {"Ho Seven","male" } }; for(inti =0; I < MyStr. Length/2; i++) {DataRow mydr=myDT. NewRow (); mydr[0] = Mystr[i,0]; mydr[1] = Mystr[i,1]; myDT. Rows.Add (MYDR); } returnmyDT; } }}
Two methods for 15.2DataGridView binding data sources