• home
  • Email: trainings@synapseindia.careers



Understanding Complex Data Binding in ASP.NET Web Forms

Mar 09, 2016

Data binding is one of the effective methodology in ASP.NET Web forms where we can bind some of the list controls and data controls with various kind of data sources like array, collections , data reader , Sqldatasource as well as with dataset table fields. In this article , we will bind Dropdownlist with SqlDataSource. Take an scenario where you have to display all employee ids in a DropDownList. Follow the below simple steps ,

Step 1: Add SqlDataSource into the webform and add one DropDownList as in below code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:myconnection %>" SelectCommand="select * from employee"> </asp:SqlDataSource>

<asp:DropDownList ID="DropDownList1" runat="server"> </asp:DropDownList>


</form> </body> </html>

Step 2: In the above code , we have passed a fetched a connection string name 'myconnection' added into the web.config file as below:

<?xml version="1.0"?>

<!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 -->


<system.web> <compilation debug="false" targetFramework="4.0" /> </system.web>

<connectionStrings> <add name="myconnection" connectionString="Data Source=PC13\SQLEXPRESS;Initial Catalog=synapse;Integrated Security=true"/>

</connectionStrings> </configuration>

Step 3: This is the final step where we will work with the .cs file for binding DropDownList control with SqlDataSource as below :

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {

DropDownList1.DataSourceID = "SqlDataSource1"; DropDownList1.DataTextField = "eid";

} } On page load stage , all value of eid column in employee table will be bound into DropDownList1 control.  In the next article also we will cover more about complex binding.

.NET is one from the list of various SynapseIndia technologies used for developing scalable and dynamic web applications.  We have delivered many projects to our international clients on .NET with good reviews.

SynapseIndia (CEO: Shamit Khemka)