Sample Code: Using Dropdownlist in Editable DataGrid

This article demonstrates how to use Dropdownlist in Editable DataGrid 

Html Source

<asp:DataGrid id="DataGrid1" AutoGenerateColumns="False" ItemStyle-CssClass="cdb-AltRow" 
AlternatingItemStyle-CssClass="cdb-AltRow2"
 DataKeyField="ProductID" OnUpdateCommand="DataGrid1_Update" OnEditCommand="DataGrid1_Edit"
 OnCancelCommand="DataGrid1_Cancel" runat="server">
<Columns>
 <asp:TemplateColumn HeaderText="Discontinued">
 <ItemTemplate>
  <asp:Label ID="lblDiscontinued" 
   Text='<%#ShowVal(Convert.ToBoolean( 
DataBinder.Eval(Container.DataItem, "Discontinued").ToString()) )%>' 
   Runat="server" />
 </ItemTemplate>
 
 <EditItemTemplate>
  <asp:Label runat="server" id="lblProductID" Visible="False" 
  Text='<%# 
DataBinder.Eval(Container.DataItem, "ProductId") %>'/>
  <asp:Label ID="lblEditDiscontinued" 
  Text='<%#ShowVal(Convert.ToBoolean( 
DataBinder.Eval(Container.DataItem, "Discontinued").ToString() ))%>' 
  Runat="server" />
  <asp:DropDownList id="ddlDiscontinued" 
  DataSource="<%# BindTheDiscontinued() %>"  
  OnPreRender="SetDropDownIndex" 
  DataTextField="Discontinued" 
  DataValueField="Discontinued" 
  runat="server" />
 </EditItemTemplate>
     
 </asp:TemplateColumn>
 
 <asp:EditCommandColumn 
 EditText="Edit" CancelText="Cancel"  UpdateText="Update"
        ItemStyle-Width="100px"
        HeaderText="Commands" />
</Columns>
</asp:DataGrid>
Code Behind
string strDiscontinued;
GetData obj;
string strSql;
string strConn;
DataSet ds;
SqlDataReader dr;
private void Page_Load(object sender, System.EventArgs e)
{
 // Put user code to initialize the page here
 strConn ="server=localhost;uid=sa;pwd=;database=northwind";
 if (!Page.IsPostBack )
 {
    BindGrid();
 }
}

//*******
//To Bind the DataGrid
//******* 
void BindGrid()
{
    obj=new GetData ();
    strSql = "Select productid, discontinued from Products";
    ds=obj.GetDataFromTable (strSql ,strConn);
    DataGrid1.DataSource =ds;
    DataGrid1.DataBind (); 
}

//*******
//To display Yes/No for True/False
//*******
protected string ShowVal(bool blnval)
{
    if (blnval==true)
    {
      return "Yes";
    } 
    else
    {
      return "No";
    }
}

//*******
//Bind the Data to the dropdownlist in the EditTemplate
//*******
protected SqlDataReader BindTheDiscontinued()
{
    obj=new GetData ();
    strSql ="SELECT distinct 'Discontinued' =" ;
    strSql+=" CASE ";
    strSql+=" WHEN Discontinued = 1 Then 'Yes'" ;
    strSql+=" ELSE 'No'" ;
    strSql+=" END " ;
    strSql+=" From Products ";
    dr=obj.GetSingleDataUsingReader (strSql ,strConn);
    return dr;
}

//*******
//Set the Text of the Dropdownlist to the field value in Database
//*******
protected void SetDropDownIndex(Object sender ,System.EventArgs e   )
{
    DropDownList ed ; 
    ed = (DropDownList) sender;
    ed.SelectedIndex = ed.Items.IndexOf(ed.Items.FindByText(strDiscontinued));
}

//*******
//For Edit Update Cancel
//*******
public void DataGrid1_Edit(Object sender, DataGridCommandEventArgs e)
{
    strDiscontinued = ((Label )e.Item.FindControl("lblDiscontinued")).Text;
    DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;    
    BindGrid(); 
}

public void DataGrid1_Update(Object sender, DataGridCommandEventArgs e)
{
    DropDownList TempList ; 
    String TempValue ; 
    TempList = (DropDownList) e.Item.FindControl("ddlDiscontinued");
    TempValue = TempList.SelectedItem.Value;
    //Place update code here
    Response.Write (TempValue);
    DataGrid1.EditItemIndex = -1;
    BindGrid();
}
public void DataGrid1_Cancel(Object sender, DataGridCommandEventArgs e)
{
   DataGrid1.EditItemIndex = -1;
   BindGrid();
}

