我有一个GridView,它包含一个下拉列表。我有一个列表,希望将此列表绑定到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>
和
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();
}
和
namespace sample_table
{
public class ClassDal
{
public List<phone> GetAll()
{
using (PracticeDBEntities1 context = new PracticeDBEntities1())
{
return context.phone.ToList();
}
}
}
}
但是我收到了这个例外:对象引用未设置为对象的实例 在行上:dropdown.DataTextField =&#34; phone&#34 ;;
答案 0 :(得分:1)
在RowType
事件处理程序中加入RowDataBound
检查。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
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(); // <- why are you doing list.ToList()?
dropdown.DataBind();
}
}
答案 1 :(得分:0)
您的问题将得到解决,只需将数据源置于文本字段之前,如下所示
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.DataSource = list.ToList();
dropdown.DataTextField = "phone";
dropdown.DataValueField = "id";
dropdown.DataBind();
}