Friday, 18 October 2013

Binding data to drop down list in C# .NET


In this article I will explain how to bind data to Dropdown list

This control supports data binding.

Below is method

First we need to declare a drop down list. We have an asp tag to add a drop down list.

<asp:DropDownList>

We will give an ID to every field. We are declaring a drop down list called “ddlClient”. Here we can mention the dimensions of the drop down list.

Width=”220px”


Whenever we change the selection in the drop down list the page is reloaded. For this we’ll write

AutoPostBack=”true”

Now the entire code is

ASP.N.ET

<table>
<tr>
<td>
  <asp:DropDownList runat="server" ID="ddlClient" Width="220px" AutoPostBack="true">                                                                            
                                                                                    </asp:DropDownList>
</td>
</tr>
</table>

Now we’ll look at the code which gets the data from the data base and binds it to the drop down list.

C#

First we’ll declare a method. Let’s take method called

public void GetDropDownList()

We’ll get the data from the data base using the method GetData();

The GetData method is then bound to the dataset.

dsGetData = objClass.GetData();

Then we’ll declare the datasource to the dropdown list ddlClient

ddlClient.DataSource = dsGetData.Tables[0];

Data text field to the drop down list ddlClient is given.

ddlClient.DataTextField = "ClientCode";

Data value to the drop down list ddlClient is declared.

ddlClient.DataValueField = "T_id";

Now we’ll bind the obtained data to drop down list ddlClient.

ddlClient.DataBind();

In the first row we’ll give something like ‘select’. To get a select at the top of the drop down list we need to write the following code.

if (dsPropertyType.Tables[0].Rows.Count > 0)
        {
            ListItem item = new ListItem("--Select Client--", "0");
            ddlClientModelPopup.Items.Insert(0, item);

        }

Now the entire code altogether is

public void GetDropDownList()
    {
        
        dsGetData = objClass.GetData();

        ddlClient.DataSource = dsGetData.Tables[0];
        ddlClient.DataTextField = "ClientCode";
        ddlClient.DataValueField = "T_id";
        ddlClient.DataBind();

        if (dsPropertyType.Tables[0].Rows.Count > 0)
        {
            ListItem item = new ListItem("--Select Client--", "0");
            ddlClientModelPopup.Items.Insert(0, item);

        }

    }

No comments:

Post a Comment