//
//*******
//Functions used in Class GetData.cs
//*******
SqlConnection mycn;
SqlDataAdapter myda;
SqlCommand mycmd;
DataSet ds;
String strConn;
SqlDataReader myReader;
public DataSet GetDataFromTable(string strSQL ,string strConnString)
{
 try
 {
    strConn=strConnString;
    mycn = new SqlConnection(strConn);
    myda = new SqlDataAdapter (strSQL, mycn);
    ds= new DataSet ();
    myda.Fill (ds,"Table");
    return ds;
 }
 catch(Exception ex)
 {
    throw new Exception (ex.Message.ToString ());
 }
 finally
 {
    mycn.Close ();
 }
}
public SqlDataReader GetSingleDataUsingReader(string strSQL ,string strConnString)
{
 try
 {
    strConn=strConnString;
    mycn = new SqlConnection(strConn);
    mycmd = new SqlCommand  (strSQL, mycn);
    mycn.Open ();
    myReader=mycmd.ExecuteReader(CommandBehavior.CloseConnection ); 
    return myReader;
 }
 catch(Exception ex)
 {
    throw new Exception (ex.Message.ToString ());
 }
 finally
 {
    //mycn.Close ();
 }
}
Published Friday, July 30, 2004 11:43 AM by SushilaSB
Filed under:

Comments

Friday, July 30, 2004 11:47 AM by Varad

# re: Sample Code: Using Dropdownlist in Editable DataGrid

Hi,
The code is not properly visible.
Please format.

Thanks.
Friday, July 30, 2004 11:52 AM by Sushila

# re: Sample Code: Using Dropdownlist in Editable DataGrid

Done!!.
Thanks Varad
Friday, July 30, 2004 11:33 PM by TrackBack

# TrackBack

TrackBack
Friday, August 06, 2004 10:34 AM by Chris

# thanks

thanks a lot

was having a lot of trouble working out how to set the drop down list with the value from the DB when you put the grid into edit mode.

this explains it nicely

thank you
Tuesday, August 10, 2004 11:17 AM by TrackBack

# TrackBack

TrackBack
Wednesday, August 11, 2004 4:30 PM by Priya

# re: Sample Code: Using Dropdownlist in Editable DataGrid

Hi,

Like your examples on C-sharpcorner. Could you explain this a little I am newbie to ASP.Net and C#.

Appreciate it.

Priya
Wednesday, August 11, 2004 5:38 PM by Sushila

# re: Sample Code: Using Dropdownlist in Editable DataGrid

Which part of the code block are you having trouble understanding it??
Thursday, August 12, 2004 8:50 AM by Priya

# re: Sample Code: Using Dropdownlist in Editable DataGrid

The HTML source part where you are adding a dropdownlist in a datagrid.

Thursday, August 12, 2004 12:42 PM by Sushila

# re: Sample Code: Using Dropdownlist in Editable DataGrid

Hello Priya
check the inline comments
<asp:DataGrid id="DataGrid1" AutoGenerateColumns="False"
ItemStyle-CssClass="cdb-AltRow"
AlternatingItemStyle-CssClass="cdb-AltRow2"
DataKeyField="ProductID" OnUpdateCommand="DataGrid1_Update"
OnEditCommand="DataGrid1_Edit"
OnCancelCommand="DataGrid1_Cancel" runat="server">

<Columns>
<asp:TemplateColumn HeaderText="Discontinued">

*****************************************
Step 1) To display the Data in the Datagrid
Initially the Datagrid is populated with the records in the db
The field Discontinued is of data type bit in the db i.e 0/1
To display it as yes/no in the Datagrid a helper function ShowVal(...) is called
****************************************

<ItemTemplate>
<asp:Label ID="lblDiscontinued"
Text='<%#ShowVal(Convert.ToBoolean(
DataBinder.Eval(Container.DataItem, "Discontinued").ToString()) )%>'
Runat="server" />
</ItemTemplate>


****************************************
Step 2) To Edit the Datagrid
When the edit button is clicked it should display field Discontinued as Yes/No
a)To update the record the user should get a choice to Select Yes/No using dropdownlist
b)By default the dropdownlist should be set to the value in the database

