Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Bind (Set) DropDownList Selected Value in GridView EditItemTemplate in ASP.Net

Jun 7, 2015
Introduction

Here I will explain how to populate or bind dropdownlist selected value in
gridview edititemtemplate in asp.net using c#, vb.net with example or set selected value of dropdownlist in gridview from database in asp.net using c#, vb.net with example.


Before implement this example first design one table productinfo in your database as shown below

Column Name
Data Type
Allow Nulls
productid
Int(IDENTITY=TRUE)
Yes
productname
varchar(50)
Yes
price
varchar(50)
Yes
Once table created in database enter some dummy data to test application now open your aspx page and write the code like as shown below


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Populate Dropdownlist Selected value in Gridview Edititemtemplate in Asp.net</title>
<style type="text/css">
.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
.headerstyle
{
color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;background-color: #df5015;padding:0.5em 0.5em 0.5em 0.5em;text-align:center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="GridviewDiv">
<asp:GridView runat="server" ID="gvDetails" AllowPaging="true" PageSize="10" AutoGenerateColumns="false" DataKeyNames="productid" OnPageIndexChanging="gvDetails_PageIndexChanging" OnRowCancelingEdit="gvDetails_RowCancelingEdit"
OnRowEditing="gvDetails_RowEditing" OnRowUpdating="gvDetails_RowUpdating" OnRowDataBound="gvDetails_RowDataBound" >
<HeaderStyle CssClass="headerstyle" />
<Columns>
<asp:BoundField DataField="productid" HeaderText="Product Id" ReadOnly="true" />
<asp:BoundField DataField="productname" HeaderText="Product Name" />
<asp:TemplateField HeaderText = "Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Eval("price")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:HiddenField ID="hdnprice" runat="server" Value='<%#Eval("price") %>' />
<asp:DropDownList ID = "ddlprice" runat = "server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
After completion of aspx page add following namespaces in codebehind

C# Code


using System;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;

After completion of adding namespaces you need to write the code like as shown below


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
protected void BindGridview()
{
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection("Data Source=Suresh;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from productinfo", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
}
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvDetails.EditIndex == e.Row.RowIndex)
{
using (SqlConnection con = new SqlConnection("Data Source=Suresh;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
DropDownList ddlprod = (DropDownList)e.Row.FindControl("ddlprice");
HiddenField hdnval = (HiddenField)e.Row.FindControl("hdnprice");
SqlCommand cmd = new SqlCommand("select * from productinfo", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlprod.DataSource = ds;
ddlprod.DataTextField = "price";
ddlprod.DataValueField = "price";
ddlprod.DataBind();
ddlprod.Items.Insert(0, new ListItem("--Select--", "0"));
ddlprod.Items.FindByValue(hdnval.Value).Selected = true;
}
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindGridview();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindGridview();
}
protected void gvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvDetails.PageIndex = e.NewPageIndex;
BindGridview();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=Suresh;Integrated Security=true;Initial Catalog=MySampleDB"))
{
int productid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
DropDownList ddlprice = (DropDownList)gvDetails.Rows[e.RowIndex].FindControl("ddlprice");
con.Open();
SqlCommand cmd = new SqlCommand("update productinfo set price='" + ddlprice.SelectedValue +"' where productid=" + productid, con);
cmd.ExecuteNonQuery();
lblresult.ForeColor = Color.Green;
lblresult.Text = " Details Updated successfully";
gvDetails.EditIndex = -1;
BindGridview();
}
}
VB.NET Code


Imports System.Web.UI.WebControls
Imports System.Data.SqlClient
Imports System.Data
Imports System.Drawing
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridview()
End If
End Sub
Protected Sub BindGridview()
Dim ds As New DataSet()
Using con As New SqlConnection("Data Source=Suresh;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("select * from productinfo", con)
Dim da As New SqlDataAdapter(cmd)
da.Fill(ds)
con.Close()
gvDetails.DataSource = ds
gvDetails.DataBind()
End Using
End Sub
Protected Sub gvDetails_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow AndAlso gvDetails.EditIndex = e.Row.RowIndex Then
Using con As New SqlConnection("Data Source=Suresh;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim ddlprod As DropDownList = DirectCast(e.Row.FindControl("ddlprice"), DropDownList)
Dim hdnval As HiddenField = DirectCast(e.Row.FindControl("hdnprice"), HiddenField)
Dim cmd As New SqlCommand("select * from productinfo", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
con.Close()
ddlprod.DataSource = ds
ddlprod.DataTextField = "price"
ddlprod.DataValueField = "price"
ddlprod.DataBind()
ddlprod.Items.Insert(0, New ListItem("--Select--", "0"))
ddlprod.Items.FindByValue(hdnval.Value).Selected = True
End Using
End If
End Sub
Protected Sub gvDetails_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
gvDetails.EditIndex = e.NewEditIndex
BindGridview()
End Sub
Protected Sub gvDetails_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
gvDetails.EditIndex = -1
BindGridview()
End Sub
Protected Sub gvDetails_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
gvDetails.PageIndex = e.NewPageIndex
BindGridview()
End Sub
Protected Sub gvDetails_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Using con As New SqlConnection("Data Source=Suresh;Integrated Security=true;Initial Catalog=MySampleDB")
Dim productid As Integer = Convert.ToInt32(gvDetails.DataKeys(e.RowIndex).Value.ToString())
Dim ddlprice As DropDownList = DirectCast(gvDetails.Rows(e.RowIndex).FindControl("ddlprice"), DropDownList)
con.Open()
Dim cmd As New SqlCommand("update productinfo set price='" & ddlprice.SelectedValue & "' where productid=" & productid, con)
cmd.ExecuteNonQuery()
lblresult.ForeColor = Color.Green
lblresult.Text = " Details Updated successfully"
gvDetails.EditIndex = -1
BindGridview()
End Using
End Sub
End Class
Demo

Bind (Set) DropDownList Selected Value in GridView EditItemTemplate in ASP.Net

Download Sample Code Attached

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

10 comments :

Unknown said...

Hi.
I tried doing this way but not able to get the desired results. Can you pls help me.

Unknown said...

give me source code of this program

Unknown said...

i also tried this but, not getting desired result

Anonymous said...

i am getting error of : Object reference not set to an instance of an object.

Anonymous said...

Me Too getting same error at line : ddlprod.DataSource = ds;
on .cs file please help as soon as possible.
thanks.

vibhusha said...

Nice articles.It Save my time.Thank you Suresh Dasari.

Anonymous said...

if (ds.Tables[0].Rows.Count > 0)
{
grd_TermsAndConditions_AddEdit.DataSource = ds;
grd_TermsAndConditions_AddEdit.DataBind();

DataTable dt_mstDetail = new DataTable();
dt_mstDetail = ds.Tables[0].Copy();
for (int i = 0; i < dt_mstDetail.Rows.Count; i++)
{
foreach (GridViewRow rw in grd_TermsAndConditions_AddEdit.Rows)
{
Label lbl_Pk_TermID = (Label)rw.FindControl("lbl_Pk_TermID");
Label lbl_Module = (Label)rw.FindControl("lbl_Module");
Label lbl_Term_Title = (Label)rw.FindControl("lbl_Term_Title");
Label lbl_Term_Description = (Label)rw.FindControl("lbl_Term_Description");
Label lbl_Days = (Label)rw.FindControl("lbl_Days");

DropDownList drp_ApplicableOn = (DropDownList)rw.FindControl("drp_ApplicableOn");
//CheckBox chk_Select = (CheckBox)rw.FindControl("chk_Select");

if (dt_mstDetail.Rows[i]["pk_TermID"].ToString() == lbl_Pk_TermID.Text.ToString())
{
lbl_Term_Title.Text = dt_mstDetail.Rows[i]["Term_Title"].ToString();
lbl_Term_Description.Text = dt_mstDetail.Rows[i]["Term_Description"].ToString();
lbl_Days.Text = dt_mstDetail.Rows[i]["Days_Description"].ToString();
//Binding Dropdown
drp_ApplicableOn.SelectedValue = dt_mstDetail.Rows[i]["ApplicableOnID"].ToString();
lbl_Module.Text = dt_mstDetail.Rows[i]["ModuleName"].ToString();

//chk_Select.Checked = true;
}
}
}

Lahiru Fernando said...

tried the same way but not working for me either. when i change the selected value in the dropdown and click on the update button, it still gets the old value. How can i get the new value?

Unknown said...

how to do this in windoew form?

Unknown said...

window form

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.