开发者

SelectedValue of DropDownlList

开发者 https://www.devze.com 2023-01-05 20:47 出处:网络
I have a gridview that has dropdownlist in edit section, I want to bind the selectedvalue from database when editing. In designer section there is no SelectedValue attribute, it gives runtime error. W

I have a gridview that has dropdownlist in edit section, I want to bind the selectedvalue from database when editing. In designer section there is no SelectedValue attribute, it gives runtime error. What to do any help?? Is there any way to handle it from code-behind?

<asp:TemplateField HeaderText="Company">
                <EditItemTemplate>
                    <asp:DropDownList ID="DDLCompany" runat="server" DataValueField="cname" DataTextField="cname" SelectedValue = '<%# Bind("cname") %>'  >
                    </asp:DropDownList>
                </EditItemTemplate>
                <ItemTemplate>
                <asp:Label ID="CompanyLabel" runat="server" Text='<%# Bind("cname") %>'></asp:Label>
                </ItemTemplate>   
             </asp:TemplateField>

protected void GridView1_RowDataBound(object s开发者_如何转开发ender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList DDLCompany = (DropDownList)e.Row.FindControl("DDLCompany");
            DropDownList DDLPrinter = (DropDownList)e.Row.FindControl("DDLPrinter");

            if (DDLCompany != null)
            {
                DDLCompany.DataSource = userobj.FetchCompanyList();
                DDLCompany.DataBind();
                DDLCompany.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[0].ToString();                
            }

            if (DDLPrinter != null)
            {
                DDLPrinter.DataSource = userobj.FetchPrinterList();
                DDLPrinter.DataBind();
                DDLPrinter.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[0].ToString();
            }
        }
    } 


  • In Codebehind you have to check for e.Row.RowType== DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit in RowDataBound before you find your Dropdwonlist. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.dataitem.aspx
  • On aspx you can set the seletcedvalue in the following way: http://msdn.microsoft.com/en-us/library/ms178294.aspx
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号