how to bind a list to a dropdown list in gridview

Posted by user3721173 on Stack Overflow See other posts from Stack Overflow or by user3721173
Published on 2014-06-09T09:15:22Z Indexed on 2014/06/09 9:24 UTC
Read the original article Hit count: 197

Filed under:

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";

© Stack Overflow or respective owner

Related posts about ASP.NET