值不会显示在下拉列表中

时间:2013-10-04 08:29:22

标签: c# asp.net c#-4.0

我尝试在gridview查询中的dropdownlist中添加值工作正常,但它显示为此.. enter image description here

gridview html

<asp:BoundField HeaderText="ApproveID" DataField="ApproveID" ></asp:BoundField>
            <asp:TemplateField>
                <ItemTemplate>

                   <asp:Label ID="lblCountry" runat="server" Text='<%# 
             Eval("ApproveID") %>' Visible = "false" />

                    <asp:DropDownList ID="DropDownList4" runat="server"
           class="vpb_dropdown">
                    </asp:DropDownList>
                </ItemTemplate>
            </asp:TemplateField>

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //Find the DropDownList in the Row
            DropDownList ddlCountries = (e.Row.FindControl("DropDownList4") as
                  DropDownList);
            ddlCountries.DataSource = GetData("SELECT ApproveID,ApproveType FROM
           ApproveType");
            ddlCountries.DataTextField = "ApproveType";
            ddlCountries.DataValueField = "ApproveID";
            ddlCountries.DataBind();

            //Add Default Item in the DropDownList
            ddlCountries.Items.Insert(0, new ListItem("Please select"));

            //Select the Country of Customer in DropDownList
            //string country = (e.Row.FindControl("lblCountry") as Label).Text;
            //ddlCountries.Items.FindByValue(country).Selected = true;
        }
    }

值不在dropdownlist中..如何在下拉列表中显示值? 当我调试代码时,它无法显示任何错误

getdata代码

private DataSet GetData(string query)
    {
        string conString = 
       ConfigurationManager.ConnectionStrings["mydms"].ConnectionString;
        SqlCommand cmd = new SqlCommand(query);
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    sda.Fill(ds);
                    return ds;
                }
            }
        }

4 个答案:

答案 0 :(得分:1)

DropDownList1.SelectedValue = "Some Value";

然后您将获得默认值

答案 1 :(得分:0)

获取数据函数返回null或空值,以便在调试时不会出现错误或异常。您的代码工作正常,可以更好地检查数据库中的数据。

答案 2 :(得分:0)

在我参与的项目中,我们返回了DataTable而不是DataSet,它在下拉列表中运行良好。我们有这样的代码:

if( ds.Tables.Count == 1)
    return ds.Tables[0];
else
    return new DataTable();

此外,我会改变数据绑定的方式。在我看来,使用ObjectDataSource是一种更好的方法,因为只有在需要数据时才调用事件,而且你不必像这样进行检查:

if (e.Row.RowType == DataControlRowType.DataRow)

答案 3 :(得分:0)

在您上次发表评论后,您应该检查DataSet是否包含您想要设置为所选的记录:

if (ddlCountries.Items.FindByValue(country) != null) 
{ 
   ddlCountries.Items.FindByValue(country).Selected = true; 
}