Sử dụng dropdownlist trong asp.net mvc

[Using Dropdownlist in a Gridview] Control Dropdowlist thường xuyên được sử dụng trên các Form nhập dữ liệu, và nó giúp người sử dụng dễ dàng lựa chọn giá trị từ các danh sách có sẵn. Bài viết dưới đây sẽ hướng dẫn các bạn cách sử dụng Control Dropdownlist trong Gridview. Trong Gridview sẽ gồm có 2 Dropdownlist và mỗi khi lựa chọn Dropdownlist châu lục nó sẽ lọc danh sách các quốc gia trong châu lục được chọn rồi điền vào Dropdownlist quốc gia.

Nghe những bài hát đỉnh nhất về Thấy cô giáo - Nghe trên Youtube






-B1: Tạo CSDLCustomerstrong SQL Server

-B2: Tạo BảngAccountscó cấu trúc phía dưới

STTTên trườngKiểu trườngGhi chú
1AccountIDIntTrường tự tăng
2AccountCodenvarchar[25]
3AccNamenvarchar[250]
4AccAddressnvarchar[250]
5AccPhonenvarchar[50]
6AccFAXnvarchar[50]
7AccEmailnvarchar[50]
8AccWebsitenvarchar[150]
9AccDescnvarchar[1500]
10CountryIDInt
11CreatedDatedatetime
12ModifiedDatedatetime

-B3: Nhập dữ liệu cho bảngAccounts

Chú ý:Trong Script chúng tôi cung cấp đã có chức năng Create và Insert dữ liệu cho 2 bảng Continents và Countries.

-B4: Tạo stored procedure trong SQL Server

USE[Customers]
GO

Cteate PROCEDURE [dbo].[Pro_Accounts_List]
@Keyword nvarchar[250],
@SortField nvarchar[50],
@SortType nvarchar[10]
AS

declare@strSQL nvarchar[1000]
declare @strWhere nvarchar[500]
declare @strOrder nvarchar [50]

set @strSQL= 'Select *, Countries.ContinentID
FROM Accounts INNER JOIN
Countries ON Accounts.CountryID = Countries.CountryID'
set @strWhere =' Where 1=1 '

if @Keyword''
set @strWhere= @strWhere +' And [AccountCode like N''%' +@Keyword+'%''
Or AccName like N''%' +@Keyword+'%'' Or AccAddress like N''%' +@Keyword+'%''
Or AccPhone like N''%' +@Keyword+'%'' Or AccFAX like N''%' +@Keyword+'%''
Or AccEmail like N''%' +@Keyword+'%'' Or AccWebsite like N''%' +@Keyword+'%'']'

if @SortField='CreatedDate'
Begin
set @strOrder =' Order by CreatedDate'
End
Else
Begin
set @strOrder =' Order by AccName'
End

set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL

exec sp_executesql @strSQL
Go

Bạn có thể tải về bảng cơ sở dữ liệu SQL bằng cách nhấn vào liên kết tải về dưới đây
-B5: Tạo Project trong Microsoft Visual Studio 2010

Trong Visual Studio tạo 1 Class có tên: Utility và nhập đoạn Code phía dưới cho Class này.

Imports System.Data.SqlClient
Imports System.Data

Namespace AccessingDropDownListInsideGridView

Public Class SqlDataProvider

#Region "Membres Prives"

Shared _IsError As Boolean = False
Private _connectionString AsString

#End Region

#Region "Constructeurs"

Public Sub New[]
Try
_connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString
_IsError = False
Catch ex As Exception
_IsError = True
End Try
End Sub

#End Region

#Region "Proprietes"

Public ReadOnly Property ConnectionString[] AsString
Get
Return _connectionString
End Get
End Property

#End Region

#Region "Functions"

Public FunctionFillTable[ByVal sql AsString] As DataTable
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter[sql, _connectionString]
adap.Fill[tb]
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function

Public FunctionFillTable[ByVal ProcName As String, ByVal ParamArrayPara[] As ObjectPara] As DataTable
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter[ProcName, _connectionString]
adap.SelectCommand.CommandType = CommandType.StoredProcedure
If NotPara Is NothingThen
For Eachp As ObjectParaIn Para
adap.SelectCommand.Parameters.Add[New SqlParameter[p.Name, p.Value]]
Next
End If
adap.Fill[tb]
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function

#End Region

End Class

Public Class ObjectPara
Dim _name As String
Dim _Value As Object

Sub New[ByVal Pname As String, ByVal PValue As Object]
_name = Pname
_Value = PValue
End Sub

Public PropertyName[] As String
Get
Return _name
End Get
Set[ByVal value As String]
_name = value
End Set
End Property

