0% found this document useful (0 votes)
31 views

vb.net with ado.net

The document provides an overview of ADO.NET, a part of the Microsoft .NET Framework, focusing on its architecture, components, and advantages for database programming. It contrasts connected and disconnected data access models, highlighting the use of DataSets and DataReaders for data manipulation. Additionally, it discusses the interoperability of ADO.NET with XML and the maintainability and performance benefits of using this technology for scalable applications.

Uploaded by

GANESH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
31 views

vb.net with ado.net

The document provides an overview of ADO.NET, a part of the Microsoft .NET Framework, focusing on its architecture, components, and advantages for database programming. It contrasts connected and disconnected data access models, highlighting the use of DataSets and DataReaders for data manipulation. Additionally, it discusses the interoperability of ADO.NET with XML and the maintainability and performance benefits of using this technology for scalable applications.

Uploaded by

GANESH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 26
US0SCCSC03 ‘Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET Database Programming With ADO.NET ADO.NET — introduction and applications ADO.NET~ architecture (connected and disconnected) Database connectivity using ADO.NET Use of Data sources, Server Explorer and working with DataSet a) ye" data manipulation vVvVVY Populating data in a DataGridView ADO.NET is a part of the Microsoft Net Framework. The full form of ADO.Net is ActiveX® Data Objects. ADONet has the ability to separate data access mec! mechanisms and data connectivity mechanisms. Q ADO.Net is a set of classes that allow applications) \d and write information in > > > databases, > ADO.Net can be used by any Net Language. LY > It’s concept. It’s not a programming lang @) > ADO.Net introduces the concept of disconneaged architecture. > We need to add System.Data nam cogvork with ADO.Net > It’sanext version of ActiveX Dati ts (ADO) technology which was used in VB6.0. sources exposed through OLE DB arid ODBC. Data-sharing consumer applications can use ADO.NET to connect to thes® datasources and retrieve, handle, and update the data that they contain. ADONET separat Aude from data manipulation into discrete components that can be used separately, ADO.NET includes NET Framework data providers for connecting to a database, exedutitig commands, and retrieving results. Those results are either processed directly, placed in an ADO:NET DataSet object in order to be exposed to the user in an ad hoc manner, waht {a from multiple sources, or passed between tiers. The DataSet object can also ADO.NET provides cons ott data sources such as SQL Server and XML, and to data be fdependently of a NET Framework data provider to manage data local to the application %r sourced from XML. The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes found in System.Xml.dil. For sample code that connects to a database, retrieves data from it, and then displays that data in a console window. ADO.NET provides functionality to developers who write managed code similar to the functionality provided to native component object model (COM) developers by ActiveX Data Objects (ADO). We recommend that you use ADO.NET, not ADO, for accessing data in your NET applications Page 1 of 26 US0SCCSC03 ‘Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET Comparison between ADO and ADO. ‘ADO ADO.NET Data access ‘ADO used connected data | ADO.NET used usage. (Connection- | disconnected da Oriented Models) environment, (Disconnee Models) XML Support In ADO XML Support is | In ADO.NET Rep limited. Support. se Format of data transferring [ADO used technology to | ADO.NET us I for access data and is COM — | transmitting( dita” to and Based from four datatase and web application, Data provider Tn ADO disconnected data | InqADO.NET disconnected provide by Record Set. f provide by DataSet and ‘DataAdpter. Tables In ADO, Record Set, is, ADO.NET DataSet, can a single table contain multiple tables. | result Client connection In ADO lien ction {In ADONET client model is Client | disconnected as soon as the application needs tobe | data is fetched or processed. conntéted data-sever | DataSet is always ~< ‘orking on the data, _| disconnected. Advantages of ADO.NEK I interoperability < . ADO.NET applications an take advantage of the flexibility and broad acceptance of XML. Because XMI mat for transmitting datasets across the network, any component that can read the XML(TOHifiat can process data. In fact, the receiving component need not be an ADO.NETjcomBOhent at all: The transmitting component can simply transmit the dataset to its destistatio without regard to how the receiving component is implemented. The destination sa ight be a Visual Studio application or any other application implemented with any tool Whiatsoever. The only requirement is that the receiving component be able to read XML. As an industry standard, XML was designed with exactly this kind of interoperability in mind. Maintainability In the life of a deployed system, modest changes are possible, but substantial, architectural changes are rarely attempted because they are so difficult, That is unfortunate, because in a natural course of events, such substantial changes can become necessary. For example, as a deployed application becomes popular with users, the increased performance load might require Page 2 of 26 US0SCCSC03 ‘Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET architectural changes. As the performance load on a deployed application server grows, system resources can become scarce and response time or throughput can suffer. Faced with this problem, software architects can choose to divide the server’s business-logic processing and user- interface processing onto separate tiers on separate machines. In effect, the application server tier is replaced with two tiers, alleviating the shortage of system resources. The problem is not designing a three-tiered application, Rather, it is increasing the number of tiers after an application is deployed. If the original application is implemented in ADO.NET using datasets, this transformation is made easier. Remember, when you replace a single ti h two tiers, you arrange for those two tiers to trade information, Because the tiers can tr ta through XML-formatted datasets, the communication is relatively easy. Programmability se? ADO.NET data components in Visual Studio encapsulate data access fi lity in various ways that help you program more quickly and with fewer mistakes. FOr example, data commands abstract the task of building and executing SQL statements or stored\procedures. Similarly, ADO.NET data classes generated by the designer too] sult in typed datasets, This in tum allows you to access data through typed programmin; ode for the typed dataset is easier to read. It is also easier to write, because statement ~ ion is provided. Performance For disconnected applications, ADO.NET saad Ce, tn advantages over ADO disconnected recordsets. When using CO! recta fling to transmit a disconnected recordset among tiers, a significant processing cost ey from converting the values in the recordset to data types recognized by COM. S. , such data-type conversion is not necessary. BX demands on your data, scalability has become critical. Internet applications hav ithe supply of potential users. Although an application might serve a dozen use ight not serve hundreds —or hundreds of thousands — equally well. An spar ebonts resources such as database locks and database connections will not serve high numt of users well, because the user demand for those limited resources will eventuall their supply. ADO.NET, acdogymodates scalability by encouraging programmers to conserve limited resoureés. Because any ADO.NET application employs disconnected access to data, it does not dalagase locks or active database connections for long durations. Page 3 of 26 US0SCCSC03 ‘Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET ADO.NET Architecture DataAdapter DataSet SelectCommand Data Tables Data Table]| |[Data Tabi w f1| InsertCommand | + ala Table || || Data Table: - [Connection : Data Rows]| |[Data Rows 2 DeleteCommand cu = Columns |} || Columns UpdateCommand Data Relation Database Data processing has traditionally relied pt in a connection-based, two-tier model, As data processing increasingly uses multistier architectures, programmers are switching to 2 disconnected approach to provide bétteF scalability for their applications. The two main components of/AQO.NBT 3.0 for accessing and manipulating data are the NET Framework data providers amd the DataSet. .NET Framework D; Q. The NET Framework ‘roviders are components that have been explicitly designed for data manipulation gnd fast, forward-only, read-only access to data. The Connection object provides connectivity RS source. The Command object enables access to database commands to return modify data, run stored procedures, and send or retrieve parameter information. The DataRéadér provides a high-performance stream of data from the data source. Finally, the DataAdapter provides the bridge between the DataSet object and the data source. The fer uses Command objects to execute SQL commands at the data source to both load the hee with data and reconcile changes that were made to the data in the DataSet back to the data source. The DataSet The ADO.NET DataSet is explicitly designed for data access independent of any data source. As a result, it can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application. The DataSet contains a collection of one or more DataTable objects consisting of rows and columns of data, and also primary key, foreign key, Page 4 of 26 US0SCCSC03 ‘Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET constraint, and relation information about the data in the DataTable objects. The follor diagram illustrates the relationship between a NET Framework data provider and a DataSet. ing Selecting a DataReader or a DataSet When you decide whether your application should use a DataReader or a DataSet, consider the type of functionality that your application requires. Use a DataSet to do the following: * Cache data locally in your application so that you can manipulate it, If you only need to read the results of a query, the DataReader is the better choice. @ + Remote data between tiers or from an XML Web service. + Interact with data dynamically such as binding to a Windows Forms controler e0n6jning and relating data from multiple sources + Perform extensive processing on data without requiring an open conection to the data source, which frees the connection to be used by other clients. oO If you do not require the functionality provided by the DatdSet, you can improve the performance of your application by using the DataReader to return ta in a forward-only, read-only manner. Although the DataAdapter uses the DataReader to fill the contents of a DataSet, by using the DataReader, you can boost perform: use you will save memory that would be consumed by the DataSet, and avoid the pe ig that is required to create and fill the contents of the DataSet. ~ eC must be opened to access the data retrieved from database is called as connected architegture. Connected architecture was built on the Connection : in connect AY also the purpose of connection is to just establish aconnection to database andhi(self will not transfer any data, DataReader : Datal used to store the data retrieved by command object and make it available for net applidation. Data in DataReader is read only and within the DataReader you can navigate forward direction and it also only one record at a time. To accegs he by one record from the DataReader, call Read() method of the DataReader whose returfy ty is bool. When the next record was successfully read, the Read() method will return and otflerwise retums false: Page 5 of 26 US0SCCSC03 Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET ata Provider The architecture of ADO.net in which data retrieved from Qa can be accessed even when connection to database was closed is called as disc d architecture. Disconnected architecture of ADO.net was built on classes comnectigndataadaper, commandbuilder and dataset and dataview. A Data Provider ‘Command Builder in vant Data Adapter DataTable ‘Select Command = Insert Command = columns Update Command Constraints ‘command Tallin ‘connect nection Dataview Database Page 6 of 26 US0SCCSC03 ‘Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET Connection : Connection object is used to establish a connection to database and connectionit self will not transfer any data. DataAdapter : DataAdapter is used to transfer the data between database and dataset. It has commands like select, insert, update and delete. Select command is used to retrieve data from database and insert, update and delete commands are used to send changes to the data in dataset to database. It needs a connection to transfer the data. CommandBuilder + by default dataadapter contains only the select comman it doesn’tcontain insert, update and delete commands. To create insert, update felete commands for the dataadapter, commandbuilder is used. It is used only t ese commands for the dataadapter and has no other purpose. SS DataSet : Dataset is used to store the data retrieved from database. ipter and make it available for net application. ; To fill data in to dataset fill() method of dataadapter is used and e” following syntax. Da.Fill(Ds,”TableName’ When fill method was called, dataadapter will aah fection to database, executes select command, stores the data retrieved by select 1 to dataset and immediately closes the As connection to database was closed, an’ ‘s to the data in dataset will not be directly sent to the database and will be made onlin thé-dataset. To send changes made to data in dataset to the database, Update() method o taadapter is used that has the following syntax. executes insert, upd: delete commands to send changes in dataset to database and immediately closes the CBrinection. As connection is opened only when it is required and will be automatically’ -d) when it was not required, this architecture is called disconnected architectur of contain data in multiple tables, DafiView : DataView is a view of table available in DataSet. It is used to find a record, sort the records and filter the records. By using dataview, you can also perform insert, update and delete as in case of a DataSet. Update(Ds,”Tablename”); When Update nos dataadapter will again open the connection to database, DataReader is Connected Architecture since it keeps the connection open until all rows are fetched one by one DataSet is DisConnected Architecture since all the records are brought at once and there is no need to keep the connection alive Page 7 of 26 US0SCCSC03 U Visual Programming through VB.NET NIT 4 : Database Programming With ADO.NET Difference between Connected and disconnected architecture Connected (DataReader) Disconnected (DataSet) It is connection oriented, Itis disconnection oriented, Connected methods gives faster performance Disconnected get low in speed and performance. connected can hold the data of single table eZ ws disconnected can hold multiple tables ‘connected you need to use a read only forward only data reader x disconnected you cannot Data Reader can't persist the data Data Set can persist the dat Itis Read only, we can't update the data. ADO.NET Components There are two major components of ADO.NET: 1. DataSet 2. DataProvider We can update data ( ba¥eor a subset of database, It can contain tables and relationships between those tabl DataSet : represents either an ee = Data Provider is a collee DataAdapter objects and Data Provider Y > The dafa)pfpvider is responsible for providing and maintaining the cone datab: sf Gomponents like Connection, Command, DataReader, yunication with a physical data store and the dataset. > Anis’a set of classes that can be used for communicating with database, and \ holding/manipulating data the DataProvider connects to the data source on behalf of ADO.NET. > The data source can be Microsoft SQL Server or Oracle database and OLEDB data provider. > The data provider components are specific to data source, The following lists the NET Framework data providers that are included in the NET Framework. Page 8 of 26 US0SCCSC03 ‘Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET For SQL Server > Imports System.Data SqiClient namespace. > It provides data access for Microsoft SQL Server. For OLEDB > Imports System.Data.OleDb namespace. > It provides data sources exposed using OLEDB. @ » We can use OLEDB for connect Microsoft Access For ODBC Ao 0 > Imports System.Data.Odbe namespace. \ > It provides data sources exposed using ODBC ( Ss For Oracle > Imports System. Data.OracleClient namespace. y > Itprovides data access for oracle. © Data Provider's common set of classes for all DataSoy 1. Connection a oY DataAdapter S DataReader RQ Coneton A > It cin os a connection to the data source. > In Qe) Ye connection can establish using SqlConnection object. Command PN ES > Fires Repro or perform some action on the data source, such as insert, update, Se. Server command can fires using SqlCommand object. > It’sa bride between Data source and DataSet object for transferring data, > In SQL Server the Data Adapter can create using SqlDataAdapter object DataReader > Used when large list of results one record at a time. > Itreads records in a read-only, forward-only mode. Page 9 of 26 US0SCCSC03 ‘Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET > In SQL Server the datareader can create using SqlDataReader object Use of Server Explorer Server Explorer/Database Explorer is the server management console for Visual Studio. Use this window to open data connections and to log on to servers and explore their system seryices Use Server Explorer/Database Explorer to view and retrieve information from, ne databases you are connected to, You can do the following: 0 + List database tables, views, stored procedures, and functions Ao + Expand individual tables to list their columns and triggers \ + Right-click a table to perform actions, such as showing the (a RE ‘or viewing the table's definition, from its shorteut menu. ) To access Server Explorer/Database Explorer, choose Server Exploxer’or Database Explorer on the View menu, To make the Server Explorer/Database Explorer window close automatically when not in use, choose Auto Hide on the W jen. Namespa Ss iw System Data ‘The System.Dat provides access to classes that represent the ADO.NET arghitecture) ADO.NET lets you build components that efficiently Manage data from multiple data sources. ConsiSts\og the Classes that constitute the ADO.NET architecture, which is ql aryPdata access method for managed applications. The ADO.NET rchifecture enables you to build components that efficiently manage data ym Multiple data sources. ADO.NET also provides the tools to request, ‘update, and reconcile data in distributed applications. System.Data. The System.Data.OleDb namespace is the. NET Framework Data Provider for OLE DB. a\ . Classes that make up the NET Framework Data Provider for OLE DB- compatible data sources. These classes allow you to connect to an OLE DB data source, execute commands against the source, and read the results. System,Data,SqlClient ‘The System.Data, SqlClient namespace is the. NET Framework Data Provider for SQL Server. Classes that make up the NET Framework Data Provider for SQL Server, which allows you to connect to SQL Server 7.0, execute commands, and Page 10 of 26 US0SCCSC03 ‘Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET read results. The System.Data.SqIClient namespace is similar to the System.Data.OleDb namespace, but is optimized for access to SQL. Server 7.0 and later. SystemData.SqlTypes The System.Data.SalTypes namespace provides classes for native data types in SQL Server. These classes provide a safer, faster alternative to the data types provided by the .NET Framework common language runtime (CLR). Using the classes in this namespace helps prevent type couyrsion errors caused by loss of precision, Because other data types ar; ed to and from Sql Types behind the scenes, explicitly ereatin; i objects within this namespace also yields faster code. i Ps yi ON Y Connection Object 9 ) A primary function of any database application is connecting to a dat®surce and retrieving the data that it contains. The NET Framework data providers }O.NET serve as a bridge between an application and a data source, allowing you ite commands as well as to retrieve data by using a DataReader or a DataAday key function of any database application is the ability to update the data that is stored’in.tht database In ADO.NET you use a Connection object to c to a specific data source by supplying necessary information in a connection string. {hs Camnectn object you use depends on the type of data source. C - Each .NET Framework data provi object: the NET Framework Dat the NET Framework Data Pr Framework Data Provider, Framework Data Provider race includes an OracleConnection object, Steps to connect datal 1. Create Databi 2. Start writing confection string in VB.Net. Com Seda have ConnectionString property. Depends on the parameter specified in the ConndetionSiring, ADO.Net Connection Object connect to the specified Database. Properties : included with the NET Framework has a Connection ider for OLE DB includes an OleDbConnection obj ConnectionString Gets/sets the connection string to open a database. Database : Gets the name of the database to open. DataSource Gets the name of the SQL Server to use. State : Gets the connection’s current state Page 11 of 26 USOSCCSCO3 Visual Programming through VB.NET UNIT 4 : Database Programming Methods : Close Closes the connection to the data provider. Open Opens a database connection. mmand vet: > It’s depended on Connection Object. > Command objects are used to execute commands to a database across a data coneeiny » The Command object in ADO.NET executes SQL statements and stored ci es against the data source specified in the connection object. The Command objects has a property called Command Text, rig Gea source (Query) value that represents the command that will be executed in me There are many ways to initialize Command object: © For Example Dim con As New SqlConnection Dim cmd As SqlCommand Dim strl As String v Strl = "Insert into stud values(‘”+ TextBox. Text con.Open() emd = New SqlCommand{(strl, con) cmd.ExecuteNonQuery() con.close() Q OR ay Dim con As New SqlC Q Dim cmd As see con.Open() emd,Connecti ‘TextBox Text +”) ‘Insert into stud values(‘"+ TextBox Text +”, °+ TextBox1.Text +") NonQuery() Property Meaning ‘CommandText Gets/sets the SQL statement (or stored procedure) for this command to execute. ‘CommandType Gets/sets the type of the CommandText property (typically set to text for SQL). ‘Connection Gets/sets the SqlConnection to use. Page 12 of 26 USOSCCSCO3 Visual Programming through VB.NET. UNIT 4 : Database Programming With ADO.NET Parameters Gets the command parameters. Page 13 of 26 US0SCCSC03 ‘Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET Methods Methods ‘Meaning ExecuteNonQuery Executes a non-row returning SQL statement, returning the number of affected rows ExecuteReader Creates a data reader using the command ExecuteScalar Executes the command and returns the value in the first column in the first row of the result. 2 DataAdapter 6 4] The SqlDataAdapter, serves as a bridge between a DataSet and SQL suit Dg and saving data, The SqlDataAdapter provides this bridge by mapping Fill, anges the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet, using the appropriate Transact-SQL statements against the data source. The update is performed on a by-row basis. ery inserted, modified, and deleted row, the Update method determines the type of chaufZ€ that has been performed on it (Insert, Update, or Delete), Depending on the type of chg ie Insert, Update, or Delete command template executes to propagate the modified Fes data source. When the SqlDataAdapter fills a DataSet, it gag returned data if they do not already exist. dapter is used in conjunction with SqlConnection and SqlCommand to increase CF ance when connecting to a SQL Server Kcessary tables and columns for the database, The SqlDataAdapter also includes_the SelettCommand, InsertCommand, DeleteCommand, UpdateCommand properties to facilifat® the ISading and updating of data. When an instance of SqIDataAdaptér’is created, the read/write properties are set to initial values. For a list of these values, s8e,the SqIDataAdapter constructor. The InsertCommand, DeléeCommand, and UpdateCommand are generic templates that are automatically filled fit) indi¥idual values from every modified row through the parameters mechanism. For every col at you propagate to the data source on Update, a parameter should be added to the InsertC id, UpdateCommand, or DeleteCommand. The SourceColumn property of the DbRgramétet object should be set to the name of the column, This setting indicates that the valu ae parameter is not set manually, but is taken from the particular column in the sey yeessed row. Properties Name Meaning DeleteCommand Gets or sets a Transact-SQL statement or stored procedure to delete records from the data set. TnsertCommand Gets or sets a Transact-SQL statement or stored procedure to insert new records into the data source. Page 14 of 26 US0SCCSC03 ‘Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET SeleciCommand Gets or sets a Transact-SQL statement or stored procedure used to select records in the data source. TableMappings Gets a collection that provides the master mapping between a source table and a DataTable. (Inherited from DataAdapter.) UpdateCommand Gets or sets a Transact-SQL statement or stored procedure used to update records in the data source. Methods ‘Meanin; = Fill ‘Adds or updates rows in a data set to match those in the data source. () Creates a table named "Table" by default Update Updates the data store by calling the INSERT, UPDATE, eo dataset statements for each inserted, updated, or deleted row a For Example : Oo Dim da As SqlDataAdapter Dim ds As New DataSet str = "selet™ from stud" Q da = New SqlDataAdapter(strl, con) WL da Fill(ds) x DataSet Object © > ADO.NET caches data locally on he cliduind store that data into DataSet. > The dataset is a disconnected, I-meioryrepresentation of data. > It’snot exact copy the datal > Itcan be considered as adovalégpy of the some portions of the database. > The DataSet contains ne jon of one or more DataTable objects made up of rows and columns of data. Tables can be ideptifféd in DataSet using DataSet’s Tables property. Italso crn key, foreign key, constraint and relation information about the data in the DataTable objects. DataS¢fré also fully XML-featured. Whater rations are made by the user itis stored temporary in the DataSet, when the thi ataSet is finished, changes can be made back to the central database for inne ay jabeSet doesn’t “know” where the data it contains came from and if fact it can contain lata from multiple sources. > The DataSet is populated DataAdapter’s Fill method. vv vv The DataSet is a major component of the ADO.NET architecture. The DataSet consists of a collection of DataTable objects that you can relate to each other with Data Relation objects. You can also enforce data integrity in the DataSet by using the UniqueConstraint and ForeignKeyConstraint objects. For further details about working with DataSet objects. Page 15 of 26 US0SCCSC03 ‘Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET Whereas DataTable objects contain the data, the DataRelationCollection allows you to navigate though the table hierarchy, The tables are contained in a DataTableCollection accessed through the Tables property. When accessing DataTable objects, note that they are conditionally case sensitive, For example, if one DataTable is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case sensitive. However, if “mydatatable" exists and "Mydatatable” does not, the search string is regarded as case insensitive, For more information about working with DataTable objects. A DataSet can read and write data and schema as XML documents. The data and s¢lfemean then be transported across HTTP and used by any application, on any platform that L- enabled. You can save the schema as an XML schema with the WriteXml Reo tha, and IL both schema and data can be saved using the WriteXml method. To read an yeument that includes both schema and data, use the ReadXml method. Ina typical multiple-tier implementation, the steps for creating and fefreshing a DataSet, and in turn, updating the original data are to: 1. Build and fill cach DataTable in a DataSet with dafP from a data source using @ DataAdapter. 2. Change the data in individual DataTable obje, DataRow objects. Invoke the GetChanges method to create @ .dding, updating, or deleting Gp Bast that features only the changes to the data, 4. Call the Update method of the Dat; passing the second DataSet as an argument. 5. Invoke the Merge method to mergl anges from the second DataSet into the first. 6. Invoke the en fataSet. Alternatively, invoke RejectChanges to cancel the changes. Properties ay Name Description Relations Get the co Sia ens that link tables and allow navigation from parent dt tables es. Tables Gets the c «ction of tables contained in the DataSet. DataGridView! DataSource = ds.Tables(0) Page 16 of 26 USOSCCSCO3 Visual Programming through VB.NET UNIT 4 : Database Programming DataReader Object Provides a way of reading a forward-only stream of rows from SQL Server database To create a SqlDataReader, you must call the ExecuteReader method of the SqlCommand object, instead of directly using a constructor. While the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader, and no other operations can be performed on the SqlConnection other tha closing it. This is the case until the Close method of the SqlDataReader is called. For e3 abl, you cannot retrieve output parameters until after you call Close. oh Changes made to a result set by another process or thread while data is being ri Gyn ‘ible to the user of the SqlDataReader. However, the precise behavior is timing we IsClosed and RecordsA fected are the only properties that you can call after‘the SqlDataReader is closed. Although the Records ffected property may be accessed while tht,SqlDataReader exists, always call Close before returning the value of RecordsAffecied to guarantee an accurate return value. Properties Name _ Description Connection Gets the SqlConnection associated IsClosed Retrieves a Boolean value tl instance has been closed. (O' s whether the specified SqlDataReader 's DbDataReader IsClosed.) Item Overloaded. “XS a column in its native format. Name Description Close CloseytheSqlDataReader object. (Overrides DbDataReader.Close(),) Read Ad SqlDataReader to the next record. (Overrides DbDataReader. Read().) Dim Q.. SqlDataReader "\Select * from stud” T con.Open() emd = New SqlCommand(sql, con) reader = emd.ExecuteReader() While reader Read() MsgBox(reader.Item(0) & " - " & reader-tem(1)) End While reader.Close() Page 17 of 26 US0SCCSC03 ‘Visual Programming through VB.NET UNIT 4 : Database Programming With ADO.NET emd.Dispose() con.Close() Catch ex As Exception MsgBox("'Can not open connection ! ") End Try DataGridView Control The DataGridView control provides a powerful and flexible way to display data it lar format. You can use the DataGridView control to show read-only views of a sm tof data, ot you can scale it to show editable views of very large sets of data. A You can extend the DataGridView control in a number of ways to build She) hhaviors into your applications. For example, you can programmatically specify yor og ing algorithms, and you can create your own types of cells. You can easily custofnize theappearance of the DataGridView control by choosing among several properties. Man§jtypes of data stores can be used as a data source, or the DataGridView control can operate with n6°Wata source bound to it The DataGridView control provides a customizable le for displaying data. The DataGridView class allows customization of cells, ro lumns, and borders through the use of properties such as DefaultCellStyle, Columnk faultCellStyle, CellBorderStyle, and GridColor. You can use a DataGridView control to di§playadgta with or without an underlying data source. Without specifying a data source, you c. ie columns and rows that contain data and add them directly to the DataGridView-tRing theRows and Columns properties. You can also use the Rows collection to access ridViewRow objects and the DataGridViewRow,Cells property to read or write cel fectly, The Item indexer also provides direct access to cells, As an alternative to in the control manually, you can set the DataSource and DataMember prope bind the DataGridView to a data source and automatically populate it with data. For more ififormation, see Displaying Data in the Windows Forms DataGridView Control When soni Pe large amounts of data, you can set the VirtualMode property to true to available data, Virtual mode requires the implementation of a data cache display a-sybsetof t fromgwhigh the DataGridView control is populated. For more information, see Data Display meen Windows Forms DataGridView Control For adWitional information about the features available in the DataGridView control, see DataGridView Control (Windows Forms). The following table provides direct links to common tasks. Step: 1] Take New VB.NET Project Step : 2 | Add database in your project (Named : dbemp.md?) ‘Add New Table in database file (Named : emp ) from the Server Explorer Window Page 18 of 26

You might also like