点击编辑按钮时,我丢失了下拉列表值。我正在尝试获取值并将其分配给下拉列表,但我收到错误说 -
对象引用未设置为对象的实例。
在我们更改下拉列表之前不应重置。
aspx代码
<asp:TemplateField HeaderText="Cat Id">
<ItemTemplate>
<asp:Label ID="lblCatId" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,
"Categoryname") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" Width="20px" />
<HeaderStyle HorizontalAlign="Left" Width="20px" />
<FooterStyle Width="20px" />
<EditItemTemplate>
<asp:Label ID="lblCategory" runat="server" Text='<%#Eval("Categoryname")%>'
Visible="true"></asp:Label>
<asp:DropDownList ID="DDl_CateName" runat="server" onkeydown="return (event.keyCode!
=13);" >
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDl_AddCateName" runat="server" onkeydown="return
(event.keyCode!=13);" >
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
aspx.cs代码
if (e.Row.RowType == DataControlRowType.DataRow && gvDaySubmission.EditIndex == e.Row.RowIndex)
{
DropDownList ddlCategories = (DropDownList)e.Row.FindControl("DDl_CateName");
string query = "select * from tbl_Category";
SqlCommand cmd = new SqlCommand(query);
ddlCategories.DataSource = GetData(cmd);
ddlCategories.DataTextField = "Categoryname";
ddlCategories.DataValueField = "CategoryId";
ddlCategories.DataBind();
ddlCategories.Items.FindByValue((e.Row.FindControl("lblCategory") as Label).Text).Selected = true;//getting error in this line
答案 0 :(得分:1)
您收到该错误的原因是,您尝试查找的标签文本可能不存在,或者可能在下拉列集中包含空格。您可以像这样避免此错误: -
string category = (e.Row.FindControl("lblCategory") as Label).Text;
ListItem item = ddlCategories.Items.FindByText(category);
if(item != null)
item.Selected = true;