Public PropertyValue[] As Object
Get
Return _Value
End Get
Set[ByVal value As Object]
_Value = value
End Set
End Property

End Class

End Namespace

Chú ý: Thuộc tínhSiteSqlServerchính là chuỗi Connect với SQL Server trong file Web.Config

-B6:Mở file Default.aspx dưới dạng HTML và nhập mã HTML
Accessing a DropDownList inside a GridView in Asp.net

-B7:Viết Code cho file Default.aspx
C# Code
//Visit //www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Diagnostics;

namespace AccessingDropDownListInsideGridView
{
public partial class _Default : System.Web.UI.Page
{

#region"ComboData"

private void LoadDropDownList[DropDownList ucControl, stringDataValueField, string DataTextField, string sql]
{
SqlDataProvider objSQL = newSqlDataProvider[];
DataTable objBind = objSQL.FillTable[sql];

ucControl.Items.Clear[];

if[objBind != null]
{
ucControl.DataTextField = DataTextField;
ucControl.DataValueField = DataValueField;
ucControl.DataSource = objBind;
ucControl.DataBind[];
ucControl.Items.Insert[0, [new ListItem["---Select---", "-1"]]];
}
}

#endregion

#region"Bind Data"

private voidBindAccount[]
{
DataTable objBind = newDataTable[];
objBind = BindData[];

if [objBind != null]
{
if [objBind.Rows.Count > 0]
{
grvObject.DataSource = objBind;
grvObject.DataBind[];
trMessage.Visible = false;
grvObject.Visible = true;
}
else
{
trMessage.Visible = true;
grvObject.Visible = false;
}
updatePanel.Update[];
}
}

private DataTableBindData[]
{
SqlDataProvider objSQL = newSqlDataProvider[];
DataTable objBind = objSQL.FillTable["Pro_Accounts_List", new ObjectPara["@Keyword", txtSearch.Text], new ObjectPara["@SortField", "CreatedDate"], new ObjectPara["@SortType", "DESC"]];
return objBind;
}

#endregion

#region"GridView Methods"

protected voidgrvObject_RowDataBound[object sender, GridViewRowEventArgs e]
{
if [e.Row.RowType == DataControlRowType.DataRow]
{
int ContinentID =Convert.ToInt32[DataBinder.Eval[e.Row.DataItem, "ContinentID"]];
int CountryID = Convert.ToInt32[DataBinder.Eval[e.Row.DataItem, "CountryID"]];
DropDownList ddlContinents = [DropDownList]e.Row.FindControl["ddlContinents"];
if [ddlContinents != null]
{
string sSQL = "Select ContinentID, ContinentName from Continents";
LoadDropDownList[ddlContinents, "ContinentID", "ContinentName", sSQL];
if [ContinentID != -1]
{
ddlContinents.SelectedValue = ContinentID.ToString[];
ddlContinents_SelectedIndexChanged[ddlContinents, System.EventArgs.Empty];
}
}
DropDownList ddlCountries = [DropDownList]e.Row.FindControl["ddlCountries"];
if [[ddlCountries != null]]
{
ddlCountries.Items.Insert[0, [new ListItem["---Select---", "-1"]]];
ddlCountries.SelectedValue = CountryID.ToString[];
}
}
}

protected voidgrvObject_PageIndexChanging[object sender, System.Web.UI.WebControls.GridViewPageEventArgse]
{
grvObject.PageIndex = e.NewPageIndex;
BindAccount[];
}

#endregion

#region"Event Handles"

protected voidPage_Load[object sender, System.EventArgs e]
{
try
{
if [!IsPostBack]
{
Page.Form.DefaultButton = cmdQuickSearch.UniqueID;
BindAccount[];
}
}
catch
{
}
}

protected voidcmdQuickSearch_Click[object sender, System.EventArgs e]
{
BindAccount[];
}

protected voidddlContinents_SelectedIndexChanged[objectsender, EventArgs e]
{
DropDownList ddlObject = [DropDownList]sender;
DropDownList ddlContinents = new DropDownList[];
DropDownList ddlCountries = new DropDownList[];
GridViewRow row = [GridViewRow]ddlObject.NamingContainer;
int ItemID = -1;

ddlContinents = [DropDownList]row.FindControl["ddlContinents"];
ddlCountries = [DropDownList]row.FindControl["ddlCountries"];

if [ddlContinents != null]
{
ItemID =Convert.ToInt32[ddlContinents.SelectedValue];
}

if [ItemID != -1]
{
string sSQL = "Select CountryID, CountryName from Countries where ContinentID=" + ItemID;
LoadDropDownList[ddlCountries, "CountryID", "CountryName", sSQL];
}
updatePanel.Update[];
}

#endregion
}
}
VB.NET Code
'Visit//www.laptrinhdotnet.comfor more ASP.NET Tutorials
Imports System.Data.SqlClient

