How to use DropDownList in GridView


In this article I have explained about how to use drop down list in grid view. In this example application I used employee table for bind details in Grid view. One field in the table mention employee retired or not. I show in the grid view Yes/No if user click edit option that two values are displayed in Drop down list for editing that value.

How to bind drop down value in grid view during page load?



Client side
use Eval method in grid view drop down selected value

Server side

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridData();
}
}
void GridData()
{
sqlcmd = new SqlCommand("select *,CASE empstatus when 'Y' then 'Yes' else 'No' END as STATUS from emp", sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}

How to update Grid view drop down value?

protected void GridView1_RowUpdating(object sender,GridViewUpdateEventArgs e)
{

GridViewRow row = GridView1.Rows[e.RowIndex];
string eno;

eno = GridView1.DataKeys[e.RowIndex].Value.ToString();

TextBox empname = (TextBox)row.FindControl("txtempname");
DropDownList status = (DropDownList)row.FindControl("DropDownList1");
string selval;

if (status.SelectedValue == "Yes")
{
selval = "Y";
}
else
{
selval = "N";
}

sqlcon.Open();
sqlcmd = new SqlCommand("update emp set empname='" + empname.Text + "',empstatus='" + selval + "' where eno='" + eno + "'",sqlcon);
sqlcmd.CommandType = CommandType.Text;
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
GridView1.EditIndex = -1;
GridData();
}

Source Code Detail:
Here with I have attached source code to show drop down list in Gridview. Download it and try to update values using that drop down list.
Front End : ASP.NET
Code Behind : C#

Conclusion:
I hope this Article is help to you understand Drop down list in Grid View.


Attachments

  • GridView_DropDownList (42858-221021-GridViewDDL.rar)
  • Comments

    Guest Author: Akin Tamil17 Mar 2012

    This was Very useful about in datagrid in include dropdownlist



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: