Binding List with Database in ASP.net

asp.net

Lastly we told you about the Server Controls in ASP.net and today we will explain how to fetch data from database. And display the content on the dropdown list in asp.net web form. So for this purpose we have to make a table in the database first. We will move forward step by step.
You can use any database software. But here I’m using MySQL Server 2012. Open the SQL server. Create a new project. Then in object explorer box you will see many folders. Right click on the database option and create new Database.

After clicking it a small screen will appear. That will ask for the name and row of the new database. Give it a desired name. I have given it a name Employee. This screen might appear like this. After giving it an appropriate name and no. of required rows press ok button.

Now after that you have to click the newly created Database in the object explorer. Some folders will be shown here. Right Click the table folder. Click create new table. And then enter the values in the columns section. Right click the CityID and make it primary key. It can’t be null so it will automatically get uncheck. Rest of the values can be null so let it be checked. And enter the type of the data that will be entered. ID can only be integer values so it is set as an integer. While other are set as nvarChar(50) according to the requirement. Now save it. I have saved it with emp name. So here our table is ready.

Now our table is ready we are ready to write a query and execute it. So let’s write our first query. Click on the new query button and write this query and execute it. As a result box will show that have values in it. For that you have to write another query.

So to insert the values you have to execute this query.

You are done with the database now lets move to the Visual Studio for web. Create a new project in visual studio. Add web form in it. Then in the designer view add a drop down list to the form. Now here is time to create a database connection. For that click the tool option then click the add database. A box will appear in front of you. In the server name enter the server name. Then select the database which you have created in the database. Here I have given it Employee name.

Now click the web config file in the solution explorer. And you will find connection string tag. You have to give it the database path.  Lets see it.

Now you have to write the code to fetch the data from the database.
Click the dropdownlist and press view code. Then in the load method. Write all the code.

You are done with the data binding. Now debug it. You will get the end result like this.

Article Written by Waleed Rashid. More info here.

Exit mobile version