How do I set a DataSource to a DropDownList?

10,310

Solution 1

I solved my problem like this:

DataSet ds = SomeMethodToFillTheDataSet()

foreach(DataRow row in ds.tables[0].Rows)
{
  ListItem item = new ListItem();
  item.text = "fieldName";  e.g  Name
  item.value = "FieldName"; e.g  ID
  DropDOwnList.Items.Add(item);
}

Solution 2

Kindly follow this code to assign a Datasource to Dropdown

    DataTable dt = ds.tables[0];
    DropdownId.DataSource = dt;
    DropdownId.DataTextField = "Text Column";
    DropdownId.DataValueField = "Value Column";
    DropdownId.DataBind();
    DropdownId.Items.Insert(0, new ListItem("-- Select --", "0"));

Solution 3

ddlList.DataTextField = "Text"; If this line gives you an error, then make sure that in your datasource or dataset you have same column name. if its textname, then you should assign ddlList.DataTextField = "textname";

Just a thought!

Solution 4

Bind Row data bound event in the markup, as below:

<asp:GridView ID="grvGrid" runat="server" OnRowDataBound="grvGrid_RowBound">
   <Columns>
       <asp:TemplateField ItemStyle-HorizontalAlign="Left" ItemStyle-VerticalAlign="Top"  ItemStyle-Width="7%">
                <ItemTemplate>
                   <asp:DropDownList ID="ddlList" runat="server"/>
                </ItemTemplate>
       </asp:TemplateField>
    </Columns>
 </asp:GridView?

In the code behind:

 protected void grvGrid_RowBound(object sender, GridViewRowEventArgs e)
 {
     DropDownList ddlList= (DropDownList )e.Row.FindControl("ddlList");
     ddlList.DataSource = _dSource;
     ddlList.DataTextField = "text";
     ddlList.DataValueField = "value";
     ddlList.DataBind();


  }

OR

If you dropdown is going to have the same options for each row, you dont need to bind it during RowDataBound Event.. You can add item s to the dropdown list in markup as below:

 <asp:DropDownList id="ddlList"runat="server">

              <asp:ListItem Selected="True" Value="White"> White </asp:ListItem>
              <asp:ListItem Value="Silver"> Silver </asp:ListItem>
              <asp:ListItem Value="DarkGray"> Dark Gray </asp:ListItem>
              <asp:ListItem Value="Khaki"> Khaki </asp:ListItem>
              <asp:ListItem Value="DarkKhaki"> Dark Khaki </asp:ListItem>

           </asp:DropDownList>
Share:
10,310
Ghaleon
Author by

Ghaleon

I just want to learn the most I can and become the best programmer !

Updated on August 21, 2022

