how to bind a list to a dropdown list in gridview
- by user3721173
I have a GridView that it contain a Drop-down list.I have a list that wanna to bind this list to drop-down in gridview.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"></asp:Label>
<asp:DropDownList ID="DropDownList3" runat="server" AppendDataBoundItems="True" OnSelectedIndexChanged="DropDownList3_SelectedIndexChanged1" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
and
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList dropdown = (DropDownList)e.Row.FindControl("DropDownList3");
ClassDal obj = new ClassDal();
List<phone> list = obj.GetAll();
dropdown.DataTextField = "phone";
dropdown.DataValueField = "id";
dropdown.DataSource = list.ToList();
dropdown.DataBind();
}
and
namespace sample_table
{
public class ClassDal
{
public List<phone> GetAll()
{
using (PracticeDBEntities1 context = new PracticeDBEntities1())
{
return context.phone.ToList();
}
}
}
}
but i received this exception :Object reference not set to an instance of an object
on the row: dropdown.DataTextField = "phone";