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 ();
 }
}

21 Comments

  • Hi,

    The code is not properly visible.

    Please format.



    Thanks.

  • Done!!.

    Thanks Varad

  • 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

  • Hi,



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



    Appreciate it.



    Priya

  • Which part of the code block are you having trouble understanding it??

  • Hello Priya

    check the inline comments

    &lt;asp:DataGrid id=&quot;DataGrid1&quot; AutoGenerateColumns=&quot;False&quot;

    ItemStyle-CssClass=&quot;cdb-AltRow&quot;

    AlternatingItemStyle-CssClass=&quot;cdb-AltRow2&quot;

    DataKeyField=&quot;ProductID&quot; OnUpdateCommand=&quot;DataGrid1_Update&quot;

    OnEditCommand=&quot;DataGrid1_Edit&quot;

    OnCancelCommand=&quot;DataGrid1_Cancel&quot; runat=&quot;server&quot;&gt;



    &lt;Columns&gt;

    &lt;asp:TemplateColumn HeaderText=&quot;Discontinued&quot;&gt;



    *****************************************

    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

    ****************************************



    &lt;ItemTemplate&gt;

    &lt;asp:Label ID=&quot;lblDiscontinued&quot;

    Text='&lt;%#ShowVal(Convert.ToBoolean(

    DataBinder.Eval(Container.DataItem, &quot;Discontinued&quot;).ToString()) )%&gt;'

    Runat=&quot;server&quot; /&gt;

    &lt;/ItemTemplate&gt;





    ****************************************

    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

    ****************************************



    &lt;EditItemTemplate&gt;

    &lt;asp:Label runat=&quot;server&quot; id=&quot;lblProductID&quot; Visible=&quot;False&quot;

    Text='&lt;%#

    DataBinder.Eval(Container.DataItem, &quot;ProductId&quot;) %&gt;'/&gt;

    &lt;asp:Label ID=&quot;lblEditDiscontinued&quot;

    Text='&lt;%#ShowVal(Convert.ToBoolean(

    DataBinder.Eval(Container.DataItem, &quot;Discontinued&quot;).ToString() ))%&gt;'

    Runat=&quot;server&quot; /&gt;

    &lt;asp:DropDownList id=&quot;ddlDiscontinued&quot;

    DataSource=&quot;&lt;%# BindTheDiscontinued() %&gt;&quot;

    OnPreRender=&quot;SetDropDownIndex&quot;

    DataTextField=&quot;Discontinued&quot;

    DataValueField=&quot;Discontinued&quot;

    runat=&quot;server&quot; /&gt;

    &lt;/EditItemTemplate&gt;



    &lt;/asp:TemplateColumn&gt;



    &lt;asp:EditCommandColumn

    EditText=&quot;Edit&quot; CancelText=&quot;Cancel&quot; UpdateText=&quot;Update&quot;

    ItemStyle-Width=&quot;100px&quot;

    HeaderText=&quot;Commands&quot; /&gt;

    &lt;/Columns&gt;

    &lt;/asp:DataGrid&gt;



    Do revert back if you still have queries

  • 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

  • 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

  • how do this stuff in vb.net pls guide me

    Regards
    Kannan.D

  • nice effect to help fresher of .net technology.
    thanks

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

  • 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?

  • plese tell how handle in dropdown list in data grid

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

  • how we can bind the different table to dropdownlist in 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

  • Thanks it help me
    i correct this
    DataTextField="Discontinued"
    DataValueField="Discontinued"
    forn this mass:

    <asp:dropdownlist id="Printer" DataTextField='' DataValueField=''
    DataSource=""
    Runat=server Height="32px" Width="337px">

  • do you have this code is vb.net?

  • sushila, u did a great job..thanks a lot...

  • Meiner Meinung nach ist es so, falls alle webmasters und Blogger
    so einen perfekten Inhalt wie du in das Blog stellen würden, gaebe es so
    viel mehr nuetzliches zu finden.

  • Great beat ! I would like to apprentice while you amend your
    web site, how can i subscribe for a blog website?
    The account aided me a applicable deal. I had been tiny bit acquainted of this your broadcast provided bright clear idea

Comments have been disabled for this content.