Comments

  • Ghaleon
    Ghaleon over 1 year

    I read some of the others threads and didnt work out for me =\ I have a GridView with a DropDownList in one field. I'd like to know How may I set a DataSource for that ? I'm not using Templates neither ItemTemplate or EditItemTemplate I don't know how it work exactly , so i'm not using it yet.

    So far I have only created the GridView And filled the fields with data but I don't know how to do the same for the DropDownList. SOmething is missing I guess, it is giving me an error ("The Reference of the Object was not set as an instance of an object")

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {                                
                DropDownList Drop_Prioridades = (DropDownList)e.Row.FindControl("Drop_Prioridades");
                Drop_Prioridades.DataTextField = "BAIXA";
                Drop_Prioridades.DataValueField = "1";
                Drop_Prioridades.DataTextField = "MEDIA";
                Drop_Prioridades.DataValueField = "2";
                Drop_Prioridades.DataTextField = "ALTA";
                Drop_Prioridades.DataValueField = "3";
                Drop_Prioridades.DataBind();
            }
    

    I Also tried this / Same error =\

    DataSet ds = func.LoadPriority();
    
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    ListItem item = new ListItem();
                    item.Text = row["prioridade"].ToString();
                    item.Value = row["id"].ToString();
                    DropDownList ddlPrioridades = (DropDownList)e.Row.FindControl("Drop_Prioridades");
                    ddlPrioridades.Items.Add(item);
                }
    

    And Tried this too...

    HTML:

    <columns>                    
    
         <asp:TemplateField HeaderText="PRIORIDADE" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="100px">
                <ItemTemplate>
                    <asp:DropDownList ID="Drop_Prioridades" Width="120px" runat="server" ></asp:DropDownList> 
    </ItemTemplate>                    
    </asp:TemplateField>
    

    Code Behind:

     DataSet ds = func.CarregaPrioridade();
                DropDownList ddlist = (DropDownList)e.Row.FindControl("Drop_Prioridades");
                ddlist.DataSource = ds;
                ddlist.DataTextField = "prioridade";
                ddlist.DataValueField = "id";
    
    • Ofiris
      Ofiris over 11 years
      Better show some code. What have you tried ?
    • MethodMan
      MethodMan over 11 years
      try doing a search here tons of .NET examples
    • Ghaleon
      Ghaleon over 11 years
      I edited the post . That's All I got so far =\ I already searched there and I still doing it... Thanks
    • MethodMan
      MethodMan over 11 years
      are you sure that you did a search..? msdn.microsoft.com/en-us/library/…
    • ajp
      ajp over 11 years
      DataTextField and DataValueField should be used when you use a data source..
    • ajp
      ajp over 11 years
      Or you can add ListItem to Dopw_Priordades.Items property
    • Ghaleon
      Ghaleon over 11 years
      I did in the 2nd example... But when I use this ItemTemplate thing the ID does not appear in my code behind . . . And as I showed in the Second example, i got an error trying this way =\\ Could you help me ? Thank you
  • Ghaleon
    Ghaleon over 11 years
    May I do a normal Query that Returns a DataSet and make a foreach on the dataset and fill the dropdownlist ? with this method you showed me ?
  • ajp
    ajp over 11 years
    @Ghaleon The method 'grvGrid_RowBound' is called for each row of the grid. So your dataset _dsource can be a DataTable or DataView, if I understand you correctly.. and you can read msdn.microsoft.com/en-us/library/… for more info
  • StingyJack
    StingyJack over 11 years
    No @Ghaleon, you will have to then use ddlList.Items.Add() to add the items in that case.
  • Ghaleon
    Ghaleon over 11 years
    Really Thank you ajp ! I'll try and as soon as possible i'll leave here a feedback.
  • Ghaleon
    Ghaleon over 11 years
    I guess @StingyJack I'm getting an error : "The Reference of the object wasnt set as an instance of an object" ;s In the First lIne: ddlList.DataTextField = "Text";
  • Ghaleon
    Ghaleon over 11 years
    I checked that too. Thought the same you did ! But its alright, that method returns me two columns, named : prioridade and id but still the error =\\
  • Ghaleon
    Ghaleon over 11 years
    But the error now is in the line that I set the DataSource : ddlist.DataSource = ds;
  • rach
    rach over 11 years
    Do you have any values in ds?? use breakpoint and check it what it actually returns. Do you have SQLDATASOURCE in your aspx page?
  • Ghaleon
    Ghaleon over 11 years
    Just Checked... The ds that returns is NOT null =\\ I don't know what else may I do ;s Yes I do, But the SQLDATASOURCE is used only to fill the BoundFields... Why ?
  • Ghaleon
    Ghaleon over 11 years
    Tried this but still the same, look: <asp:DropDownList ID="Drop_Prioridades" Width="120px" runat="server" DataTextField="prioridade"></asp:DropDownList>
  • rach
    rach over 11 years
    <asp:SqlDataSource ID="SqlDataSourceDDLList" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionstringName %>" SelectCommandType="StoredProcedure" SelectCommand="SP_Name"></asp:SqlDataSource> and in your itemtemplate<asp:DropDownList ID="ddlList" runat="server" DataSourceID="SqlDataSourceDDLList" DataTextField="prioridade" DataValueField="id"> try this and see if it works.
  • rach
    rach over 11 years
    Are you using any gridview Event to bind ddl?? ddlist.DataSource = ds; ddlist.DataTextField = "prioridade"; ddlist.DataValueField = "id"; after that bind data to ddl like ddlist.databind();
  • rach
    rach over 11 years
    Please refer following link hope that helps you.aspsnippets.com/Articles/…
  • Ghaleon
    Ghaleon over 11 years
    I did as the link shows. I populate a DataSet with data, and set it as the DataSource of the DropDownList but i get that error on this line. I don't know what else could it be =\
  • rach
    rach over 11 years
    in RowDataBound event (cs code) check if the row is DataRow if yes then bind the dropdown list. I really didnt find any mistake in your code. I doubt something wrong in database. whatever your query is please run it in SQL itself.
  • Ghaleon
    Ghaleon over 11 years
    I Did. . . But when I bound the Data to the DropDownList i get that error =\
  • rach
    rach over 11 years
    Try this: ddlist.DataSource = func.CarregaPrioridade(); now if its giving you an error, First check its really finding your dropdown list...on this line DropDownList ddlList= (DropDownList )e.Row.FindControl("ddlList"); I really doubt about your query result. Second Option is that Instead of returning ds after executing your function. return it in list and then try above stmt with binding ddl with function name directly.