【问题标题】:Assign the old value of dropdown to the same dropdown after edit button clicked in grid view在网格视图中单击编辑按钮后,将下拉列表的旧值分配给相同的下拉列表
【发布时间】:2015-10-03 18:58:07
【问题描述】:

单击编辑按钮时,我丢失了下拉列表值。我正在尝试获取值并将其分配给下拉列表,但我收到错误消息 -

对象引用未设置为对象的实例。

在我们更改下拉菜单之前它不应该重置。

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

【问题讨论】:

  • 您是否调试过代码并检查您的下拉菜单中是否包含您要查找的项目?您在lblCategory 中获得了什么价值?
  • 我正在获取值,在 lblCategory="Images" 中,但在该对象引用错误之后
  • 我是这样检查的,Label LblCat = (Label)e.Row.FindControl("lblCategory");//images
  • 是的,因为它无法在 ddlCategories 项目集合中找到“图像”。你有没有调试并检查过它是否包含这样的值?
  • 在 ddl 的数据源中。有图片项目。

标签: c# asp.net gridview


【解决方案1】:

您收到该错误是因为,您尝试查找的标签文本可能不存在,或者它可能在下拉集合中包含空格。你可以像这样避免这个错误:-

string category = (e.Row.FindControl("lblCategory") as Label).Text;
ListItem item = ddlCategories.Items.FindByText(category);
if(item != null)
    item.Selected = true;

【讨论】:

  • ListItem items = ddlCategories.Items.FindByValue(category);//categore=Articlesites 但项目为空
  • @krishnamohan - 那么item呢?
  • 在 ListItem 对象中它不存储 findbyvalue(categories)
  • @krishnamohan - 是的,显然它无法在下拉集合中找到该项目。
  • @krishnamohan - 嘿,伙计,您的 DataValueField 是 CategoryId,您正在传递文本字段。您应该使用FindByText 而不是FindByValue。检查我的更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多