Hi Mehram,
Refer below code
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="CustomerId" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Country" SortExpression="SampleDetail">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>' Visible="false"></asp:Label>
<asp:DropDownList ID="countries" runat="server" CssClass="chzn-select">
<asp:ListItem Text="United States" Value="0"></asp:ListItem>
<asp:ListItem Text="India" Value="1"></asp:ListItem>
<asp:ListItem Text="France" Value="2"></asp:ListItem>
<asp:ListItem Text="Russia" Value="3"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<ItemStyle HorizontalAlign="left" Width="5px" Wrap="true" />
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
GridView1.DataSource = GetData("SELECT CustomerId, Name, Country FROM Customers");
GridView1.DataBind();
}
}
private DataSet GetData(string query)
{
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
Code
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
GridView1.DataSource = GetData("SELECT CustomerId, Name, Country FROM Customers")
GridView1.DataBind()
End If
End Sub
Private Function GetData(ByVal query As String) As DataSet
Dim constring As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim cmd As SqlCommand = New SqlCommand(query)
Using con As SqlConnection = New SqlConnection(constring)
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using ds As DataSet = New DataSet()
sda.Fill(ds)
Return ds
End Using
End Using
End Using
End Function
Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim countries As DropDownList = (TryCast(e.Row.FindControl("countries"), DropDownList))
Dim country As String = (TryCast(e.Row.FindControl("lblCountry"), Label)).Text
countries.Items.FindByText(country).Selected = True
End If
End Sub
Screenshot