Hi nauna,
Check this example. Now please take its reference and correct your code.
Database
For this example i have used of Northwind database that you can download using the link given below.
Download Northwind Database
HTML
<asp:DropDownList runat="server" ID="ddlCustomers">
</asp:DropDownList>
<asp:Button Text="Save" runat="server" OnClick="OnSave" />
DataAccess
C#
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using NorthwindModel;
public class DataAccess
{
public List<ListItem> GetCustomers(string country)
{
NorthwindEntities entities = new NorthwindEntities();
List<ListItem> items = (from c in entities.Customers
orderby c.ContactName
where c.Country == country
select new ListItem
{
Text = c.ContactName,
Value = c.CustomerID
}).ToList();
items.Insert(0, new ListItem { Text = "Select", Value = "0" });
return items;
}
}
VB.Net
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Web.UI.WebControls
Imports NorthwindModel
Public Class DataAccess
Public Function GetCustomers(ByVal country As String) As List(Of ListItem)
Dim entities As NorthwindEntities = New NorthwindEntities()
Dim items As List(Of ListItem) = (From c In entities.Customers
Order By c.ContactName
Where c.Country = country
Select New ListItem _
With {.Text = c.ContactName, .Value = c.CustomerID}).ToList()
items.Insert(0, New ListItem With {.Text = "Select", .Value = "0"})
Return items
End Function
End Class
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataAccess da = new DataAccess();
ddlCustomers.DataSource = da.GetCustomers("USA");
ddlCustomers.DataTextField = "Text";
ddlCustomers.DataValueField = "Value";
ddlCustomers.DataBind();
}
}
protected void OnSave(object sender, EventArgs e)
{
string id = ddlCustomers.SelectedValue.Trim();
string name = ddlCustomers.SelectedItem.Text.Trim();
ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('Name : " + name + "\\nId : " + id + "')", true);
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim da As DataAccess = New DataAccess()
ddlCustomers.DataSource = da.GetCustomers("USA")
ddlCustomers.DataTextField = "Text"
ddlCustomers.DataValueField = "Value"
ddlCustomers.DataBind()
End If
End Sub
Protected Sub OnSave(ByVal sender As Object, ByVal e As EventArgs)
Dim id As String = ddlCustomers.SelectedValue.Trim()
Dim name As String = ddlCustomers.SelectedItem.Text.Trim()
ClientScript.RegisterClientScriptBlock(Me.GetType(), "", "alert('Name : " & name & "\nId : " & id & "')", True)
End Sub
Screenshot