Namespace AccessingDropDownListInsideGridView

Public Class _Default
Inherits System.Web.UI.Page

#Region "Private Members"

#End Region

#Region "ComboData"

Private SubLoadDropDownList[ByVal ucControl As DropDownList, ByVal DataValueField AsString, ByValDataTextField As String, ByVal sql As String]
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable[sql]

ucControl.Items.Clear[]

If Not objBind Is Nothing Then
WithucControl
.DataTextField = DataTextField
.DataValueField = DataValueField
.DataSource = objBind
.DataBind[]
End With
ucControl.Items.Insert[0, [New ListItem["---Select---", "-1"]]]
End If
End Sub

#End Region

#Region "Bind Data"

Private SubBindAccount[]
Dim objBind As New DataTable
objBind = BindData[]

If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
grvObject.DataSource = objBind
grvObject.DataBind[]
trMessage.Visible = False
grvObject.Visible = True
Else
trMessage.Visible = True
grvObject.Visible = False
End If
updatePanel.Update[]
End If
End Sub

Private FunctionBindData[] As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable["Pro_Accounts_List", New ObjectPara["@Keyword", txtSearch.Text.Trim], _
New ObjectPara["@SortField", "CreatedDate"], _
New ObjectPara["@SortType", "DESC"]]
Return objBind
End Function

#End Region

#Region "GridView Methods"

Private SubgrvObject_RowDataBound[ByVal sender As Object, ByVal e As GridViewRowEventArgs] HandlesgrvObject.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ContinentID AsInteger = DataBinder.Eval[e.Row.DataItem, "ContinentID"]
Dim CountryID AsInteger = DataBinder.Eval[e.Row.DataItem, "CountryID"]
Dim ddlContinents As DropDownList = DirectCast[e.Row.FindControl["ddlContinents"], DropDownList]
If NotddlContinents Is NothingThen
Dim sSQL AsString = "Select ContinentID, ContinentName from Continents"
LoadDropDownList[ddlContinents, "ContinentID", "ContinentName", sSQL]
If ContinentID -1 Then
ddlContinents.SelectedValue = ContinentID
ddlContinents_SelectedIndexChanged[ddlContinents, System.EventArgs.Empty]
End If
End If
Dim ddlCountries As DropDownList = DirectCast[e.Row.FindControl["ddlCountries"], DropDownList]
If NotddlCountries Is NothingThen
ddlCountries.Items.Insert[0, [New ListItem["---Select---", "-1"]]]
ddlCountries.SelectedValue = CountryID
End If
End If
End Sub

Private SubgrvObject_PageIndexChanging[ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewPageEventArgs] Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindAccount[]
End Sub

#End Region

#Region "Event Handles"

Protected SubPage_Load[ByVal sender AsObject, ByVal e As System.EventArgs] Handles Me.Load
Try
If Page.IsPostBack = False Then
'Default Submit Button
Page.Form.DefaultButton = cmdQuickSearch.UniqueID
BindAccount[]
End If
Catch ex As Exception

End Try
End Sub

Private SubcmdQuickSearch_Click[ByVal sender As Object, ByVal e As System.EventArgs] HandlescmdQuickSearch.Click
BindAccount[]
End Sub

Protected SubddlContinents_SelectedIndexChanged[ByVal sender As Object, ByVal e As EventArgs]
Dim ddlObject As DropDownList = DirectCast[sender, DropDownList]
Dim ddlContinents As DropDownList = NewDropDownList
Dim ddlCountries As DropDownList = NewDropDownList
Dim row As GridViewRow = DirectCast[ddlObject.NamingContainer, GridViewRow]
Dim ItemID As Integer = -1

ddlContinents = DirectCast[row.FindControl["ddlContinents"], DropDownList]
ddlCountries = DirectCast[row.FindControl["ddlCountries"], DropDownList]

If Not ddlContinents Is Nothing Then
ItemID = ddlContinents.SelectedValue
End If

If ItemID -1 Then
DimsSQL As String= "Select CountryID, CountryName from Countries where ContinentID=" & ItemID
LoadDropDownList[ddlCountries, "CountryID", "CountryName", sSQL]
End If
updatePanel.Update[]
End Sub

#End Region

End Class

End Namespace

Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.





Chúc các bạn thành công!

Quang Bình

Video liên quan

Chủ Đề