aa)So the DataSource property of the dropdownlist is set to BindTheDiscontinued()
bb)and OnPreRender property does the task of setting the value from the db to the dropdownlist
****************************************

<EditItemTemplate>
<asp:Label runat="server" id="lblProductID" Visible="False"
Text='<%#
DataBinder.Eval(Container.DataItem, "ProductId") %>'/>
<asp:Label ID="lblEditDiscontinued"
Text='<%#ShowVal(Convert.ToBoolean(
DataBinder.Eval(Container.DataItem, "Discontinued").ToString() ))%>'
Runat="server" />
<asp:DropDownList id="ddlDiscontinued"
DataSource="<%# BindTheDiscontinued() %>"
OnPreRender="SetDropDownIndex"
DataTextField="Discontinued"
DataValueField="Discontinued"
runat="server" />
</EditItemTemplate>

</asp:TemplateColumn>

<asp:EditCommandColumn
EditText="Edit" CancelText="Cancel" UpdateText="Update"
ItemStyle-Width="100px"
HeaderText="Commands" />
</Columns>
</asp:DataGrid>

Do revert back if you still have queries
Tuesday, August 17, 2004 12:16 PM by Priya

# re: Sample Code: Using Dropdownlist in Editable DataGrid

Thanks for the explanation. I still have one question. What is the GetData ?

GetData obj;

I have tried to look for the class but dint find it. Could you please explain.

Thanks
Tuesday, August 17, 2004 1:06 PM by Sushila

# re: Sample Code: Using Dropdownlist in Editable DataGrid

GetData is the name of class
Below are the functions used in GetData.cs

//*******
//Functions used in Class GetData.cs
//*******
..
public DataSet GetDataFromTable(string strSQL ,string strConnString)
{
......
}
public SqlDataReader GetSingleDataUsingReader(string strSQL ,string strConnString)
{
......
}

HTH
Thursday, November 15, 2007 12:10 AM by kannan.d

# re: Sample Code: Using Dropdownlist in Editable DataGrid

how do this stuff in vb.net pls guide me

Regards

Kannan.D

Monday, December 17, 2007 7:12 PM by rajiv ranjan

# re: Sample Code: Using Dropdownlist in Editable DataGrid

nice effect to help fresher of .net technology.

thanks

Tuesday, December 18, 2007 5:17 AM by Farrukh Butt

# re: Sample Code: Using Dropdownlist in Editable DataGrid

I like the way you have presented the code example....!

thanks

Wednesday, February 20, 2008 1:59 PM by Karthik

# re: Sample Code: Using Dropdownlist in Editable DataGrid

When I used a similar code for my page and tried to run.

At run time at get an error saying "xxx_aspx does not contain a definition for 'SetDropDownIndex'(the function name specified for onprerender)"

DO I need to define it in aspx page?

Saturday, May 31, 2008 2:34 AM by thava

# re: Sample Code: Using Dropdownlist in Editable DataGrid

plese tell how handle in dropdown list in data grid

Wednesday, September 17, 2008 6:57 AM by maria

# re: Sample Code: Using Dropdownlist in Editable DataGrid

do we have any other option to avoid DataBinder.Eval() in a datagird item control?

Tuesday, November 25, 2008 1:58 AM by amit

# re: Sample Code: Using Dropdownlist in Editable DataGrid

how we can bind the different table to dropdownlist in datagrid?

Saturday, February 28, 2009 6:41 AM by Ashvin Johnson

# re: Sample Code: Using Dropdownlist in Editable DataGrid

Hello There,

The code is Fine, But could you please tell me how do I impliment same in datagrid with more columns like I have 4 columns. and want dropdown to come in 3 column.

Please Help

Thanks

Thursday, May 14, 2009 10:28 PM by MATTXtwo

# re: Sample Code: Using Dropdownlist in Editable DataGrid

Thanks it help me

i correct this

DataTextField="Discontinued"

DataValueField="Discontinued"

forn this mass:

<code>

<asp:dropdownlist id="Printer" DataTextField='<%# Container.DataItem("FLPRINTR")%>' DataValueField='<%# Container.DataItem("FLPRID")%>'

DataSource="<%# GetPrinter() %>"

Runat=server Height="32px" Width="337px"></asp:dropdownlist></code>

Wednesday, June 17, 2009 7:16 PM by jane

# re: Sample Code: Using Dropdownlist in Editable DataGrid

do you have this code is vb.net?

Leave a Comment

(required) 
(required) 
(optional)
(required)