You are on page 1of 23
Create a simple data application by using ADO.NET ice «27/2023 Applies to: @visual Studio % Visual Sudo for Mac % Visual Studio Code Note Datasets and related classes are legacy NET Framewor nologies from data in memory while the applications are disconnected from the database, They are especially useful for applications that enable We early 2000s that enable applications to work wit Users to modify data and persist the changes back to the database, Although datasets have proven to be a very successful technology, we recommend that new NET applications use Entity Framework Core, Entity Framework provides mote natural way to work with tabular data as object models, and it has a simpler programming interface When you creat an application that manipulates data in a database, you perform basic tasks such as defining connection strings, inserting data, and running stored procedures. By following this topic, you can discover how to interact with a database from within 2 simple Windows Forms “forms over data” application by using Visual C# or Visual Basic and ADO.NET. All. NET data technologies— including datasets, LING to SQL, and Entity Framework—uimately perform steps that are very similar to those shown inthis article. This article demonstrates a simple way to quickly 9 fata out of a database. I your appli ways and update the database, you should conser sin needs to modify data in non-trivial ity Framework and using data binding to automatically sync user interface controls to changes in the underiying data © Important To keep the code simple, it doesn’t inchide preduetion-ready exception handling ONote The complete code for ths tutorial can be accessed in the Visual Studio docs GitHub repo in Ci and Visual Basic Prerequisites To create the applic tion, you'll need: ++ Visual Studio, ‘+ SQL Server Express LocalDB, Ifyou don’t have SQL Server Express LocalDB, you can install it from the SQl Server dovinload page This topic assures that you're fanliar with the basic functionality ofthe Visual Studio IDE and can create a Windows Forms application, add forms to the project, put buttons and other controls on the forms, et properties ofthe controls, and code simple events. Ifyou are Visual Basic tutorial or the Create a Windows Forms app in Visual Studio with C¥ tutorial before you s -omfortable with these tasks, we suggest that you complete the Create 2 Windows Forms app in Visual Studio with this walkthrough, Set up the sample database Create the sample database by following these st 1. In Visual Studio, open the Server Explorer window. 2, Right-click on Data Connections and choose Create New SQL Server Database, 3 In the Server name text box, enter (locald)\mssallocaldb. 4. nthe New database name textbox, enter Sales, then choose OK. The empty Sales database is created and added to the Data Connections node in Server Explorer. 5, Right- Format = Short Nam toFiloae Name » dgyCustomerOrders Readonly= Te RowHaadenVisible = False toCaneelorder When your application tries to open a connection to the database, your application must have access to the connection string, To avoid entering the string manually on each form, store the string in the App.canfig file in your project, and create a method that returns the string when the method is called from any form in your application You can find the connection string by right-clicking on 1 Sales data connection in Server Explorer and choosing Properties. Locate the ConnectionString property, then use Ctrl+A, Ctel+C to select and copy the sting to the clipboard. 1. you're using CA, in Solution Explorer, expand the Properties node under the project, and then open the Settings settings file. If you're using Visual Basic in Solution Explorer, click Show All Files, expand the My Project node, and then open the Settings settings file 2. tn the Name column, enter connstring 3. tn the Type list, select (Connection String) A. Inthe Scope list, select Application 5h the Value column, enter your connection string (without any outside quotes) and then save your changes, Agen i sn oo str rit opt tng an her Hers ye mn ny ag pin or > csung Reon ne Sure Hcalhenasial Caa-Saknted ey Tok + Sete stip ONote Ina real application, you should store the connection string securely, a5 described in Connection strings and configuration files Write the code for the forms This section contains brief overviews of what each form does. t also provides the code that defines the underlying logie when a button ‘on the form is clicked Navigation form ‘The Navigation form opens when you run the application. The Add an account button opens the NewCustomer form. The Fill or ‘cancel orders button opens the FillOrCancel form. The Exit button closes the application, Make the Navigation form the startup form If you're using Cé, in Solution Explorer, open Program.cs, and then change the application. fun line to this: application. Run(new Navigetion()); It you're using Visual Basic, in Solution Explorer, open the Properties window, select the Application tab, and then select ‘SimpleDataApp Navigation in the Startup form list Create auto-generated event handlers Double-click the three buttons on the Navigation form to create empty event handler methods, Double-clicking the buttons also adds ‘auto-generated code in the Designer cade file that enables a button click to raise an event. Note Ifyou skip the double-click action in the designer and just copy the code and paste it into your code fils, don't forget to set the event handler to the right method. You can do this in the Properties window. Switch to the Events tab (use the lightning bolt toolbar button) and look for the Click handler Add code for the Navigation form logic In the code page for the Navigation form, complete the method bodies forthe three button click event handlers as shown in the following code. ve Opens the NesCustoner form as a dialog bot, which returns focus to the calling form when St closes, Private Sub btacoToadd click(sender As Object, e As Eventargs) Handles btncoToadd.Click Din frm As Form = few Hewcustoner() fen.shoa() end Sub Opens. the F£210rcancel form a5 2 dialog box Private Sub btaGoToFillorcancel Click(sender As Object, © As EventArgs) Handles benGoToFiiLOrcancel Click Din frm As Form ~ New Fall0-cencel() ‘en. showDiatog() nd Sub Closes the application (not just the navigation fora) Private Sub btnExit_Click(sender As Object, ¢ As EventArgs) Handles benExdt.Click e.close() end sub ONote The code for ths tutorial is avalable in C# and Visual asic, To switch the cade language on this page between C# and Visual Basic, use the cade language switcher at the top ofthe page on the right side NewCustomer form When you enter a customer name and then select the Create Account button, the NewCustomer form creates a customer account, and SSQL Server returns an IDENTITY value as the new customer ID. You can then place an order for the new account by specifying an amount and an order date and selecting the Place Order button, Create auto-generated event handlers Create an empty Click event handler for each button on the NewCustomer form by double-clicking on each of the four buttons. Double-clcking the buttons also adds auto-generated code inthe Designer code fle that enables a button click to raise an event. Add code for the NewCustomer form logic To complete the NewCustomer form logic follow these steps. 1. Bring the systen.oata.sqlclient namespace into scope so that you don't have to fully qualify the names ofits members. ve Imports Systen.0sta.SaiCiient 2, Add some variables and helper methods to the class as shown in the following code, ve ve Storage for ID values returned fron the database, Private parsedcustonerTO As Tnteger Private andertD As Integer csumary>: Verdfaee that the custoner nate text box ie not enaty. Private ReadOnly Property IscustoneraneValié As Boolean Get If extcustonertane. Text = ° Then Hessagedox.shou(*PLease enter a ni Return False case end IF end Get End Property Verifies the order data 4s valid, efsunnary> Private Function Isorderbstavalid() As Boolean * Verify that CustorerID is present Af txtcustomersD.Text = "Then Messagetox.Show("Please create a custoner account before placing order.") Return False. * Verify that order ancunt isn’t 8. sel (runOrderanount.valve < 2) Then Messagetox.Show("Piease specify an order ancunt.") Return False. else nd 2 End Function Clears values fron controls. Patvate Sub ClearFooa() ‘extcustonerhane.clear() ‘execustonert9.clear() dtgorderdate.value = DateTine.Now rurdrderAnount.value ~ @ e.parsedCustoneriD = @ end Su 3, Complete the method bodies forthe four button click event handlers as shown in the following code, ve Creates a new account by executing the Salles.usplewCustoner stored procedure on the database Private Sub btncreatekecount Click(sender As Object, © AS Eventangs) Handles beacreatesccount Click * engure a custoner nane has been enveres. 4 TecustoneriianeValia) Then * create the SqiConnection object. Using connection As New SqlConnection(hy. Settings connstring) * create a SqlConmand, and identify the command type as 2 stored procedure Using sqlconnand as New SqlCoemand("sales.uspNexcustoner", connection) sqlconmand.CommandType = Conmandtype. StoredProcedure "Ade the customer rane input paraneter for the stored procedure. sqlcomané,Paraneters.Add(New SqlParancter("®Custonertane", Sq1DoType.Warchar, 48)) salconnang,Paraneters("CustonerNane").Value = ¢xtCustonertane. Text * Ade the custoner 1D output parameter, sqlcomand.Paraneters.Add(New SqlParancter("EcustonerIO", Sql0bType.Tot)) sqlconand.Paraneters("AcustonerI0").0irection = ParaneterDirection-Output ry "open the conection. connection. open() * fun the stored procedure. salconmand, ExecuteNonguery() * convert the Custoner 10 value to an Integer. Ne-parsedcustonerib = CInt(sqiComnand. Paraneters("pcustoneri0").Value) Insert the custoner 10 into the corresponding text box. e-txtCustonerI0. Text = Convert. ToString(parsedCustonerI0) cater NessageBox.Show("Custoner ID was rot returned. Account could not be created") Finally Chose the connection. connection. close() tnd Try End using nd Using end 2 end suo Places the ordes by executing the Sales.uspPlaccNerder Stored procedure on the database efsunnary> Private Sub btnPlaceonder_CLick(sender As Onject, @ AS EventArgs) Handles benPlaceorden.Click Xf Ts0rderbatavalid() Then * create the connection. Using connection As New SqlConnection(hy. Settings connstring) * create Sqlconmand and identify it as a stored procedure, Using sqlConnand As New SqlCormand("Sales.uspPlaceNexOrder", connection) sqlconmand.Commandlype = Conmandtype.Storedrocedure " dé the @custoneriD paraneter, which was an ovtput parameter fron uspWeCustoner. salonnang,Paraneters.Aad(New SqlParaneter("BCustoneriI0", SelDbType.Int)) sqlConnand,Paraneters("eCustonerT0").Value = He.parsedcustorerI0 * ade the Gonderoate paraneter. sqlcomand.Paraneters.Add(New SqlParancter("forde*oate", Sqlobrype.Datetine, 8)) sqlconnang,Paranetere("BOrderdate").Value = dtpOrderoate, value " Ade the @tnount paraneter sqlconand,Paraneters.Add(New SqlParaneter("Banount", Sql0bType-Int)) sqiComand,Paraneters("gtrount”) Value = sundrderanount Value Add the @Status parameter, For a new order, the status is always 0 (open). salConmang, araneters.Aad(New SqlParaneter(“BStatus", SqlDbType-[Char], 1)) salconmand. Paraneters( "status" “o "Ade a return value paraneter for the stored procedure, which 4 the ordartD, sqlcomand.Paraneters.Add(New SqlParaneter("®C", SqlDbType.Int)) sqlconand.Paranetens("GRC") Direction = Paraneteroirection.Aeturnvalue Wry open connection. connection. pen() * fun the stored procedure salconmand, ExecuteNonguery() " Display the orden nunter. evorderdO = CInt(sqlComnand. Paraneters("ei"). Valve) Nessagetox.Show("Order nunber ~ & (Me,orderT).ToString & " has been subnitted.") cater "A siaple catch, NessageBox.Show("Order could not be placed.") Finally "Always close ® connection after you Finish using st, " so that it can be released to the conection pool. conection, lose() tnd try End Using nd Using end 1 csumary>: Resets the for for another new account. Private Sub btnaddAnotherAccount_Click(sender As Object, © As EventArgs) Handles btnAddanothernccount Click e.ClearForn() End Sub Closes the NewCustorer form and returns focus to the Navigation fore Private Sub btnaddrinish Click(sender AS Object, e AS EventArgs) Handles btnAddFinish. click e.close() FillOrCancel form The FillOrCancel form runs a query to return an order when you enter an order ID and then click the Find Order button. The returned row appears ina read-only data grid. You can mark the order as canceled 09 if you select the Cancel Order button, or you can mark the order as filled (F if you select the Fill Order button, Ifyou select the Find Order button again, the updated row appears. Create auto-generated event handlers {create empty Click event handlers forthe four buttons onthe FilOrCancel form by double-clicking the buttons. Dovble-clcking the butane also adds auto-generated code inthe Designer code ie that enables a button cick to rasa an event Add code for the FillOrCancel form logic To complete the Filorcancel form logic follow these steps. 1. Bring the following two namespaces into scope so that you don't have to fully qualify the names of their members Imports Systen.0sta.SaiCiient Inport Systen.Text Regulartxpressions 2, Add a variable and helper method to the class as shown in the following code. ve ve Storage for Ordert0, Private parsedrdert0 As Tateger csumary>: Verdfaae that Orders 4s valid. Private Function IsOrderiovalié() As #ootean * check For input tn the Order 1D text box. TF txtOrden1D. Text MessageBox. Show” Return False. check for characters other than integers. ElseZF Regex. IsMaten(txtOrderI0, Text, °\0"5") Then * show message and clear input. Messagedox.Show("Please specify integers only.") ‘tordert9.Clear() Return False ese * convert the text in the text box to an integer to send to the databace. parsedorderiD ~ int32,Parse(extorderi9. Text) Return True nd 2 end Function 3. Complete the method bodies forthe four button click event handlers as shown inthe following code. va ve Executes a t-SQL SELECT query on the database to stain order data for a specified oréer 10. Private Sub btnFind8yOrderi0_Click(sender As Object, © As EventArgs) Handles btnFindsyordertD. Click * Prepare the connection and the command If TsOedertOvalid() Then create the connection, Using connection As New SqlConnection(hy. settings conastring) " beFine the query string that has a paraneter for orderIO. Const sql As String = "select * from Sales.Orders where orderID ~ @orderIb" * create a Sqlconmand object. Using sqlConnand As New SqlConmand(sal, connection) " vefine the fordertD paraneter and its value. sqlconand.Paraneters.Add(New SqlParaneter("Borden10", Sqlbetype.tnt)) sqlcennang,Paraneters("Borderi0").value = parsedd-ders0 Try open connection connection. open() * execute the query. in datakescer Az SqlDataReacer = sqlComand.cxecutekeader() Create a data table to hold the retrieved data Din datarable As New DataTabie() Load the data from SqlDataReader into the dats table, gatatable.Load(datateader) " ohsplay the data from the data table in the date grid view. Ne. dgvcustanerorders DataSource ~ dataTable Close the sqlDatakeader. dataReader.Close() cater MessageBox. Show("The requested orden could not be loaded inte the fore.") Finally "Close the connection. ‘connection. Close() nd try nd Using End Using nd 1 End Su esumary>: " FLLIS an onder by running the Sales.uspFillOnder stored procedure on the database. Private Sub btnFillorder_Click(sender As object, e As EventArgs) Handles btnFillOrder.Click * Set up and run stored procedure only Sf OrdertD 4s valtd. If Ts0edersOvaLid() Then * create the connection. Using connection As New SgiConnection(hy. Settings .connstring) * create command and identify it as a stored procedure: Using sqlConnand AS New SqlComnand( "sales. uspFLlOnder connection) sqlconmand.Connandlype = Connandtype.storedProcedure Add Snput paraneter for the stored procedure. saiComand,Paraneters.Add(New Sq1Paraneter("Borde10", Sal0sType.Tnt)) salconmand.Paraneters("orderi0").Value = parseadederi0 " ade second input paraneter, sqlcomand.Paraneters.Aad(New SqlParancten("@Fillecoste", sqlObType.DateTine, 8)) sqiconnang,Paraneters("grilledbace").Value ~ dtpFillbate, Value Try ‘pen the connection connection.pen() * fun the Selcomang, salcomnand, ExecuteNonguery() caten " A simple catch. NessageBox.Show("The Fil operation was not conpletes.") Finally Close the connection. conection. close) nd Try End using nd Using end 2 end Su Cancels an order by running the Sales.uspCancelorder stored procedure on the database. Private Sub btncancelorder_click(sender As Object, @ As EventArgs) Handles btnCancelOrder.CLick "Set up and run the stored procedure only if Ordert0 is ready. 1 TeOedersovel44() Then * create the connection. Using connection As New SqlConnection(hy. Settings constring) * create the connand and identify st as a stored procedure. Using sqiConmand As New SqlCommand("Saies.uspCancelOrder”, connection) sqlConmand.CommandType = ConmandType. StoredProcedure " adé input parameter for the stored procedure. sqlcomand.Paraneters.Add(New SqlParaneter("Bordes10", SqlDsType.tnt)) sqicenmang,Parsneters("Border0").Value ~ parsedd-ders0 Try ‘Open the connection. connection.0pen() * fun the Seicomang, salcomnand, ExecuteNonguery() caten "A simple catch. NessageBox.Show("The cancel operation was not conpleted. Finally Close connection. connection. Close) nd Try End using nd Using end 2F end suo Closes the form and returns focus to the Navigation form Private Sub btnFinishupdates Click(sender As Object, © As EventArgs) Handles baFintshipdates cick e.ciese() Test your application fun the application an ty creating afew customers and orders to verify that everything is working as expected, To verify tha the database is updated with your changes, open the Tables node in Server Explorer, right-click on the Customers and Orders nodes, ane choose Show Table Data See also ‘Visual Studio data tools for NET

You might also like