Ado dot net complete meterial (1)

533 views
474 views

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
533
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
20
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Ado dot net complete meterial (1)

  1. 1. ADO (ACTIVEX DATA OBJECT)DATA SOURCE COMMUNICATION:Data source is a place where we can store the information which can be anything like files, databases,indexing servers etc….Languages can’t be communicate with data sources directly because each data source adopts a differentprotocol for communication. Language …… data source is not possible.To facilitate the process of communication ms has provided the solution in the form of intermediatecomponents like “drivers and providers”. Language – drivers or providers – data sourceDRIVERS:These were designed traditionally for communicating with databases which are of two types again. 1. JET drives [joint engine technology]. 2. ODBC drivers [open data source connectivity]. 1.JET Drivers: It is designed communicate with local databases. Ex: Application – JET drivers – local db (FoxPro, dbase). Local db: those are loaded in client application memory. 2.ODBC Drivers: These were designed to communicate with remote databases like SQL server,Oracle,Ingress etc.. Application – ODBC drivers – remote db’s (sql server, oracle , ingress). Drawbacks of drivers: As a driver is not part of an application first it should be explicitly install on the machine where the applications installed & then configure with application. Initially drivers were design only for databases communication. PROVIDERS: To address the problem in drivers ms has provided one more solution known as “OLEDB providers “*Object Linking and Embedding data base+. 1
  2. 2. Providers were designed for data source communication and they becomes a part of yourapplication which doesn’t required explicit installation and configurations. Application – OLEDB drivers – data sources (files, databases, indexing servers).Note: both the drivers & providers suffers from a common problem i.e as they were designed usingnative code languages Leeds to platform dependency , purely for windows.Because of support for native language code the classical visual basic language wasn’t able to makeuse of the drivers & providers directly. So ms has provided some intermediate components for theprocess of communication as following.Visual basic – DAO – JET drivers – Local DBS RDO – ODBC driver s – Remote dbs ADO – OLEDB providers – data sourcesADO.NET: Ado.net is a collection of managed providers to communicate with data sources from .net languages. When .net was introduced to communicate with data sources the best out of traditional 3 technologies ado’s has been taken out & re designed as ado.net. Ado.net provides various classes which can be used for communicating with data sources under the following namespaces.System.data;System.Data.Oledb;System.Data.Sqlclient;System.Data.OracleClient;System.Data.Odbc;System.Data:It’s a collection of classes used for holding & managing the data on client machine. Classes underthe namespaces are: dataset, data table, data row, data column, data view & data relation.System.Data.Oledb:It’s a collection of classes used for communicating with any data source.System.Data.Sqlclient: 2
  3. 3. It’s a collection of classes used for communicating only for Sql server db. System.Data.Oracle client: It’s a collection of classes used for communicating only with Oracle db. System.Data.Odbc: It’s a collection of classes used for communicating with traditional ODBC-drivers which will in turn communicate with data sources. All the above 4 namespaces contains same set of classes as following: Connection, command, data reader, data adapter, command builder & parameter. Note: each class was referred by prefixing with the namespace before the class for distinguishing b/w each other as following: Oledbconnection Sqlconnection OracleConnection OdbcConnection Difference between ADO AND ADO.NET ADO It’s a collection of unmanaged providers to communicate with data sources. It is a platform dependency ADO.NET It’s a collection of managed providers to communicate with data sources. It is a platform independencyHOW TO CONNECT/CREATE DATABASEHOW TO CREATE TABLEHOW TO INSERT DATA Every operation we perform on data source has 3 activities involved in it: Establish a connection Applying a Statement Expecting the result Establish a Connection: 3
  4. 4. In this process we open a channel for communication with the target machine to perform our operations to open the channel for communication we use the “connection class”. Connection() Connection (string connection string) Connection String: it’s a collection of attributes that are used for connecting with target machine . those are: - Provider - Data source - Usserid & password - Database or initial catalog - Trusted_connection - Dsn Provider: As we were aware a provider is required for communicating with data sources we use a separate provider for each data source to communicate. Name of providers: Oralce - Msdaora Sql server – Sqloledb MS-Access (or) – MS.Excel Microsoft.jet.oledb.4.0 Indexing server - msidxs Data source : It is the IP address (or) name of target machine where the data source (or) database is present The doesn’t require to be specified if it was on the local machine. User id & password: As db’s are secured places for string data to connect with them we require a valid user name & password. Oracle - scott/tiger Sqlserver - sa/<blank> Database(or) initial catalog and trusted _ connection attributes will be used only while connecting with sql server.Methods & properties under connection class:Open(): a method to open the connection. 4
  5. 5. Close(): a method to close the connection.State; a property to find states of the connection.Connection string: a property to get (or) set the connection stringThe object of class connection can be created in any of the following ways:Connection con=new connection();Con.connectionstring=”<con str>”;(Or)Connection con=new connectionstring=”<con str”> CONNECTING WTH SQL SERVERSQL SERVER is a collection of users & databases where user can have one or more databases of his own.So, while connecting from a .NET application to SQL SERVER in the connection string we explicitlyrequire to specify the name of the database we want to connect either by using database (or) Initialcatalog attributes.While connecting with SQL SERVER we have two different ways of authentication. 1. WINDOWS AUTHENTICATION. 2. SQL AUTHENTICATION.In this SQL SERVER OS credentials to connect with server. So, we don’t require to supply them again.Where in case of SQL authentication we require to explicitly provide user id and password.While connecting from a .net application to sql server in windows authentication in place of user id &password attributes we need to use “Trusted _Connection=True” CONNECTION STRING FOR SQL SERVER AUTHENTICATIONFOR WINDOWS AUTHENTICATIONFor c sharp:con= new SqlConnection ("Data Source=.SQLEXPRESS;Initial Catalog=sjcet;Integrated Security=True");For vb:con= new SqlConnection ("Data Source=.SQLEXPRESS;Initial Catalog=sjcet;Integrated Security=True");FOR SQL AUTHENTICATION 5
  6. 6. “Provider=sqlOledb; user Id=sa; password=<pwd>; databases=<dbname>[; data source=<servername>+”CREATING A DATABASE ON SQLSERVER:-GO TO START MENU - Programsmicrosoft sql server  sql server management studio , click on itto open and provide authentication details to login.Once the studio is open in the left and side we get a window object explorer [F8] , in that right click onthe node databases and select “NEW DATABASES” which opens a window asking for the name entername as csharp and click ok.which adds db under database node.Now expand your charp and dbnode, right click on tables node & select “NEW TABLE” which opens awindow asking for column names & datatype, enter anything which you want.NOTE:-select status column & go into ccolumn properties in the bottom and seet “default value (or)Binding” property as 1, which takes the default value for status as true.Click on the save button on the top of studio . which will prompt for table name ,enter name as“students” & click OK. Which adds table under tables node.Now right click on the table created & select “OPEN TABLE” which opens a window under it enter thedata we must ignoring photo & status columns &close the studio.PROGRAM TO CHECK WHEATHER DATABASE IS CONNECTED OR NOTSqlConnection con; private void Form2_Load(object sender, EventArgs e) { con =new SqlConnection ("Data Source=.SQLEXPRESS;InitialCatalog=sjcet;Integrated Security=True"); con.Open (); MessageBox .Show(con.State .ToString ()); con.Close(); MessageBox.Show(con.State.ToString()); }APPLYING A STATEMENT:in this process we send on instruction to the data source specify the type of activity that has to bepreferred in the form of an sql statement like select, insert , update and delete.We use command class for applying a statement:Command()Command(string stmt, connection con)Properties of command class: 6
  7. 7. 1.connection : To set (or)get the current connection object associated with command.2.command text:To set (or) get the current statement associated with command.The object of command can be created as below:Command cmd=new command();cmd.connection=<con>;cmd.command text=”<sql stmt>”;(or)Command cmd=new command(“<sql stmt>”,con);METHODS OF COMMAND CLASS:Name of method Return typeExecuteReader() - DatareaderExecuteScalar() - objectExecuteNonquery - intAfter creating the object of command class we need to call any of these 3 methods to execute thestatement. 1.ExecuteReader():Call executereader method when ever we want to execute a select statement that returns valuesin the form of rows & columns so that data comes & statements under data reader which is a classmodelation table. 2. ExecuteScalar(): Call execute scalar method when ever we want to execute a select statement that returns single value result which captures the data under an object variable. Note: we can use execute scalar method for executing a select statement that returns rows and columns also. But we get only the first row and first column value as output. 3. ExecuteNonQuery(): 7
  8. 8. Call execute non query method when ever we want to execute non-query statements [DML statements] like insert, update and delete so that the no.of rows been effected is returned as an integer. Note: the above process of calling an appropriate method in an appropriate case is our third activity expecting of the results.DATA READERIt was a class model on table that can be used for holding data on client machine.FEATURES:Faster access to data from the data source as it was connection oriented.It can hold multiple tables in it at a time .To load multiple tables we need to pass multiple selectstatements as arguments to command separated by a semi-colon.Example: cmd = new SqlCommand("select * from Table1","select * from Table1",con); DataReader dr=cmd.ExecuteReader();NOTE:-use the NextResult() method on data reader object to navigate from current table to next table.eg:dr.NextResult();ACCESSING DATA FROM A DATA READERData reader is a class which is modelled on table to access the data from datareader it provides usfollowing methods:-Read()bool Used for moving the record pointer from current location to next row , after moving the pointerit will return the status specifying values were present in the row to which it has moved, that will be trueif present & false if not present.Getvalue(int index)object Used for picking the field value from the row to which pointer was pointing by specifyingcolumn index position.Note:-we can also access data in the form of single dimensional array also,either by specifying columnindex position (or) name, as following: <dr>[index]object <dr>[colname]objectGetName(int index)string Returns name of the column for specified index. 8
  9. 9. Drawbacks of data Reader:It was designed in connection oriented which requires a permanent connection with data source toaccess the data if the connection was closed we can’t access the data, which will be a burden on dbservers when multiple clients were accessing data from it.It provides only forward navigation i.e. allow to go either to next record on table but not to previousrecord (or) table.It was a read only object which will not allow any changes on data present in it.PROGRAM TO ACCESS DATA AND DATA FIELD NAMESusing System.Data.SqlClient; SqlConnection con; SqlCommand cmd; SqlDataReader dr; private void Form1_Load(object sender, EventArgs e) { con= new SqlConnection ("Data Source=.SQLEXPRESS;Initial Catalog=sjcet;IntegratedSecurity=True"); cmd = new SqlCommand("select * from Table1",con); con.Open(); dr=cmd.ExecuteReader(); label1.Text = dr.GetName(0); label2.Text = dr.GetName(1); label3.Text = dr.GetName(2); label4.Text = dr.GetName(3); showdata(); } private void showdata() { if (dr.Read()) { textBox1.Text = dr[0].ToString(); textBox2.Text = dr[1].ToString(); textBox3.Text = dr[2].ToString(); textBox4.Text = dr[3].ToString(); } else MessageBox.Show("last record"); } private void button1_Click(object sender, EventArgs e) { rno = 0; showdata(); } }} 9
  10. 10. BEFORE AFTERDATASETIt was an another class provided for holding & managing data on a client machines apart fromdatareders. Dataset class was present in System.Data namespace.FEATURESIt was also capable of holding mltiple tables.It was designed on disconnected architecture which doesn’t reqquire permanent connection withdatasource for a holding the data.It provides scrollable navigation which allows to move in any diection.It was updatable , i.e changes can be performed on data present in it.Using datasets:The class which is responsible for loading data into data reader from a data source is “command” in thesame way data adapter class is used for communication b/w data source and data set. Data reader  command<--data source. Data set  data adapter <– data source.ACCESSING DATA FROM DATASETDataset is a collection of Tables where each table is represented as a class dataTable & identified byindex position (or) name.Connections:-(COLLECTION OF TABLES) 10
  11. 11. <dataset>.Tables[index] or Tables[name] Ds.Tables[0] or ds.Tables*“students”+Every Datatable is again a collection of rows & columns where each row is represented as a classDataRow & identified by it’s index postion. Each column is represented as a class DataColumn &identified by index position or name.DATA READER AND DATASET DIFFERENCESData Reader is a forward only and read only dataData Set is used to maintain relationships between multiple tables.Data Reader cant persist the dataData Set can persist the dataData Reader (connection oriented) is a read only and forward only record set which will have the dataretrieved based on the select statement. we cant do DML operations through Data Reader.DATA TABLE(COLLECTION OF ROWS(DATAROW)) <dataTable>.rows[index] (or) rows[name] ds.tables[0].Rows[0](COLLECTION OF COLUMNSS(DATACOLUMN)) <dataTable>.columns[index] (or) columns[name] ds.Tables[0].columns[0] (or) ds.Tables*0+.columns*“sno”+REFERING TO A CELL UNDER DATATABLE:- <dataTable>.Rows[rows][col] ds.Tables[0].columns[0] [0] (or) ds.Tables*0+.Rows*0+*“sno”+DATA ADAPTORIn the same way data adapter class is used for communication b/w data source and data set. Data set  data adapter <– data source.Connections:DataAdaptor(string stmt, Connection con) 11
  12. 12. DataAdaptor(command cmd)Eg:- DataAdaptor da=new DataAdaptor(“<sql stmt>”’con); adap = new SqlDataAdapter("select * from empdetails", con);METHODS OF DATADAPTOR FILL(Dataset ds,string tname) UPDATE(Dataset ds,String tname)Fill is for loading data from DataSource to DataSet.Update is to transfer changes made on data from DataSet to DataSource.DataAdaptor is internally collections of 4 commands in it: Select command, Insert command, Update command, Delete commandWhen we call fill method on a Adaptor following things takes place 1) Opens a connection with the DataSource. 2) Executes the select command under it & loads data from DataSource to DataSet. 3) Closes the connection with DataSource.As we are DataSet is updatable, once the data is loaded intop it we can make changes on it like adding(or) modifying (or) deleting of records.After performing changes on DataSet if we want to send these changes back to the DataSource we needto call Update method on adaptor which performs the following;- 1) Reopens a connection with the DataSource. 2) Changes which ae made on DagaSet will be sent back to DataSource, where in this process it will make use of insert,update and delete commands of adaptor. 3) Closes the connection with DataSourcce.PROGRAM TO GET DATASET IN GRIDVIEWusing System.Data.SqlClient; SqlConnection con; SqlDataAdapter adap; DataSet ds; private void Form1_Load(object sender, EventArgs e) { con = new SqlConnection("Data Source=.SQLEXPRESS;InitialCatalog=sjcet;Integrated Security=True"); 12
  13. 13. adap = new SqlDataAdapter("select * from Table1", con); con.Open(); ds = new DataSet(); adap.Fill(ds, "empdetails"); dataGridView1.DataSource = ds.Tables[0]; } }}DATA GRID VIEWIt is a control which can display data in the form of Table i.e, rows & columns.We can directly bind the datatable to the control by making use of it’s datasource property.. DataSource=<dataTale> Eg:-datagridview1.DatSource=ds.Tables[0];Datagridview control is updatable which will allow us to add , modify (or) delete records.The speciality of it is any changes we perform on data of the control reflex directly into the DataTable towhich it was bound.PROGRAM TO UPDATE DATASET IN GRIDVIEWSqlConnection con; SqlDataAdapter adap; DataSet ds; SqlCommandBuilder cmd; private void Form1_Load(object sender, EventArgs e) { con = new SqlConnection("Data Source=.SQLEXPRESS;InitialCatalog=sjcet;Integrated Security=True"); adap = new SqlDataAdapter("select * from Table1", con); con.Open(); cmd = new SqlCommandBuilder(adap); ds = new DataSet(); adap.Fill(ds, "Table1"); dataGridView1.DataSource = ds.Tables[0]; } 13
  14. 14. private void button2_Click(object sender, EventArgs e) { this.Close(); } private void button1_Click(object sender, EventArgs e) { cmd2 = new SqlCommandBuilder(adap); adap.Update(ds, "Table1"); MessageBox.Show("database saved succesfully"); } }}FILLING DATA PRESENT UNDER DATASETTo filter the data present under dataset we have two different approaches 1) FIND METHOD, 2) DATA VIEW CLASSFIND METHODIt was capable of filtering the data basing on the primary key column of table which can retrieve only asingle row.DATAVIEW CLASSIt was capable of filtering the data basing on any column of the table and retrieves multiple records.Dataview is a class which was modeled on the object view of databse.which will never contain anyinformation init . It only act as a mediator between DataProvider and DataContainer.Views also known as Logical Tables because they look like a table but never contains information initphysically. 14
  15. 15. The dataview also place the same role of a view in our .NET applications which can act as a mediatorbetween the dataprovider,dataset- and DataConsumer (like gridview,textbox,combobox e.t.c…)USING A DATAVIEWTo make use of dataview we follow the below process:Step(1):create a datview by using default view property of datatable class.which creates the view withthe same structure of the table of which it was called “DataTable”Datatable Defaultview DataType(returntype) Ex.DataView dv=ds.Tables*“emp”+.DefaultView;Step(2): After view gets created specify the condition to filter using the RowFilter property of DataViewclass.DataView: RowFilter=<condition> Ex.dv.RowFilter=”job=’manager’” dv.Rowfilterr=”sal>250”MULTI PLE GRID VIEW USING COMBOBOXBEFORE FILTERING 15
  16. 16. AFTER FILTERING BASED ON DEPTNO = 412SqlConnection con; SqlDataAdapter da; DataSet ds; bool flag = false; private void Form1_Load(object sender, EventArgs e) { con = new SqlConnection("Data Source=.SQLEXPRESS;InitialCatalog=sjcet;Integrated Security=True"); da = new SqlDataAdapter("select * from dept", con); ds=new DataSet (); da.Fill (ds,"dept"); da.SelectCommand .CommandText ="select * from emp"; da.Fill (ds,"emp"); comboBox1 .DataSource =ds.Tables ["dept"]; comboBox1.DisplayMember = "deptno"; dataGridView1.DataSource = ds.Tables["emp"]; flag = true; } 16
  17. 17. private void comboBox1_SelectedIndexChanged(object sender, EventArgse) { if (flag) { DataView dv = ds.Tables["emp"].DefaultView; dv.RowFilter = "deptno=" + comboBox1.Text; } }PROGRAM USING ALL THE ABOVE COMMANDS (ADAPTOR & COMMAND ): SqlConnection con; SqlCommand cmd; SqlDataReader dr; SqlDataAdapter adap; DataSet ds; private void Form2_Load(object sender, EventArgs e) { con = new SqlConnection("Data Source=.sqlexpress;InitialCatalog=KINGS;Integrated Security=True"); con.Open(); MessageBox.Show(con.State.ToString()); loaddata(); con.Close(); } private void loaddata() { adap = new SqlDataAdapter("select * from emp2", con); ds = new DataSet(); //adap.MissingSchemaAction = MissingSchemaAction.AddWithKey; adap.Fill(ds); DataGridView1.DataSource = ds.Tables[0]; } 17
  18. 18. private void BTNINSERT_Click(object sender, EventArgs e) { cmd = new SqlCommand("insert into emp2(sno,name,age,desg)values("+ TextBox1.Text + " ,"+textBox2.Text + "," + textBox3 .Text + ","+textBox4 .Text +")", con); con.Open(); cmd.ExecuteNonQuery(); MessageBox.Show(" 1 row inserted"); loaddata(); con.Close(); } //EDIT BUTTON private void button1_Click(object sender, EventArgs e) { try { adap = new SqlDataAdapter("select name,age,desg from emp2where sno=" + TextBox1.Text + " ", con); ds = new DataSet(); //adap.MissingSchemaAction = MissingSchemaAction.AddWithKey; adap.Fill(ds); //DataGridView1.DataSource = ds.Tables[0]; textBox2.Text = ds.Tables[0].Rows[0].ItemArray[0].ToString(); textBox3.Text = ds.Tables[0].Rows[0].ItemArray[1].ToString(); textBox4.Text = ds.Tables[0].Rows[0].ItemArray[2].ToString(); } catch (Exception ex) { MessageBox.Show("updation fail"); con.Close(); } } private void button2_Click(object sender, EventArgs e) { cmd = new SqlCommand("update emp2 set name=" + textBox2.Text +",age=" + textBox3.Text + ",desg=" + textBox4.Text + " where sno=" +TextBox1.Text + "", con); con.Open(); cmd.ExecuteNonQuery(); MessageBox.Show("updated successfully"); loaddata(); con.Close(); } private void BTNDELETE_Click(object sender, EventArgs e) { cmd = new SqlCommand("delete from emp2 where sno=" +TextBox1.Text + "", con); con.Open(); cmd.ExecuteNonQuery(); MessageBox.Show("deleted successfully"); loaddata(); } 18
  19. 19. private void BTNCLEAR_Click(object sender, EventArgs e) { TextBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = ""; TextBox1.Focus(); }PROGRAM USING ALL THE ABOVE COMMANDS(ADAPTOR & COMMAND BUILDER): SQLCOMMANDBUILDER :-if update method has to work datadaptor first requires three commandsunder it i.e insert,update and delete which should be written by programmer manually or generatethem with the help of a class command bulder. command builder class if given with An adaptor that contains a select Command in it will write theremaining three commands for adaptors.;Note:- command builder can generate us update and delete commands for agiven select command onlyif the table contains a keycolumn in it. syntax:- CommandBuilder (DataAdaptor,ds) SqlConnection con; SqlDataAdapter adap; DataSet ds; SqlCommandBuilder cmd2; int rno; private void Form1_Load(object sender, EventArgs e) { con = new SqlConnection("Data Source=.sqlexpress;InitialCatalog=KINGS;Integrated Security=True"); adap = new SqlDataAdapter("select * from empdetails", con); con.Open(); ds = new DataSet(); // adap.MissingSchemaAction = MissingSchemaAction.AddWithKey; MessageBox.Show(con.State.ToString()); adap.Fill(ds, "empdetails"); 19
  20. 20. dataGridView1.DataSource = ds.Tables[0]; showdata(); } private void showdata() { textBox1.Text = ds.Tables[0].Rows[rno][0].ToString(); textBox2.Text = ds.Tables[0].Rows[rno][1].ToString(); textBox3.Text = ds.Tables[0].Rows[rno][2].ToString(); textBox4.Text = ds.Tables[0].Rows[rno][3].ToString(); } private void BTNFIRST_Click(object sender, EventArgs e) { rno = 0; showdata(); } private void BTNPREV_Click(object sender, EventArgs e) { if (rno > 0) { rno -= 1; showdata(); } else MessageBox.Show("First record"); } private void button3_Click(object sender, EventArgs e) { //next button if (rno < ds.Tables[0].Rows.Count - 1) { rno += 1; showdata(); } else MessageBox.Show("last Record"); } private void button4_Click(object sender, EventArgs e) { //last button rno = ds.Tables[0].Rows.Count-1; showdata(); } private void BTNNEW_Click(object sender, EventArgs e) { textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text =""; textBox1.ReadOnly = false; textBox1.Focus(); } private void BTNINSERT_Click(object sender, EventArgs e) 20
  21. 21. { DataRow dr = ds.Tables[0].NewRow(); dr[0] = textBox1.Text; dr[1] = textBox2.Text; dr[2] = textBox3.Text; dr[3] = textBox4.Text; ds.Tables[0].Rows.Add(dr); MessageBox.Show("Record Added"); textBox1.ReadOnly = true; BTNFIRST.PerformClick();}private void BTNUPDATE_Click(object sender, EventArgs e){ ds.Tables[0].Rows[rno][1] = textBox2.Text; ds.Tables[0].Rows[rno][2] = textBox3.Text; ds.Tables[0].Rows[rno][3] = textBox4.Text; MessageBox.Show("record modified");}private void BTNDEL_Click(object sender, EventArgs e){ ds.Tables[0].Rows[rno].Delete(); MessageBox.Show("Records deleted"); cmd2 = new SqlCommandBuilder(adap); adap.Update(ds, "empdetails"); ds.AcceptChanges(); showdata(); BTNFIRST.PerformClick();}private void BTNSAVE_Click(object sender, EventArgs e){ cmd2 = new SqlCommandBuilder(adap); adap.Update(ds, "empdetails"); MessageBox.Show("data saved to database");}private void BTNCLOSE_Click(object sender, EventArgs e){ this.Close();} 21
  22. 22. DISPLAYING MULTIPLE TABLES IN GRID VIEW USING COMBO BOXSTEP1: drag combo box and grid viewStep2: add table names in combo box with the help of edit itemsStep3: write the code in combobox eventSqlConnection con; SqlDataAdapter da; DataSet ds; private void comboBox1_SelectedIndexChanged(object sender, EventArgse) { string sqlstr = "select * from " + comboBox1.Text; da=new SqlDataAdapter (sqlstr ,con); ds = new DataSet(); da.Fill (ds); dataGridView1 .DataSource =ds.Tables [0]; } private void Form1_Load(object sender, EventArgs e) { con =new SqlConnection ("Data Source=.sqlexpress;InitialCatalog=bank;Integrated Security=True"); } 22
  23. 23. 23
  24. 24. Small task about college using grid view and loginStep1 : take 3 forms (form 1 name it as form1, form 2 name it as homepage, form3 name it as reg.Step2: in form1 design (panel,2 labels and 2 text boxes). 24
  25. 25. SqlConnection con; SqlDataAdapter da; SqlCommand cmd; DataSet ds; private void button1_Click(object sender, EventArgs e) { con =new SqlConnection ("Data Source=.sqlexpress;InitialCatalog=bank;Integrated Security=True"); da=new SqlDataAdapter ("select * from Login",con); ds = new DataSet(); da.Fill(ds); if (ds.Tables[0].Rows.Count > 0) { Homepage f = new Homepage(); f.Show(); } else { MessageBox.Show("invalid login"); } 25
  26. 26. } private void Form1_Load(object sender, EventArgs e) { } private void checkBox1_CheckedChanged(object sender, EventArgs e) { Reg f = new Reg(); f.Show(); } }Step 3: in home page form take(labels, picture box,menustrips)Step 4 : in registration form take( label, text box, rich text box, button, grid view). 26
  27. 27. SqlConnection con; SqlCommand cmd; SqlDataAdapter da; DataSet ds; string s; private void button1_Click(object sender, EventArgs e) { con = new SqlConnection("Data Source=.sqlexpress;InitialCatalog=bank;Integrated Security=True"); if(radioButton1 .Checked ) { s=radioButton1 .Text ; } if(radioButton2 .Checked) { s=radioButton2 .Text ; } 27
  28. 28. cmd = new SqlCommand("insert intoreg(sname,fname,gender,add1)values(" + textBox1.Text + "," + textBox2.Text+ "," + s + "," + richTextBox1.Text + ")", con); con.Open(); cmd.ExecuteNonQuery(); showdata(); MessageBox.Show("1 row inserted"); con.Close(); } private void showdata() { con = new SqlConnection("Data Source=.sqlexpress;InitialCatalog=bank;Integrated Security=True"); da = new SqlDataAdapter("select * from reg", con); ds = new DataSet(); da.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; } private void Reg_Load(object sender, EventArgs e) { showdata(); } }} 28
  29. 29. Image concept storing and retriving 29
  30. 30. using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Data.SqlClient;using System.IO;namespace images_wiapp{ public partial class Form1 : Form { 30
  31. 31. SqlConnection con; SqlCommand cmd; SqlDataAdapter da; SqlDataReader dr; MemoryStream ms; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "image files|*.jpg;*.png;*.gif";DialogResult dr = ofd.ShowDialog();if (dr == DialogResult.Cancel)return; pictureBox1.Image=Image.FromFile(ofd. FileName); textBox1.Text=ofd.FileName; } private void button2_Click(object sender, EventArgs e) { con = new SqlConnection("Data Source=CHETAN-11SQLEXPRESS;InitialCatalog=sai;Integrated Security=True" ); ms = new MemoryStream(); pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] pic_arr = new byte[ms.Length]; ms.Position = 0; ms.Read(pic_arr, 0, pic_arr.Length); cmd = new SqlCommand("insert intotbl_image(imgPath,imgImage)values(@imgPath,@imgimage)", con); cmd.Parameters.AddWithValue("@imgPath", textBox1.Text); cmd.Parameters.AddWithValue("@imgimage",pic_arr); con.Open(); int res = cmd.ExecuteNonQuery(); if (res > 0) { MessageBox.Show("image added successfully"); } else { MessageBox.Show("not inserted"); } } private void button3_Click(object sender, EventArgs e) { Form2 f = new Form2(); f.Show(); 31
  32. 32. } }}using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Data.SqlClient; 32
  33. 33. using System.IO;namespace images_wiapp{ public partial class Form2 : Form { SqlConnection con; SqlCommand cmd; SqlDataAdapter da; SqlDataReader dr; MemoryStream ms; public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { con = new SqlConnection("Data Source=CHETAN-11SQLEXPRESS;InitialCatalog=sai;Integrated Security=True" ); //cmd = new SqlCommand("select imgPath from tbl_image where imgPath=" +listBox1.SelectedItem + "", con); cmd = new SqlCommand("select imgPath from tbl_image", con);con.Open();try{dr=cmd.ExecuteReader();while(dr.Read()){ listBox1.Items.Add(dr[0].ToString());}}catch(Exception ex){MessageBox.Show(ex.Message);}finally{ con.Close();} } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { con = new SqlConnection("Data Source=CHETAN-11SQLEXPRESS;InitialCatalog=sai;Integrated Security=True"); cmd = new SqlCommand("select * from tbl_image where imgPath=" +listBox1.SelectedItem + "", con); con.Open(); SqlDataReader dr; 33
  34. 34. try { dr = cmd.ExecuteReader(); if (dr.Read()) { byte[] picarr = (byte[])dr["imgimage"]; ms=new MemoryStream(picarr); ms.Seek(0,SeekOrigin.Begin); pictureBox1.Image=Image.FromStream(ms); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { con.Close(); } } }}different overloads of Dataadapter.Fill() Method that Dataadapter is working just like a bridge between a datasource and dataset. One of the method ofDataadapter is Fill() Method.It can be overloaded in 5 different ways.First OverloadDataadapter.Fill(ds) here fetches the data from tblMobile and fills in the DataSetds.OutputOn clicking the button Fill DataSet, the dataadapter fills the dataset and finally, the GridView shows all the recordspresent in the dataset ds. 34
  35. 35. Second OverloadHere Dataadapter.Fill(dt) fetches records from tblMobile and fills in the datatable named dt.OutputOn clicking the button Fill DataTable, the dataadapter fills the datatable and finally Gridview displays all therecords present in the datatable. 35
  36. 36. Third OverloadHere a datatable named nameOfDataTable has been filled by the dataadapter.Fill() method. As this datatable iswithin the dataset, we can use the commented line also to fill the gridview. Let me be clear here,To set the datasource of the gridview control we can use: 1. ds.Tables[0] //valid 2. ds.Tables["nameOfDataTable"] //validAs this is the first table of the dataset, so we can use ds.Tables[0], otherwise we can use the table name to indicatewhich table i need to access. 36
  37. 37. OutputFourth OverloadThis overload takes 3 parameters. The types of parameters are int,int and datatable. Here first parameter is thestarting record, second parameter is the maximum number of record and the last parameter is the datatablewhere we have to fill the records. The range from which the records are to be fetched are mentioned here usingthe parameters.Output 37
  38. 38. Fifth OverloadAt last, this overload takes 4 parameters. The types of parameters are dataset,int,int,string. The first parameter isthe name of the dataset, second parameter is the starting record number, third parameter is the maximumnumber of records and the last parameter is the name of the table.At first ds1 is filled with all the records of tblMobile. And then, dataadapter.Fill() method has filled thedatatable nm with the specified range of records.Following figure shows the contents of dataset ds1. It is having all the records of tblMobile. 38
  39. 39. Now, the dataadapter object da1 takes 4 parameters and fills the datatable named nm with the records ofspecified range.Output 39

×