Home » ASP.Net, GridView Tips, Tech Corner

Dropdownlist inside a Gridview

27 April 2009 No Comments Posted By:LG

How to use a dropdownlist in a gridview??
I will try explain this with best of my knowledge, the use of a dropdownlist inside comes when the case of edit update in a gridview comes. Consider an Eg:
A gridview that displays a “name” and a “Country”, and an option to edit the Country of a person. This is done from a dropdownlist.
ScreenShot
Initial Requirements:
1)
Tables(Ms sqlserver2008 is the back end database used in here)

Table name:- country_lloyd
CountryId int
CountryName varchar(50)

Table name:- Student
Id int
Name varchar(50)
CountryId int

2)
• Add a gridview (GridView1) to the page “Default.aspx”.
• It is filled with two fields, name and country name (for this an inner join is used),set the “Id” of the Student as datakey.How to set a dataKey??
• Remove “AutoGenerate Columns” of gridview.
• Add two bound fields convert it to template field.
• Add a Command Field “Edit Update Cancel”.

How to bind the values from the table to a “Template column” in the GridView???

1. Firstly “Edit templates” of the gridview (GridView1).Now in the “ItemTemplate” of Column [0]-Name drag and drop a label(name it “Label1”).And in the “ItemTemplate” of Column[1]-Country drag and drop another label(name it “lblCountry”).
2. Now in the “Edit Item Template” of Column [1]-Country drag and drop a dropdownlist (name it “ddl_CountryList”).
3. Now “End Template Editing”.
4. Now go to the html section of your page(“Default.aspx”),there you can find the html code of the gridview and the 3 controls we dragged in to the gridview, Now just check my code (“Default.aspx”) to understand what you need to do.This is how a value field is bound to a template column(Text=’<%# Bind(“Name”) %>’)

“Never loose faith if you find this a bit confusing, go on you will understand it.”

“Default.aspx”

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”
DataKeyNames=”Id” onrowcancelingedit=”GridView1_RowCancelingEdit”
onrowediting=”GridView1_RowEditing” onrowupdating=”GridView1_RowUpdating”>
<Columns>
<asp:TemplateField HeaderText=”Name”>
<ItemTemplate>
<asp:Label ID=”Label1″ runat=”server” Text=’<%# Bind(“Name”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Country”>
<EditItemTemplate>
<asp:DropDownList ID=”ddl_CountryList” runat=”server”>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID=”lblCountry” runat=”server” Text=’<%# Bind(“CountryName”) %> ‘></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton=”True” />
</Columns>
</asp:GridView>

Given below is the code segment of the “Default.aspx” page.
“Default.aspx.cs”

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
{
DBAccess dba = new DBAccess();
void FillGrid()
{
dba.GetTable(“select s.Name,s.Id,cl.CountryName from Student s inner join country_lloyd cl on cl.CountryId = s.CountryId”);
GridView1.DataSource = dba.dt;
GridView1.DataBind();
}
void fillCombo(DropDownList ddl)
{
dba.GetTable(“select * from country_lloyd”);
ddl.DataSource = dba.dt;
ddl.DataTextField = dba.dt.Columns[1].ToString();
ddl.DataValueField = dba.dt.Columns[0].ToString();
ddl.DataBind();
ListItem lstItem = new ListItem(“select”, “0″);
ddl.Items.Insert(0, lstItem);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGrid();
}

}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
string countryname = ((Label)GridView1.Rows[e.NewEditIndex].FindControl(“lblCountry”)).Text.ToString();
GridView1.EditIndex = e.NewEditIndex;
FillGrid();

DropDownList ddlCountryName = (DropDownList)GridView1.Rows[e.NewEditIndex].FindControl(“ddl_CountryList”);
fillCombo(ddlCountryName);
ddlCountryName.SelectedIndex = ddlCountryName.Items.IndexOf(ddlCountryName.Items.FindByText(countryname));

}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
FillGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddlCountryName = (DropDownList)GridView1.Rows[e.RowIndex].FindControl(“ddl_CountryList”);
string str= ddlCountryName.SelectedItem.Value.ToString();
string str1 = GridView1.DataKeys[e.RowIndex].Value.ToString();
dba.ExecuteQuery(“update Student set CountryId=’”+str+”‘ where Id=’”+ str1 +”‘”);
GridView1.EditIndex = -1;
FillGrid();
}
}

Notes:
1) FillGrid() is method to fill the grid with values.
2) void fillCombo(DropDownList ddl) is to fill the dropdownlist inside the gridview.
3) DBAccess() is the class used for database connection.
4)GridView row editing,row upadating,row canceling events for explained in the “gridview edit update cancel” post

Related posts:

  1. How to Bind Images from Database in a GridView
  2. Edit,Update,Cancel In a GridView
  3. Multiview and View controls in ASP.NET(3.5)
  4. FileUpload Control
  5. ‘Thread was being aborted’on using Response.Redirect,Response.End

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>