格式化动态下拉列表文本(钱)

时间:2013-04-07 16:58:36

标签: c# asp.net drop-down-menu

我正在尝试格式化下拉列表中的文本,但似乎没有任何效果。以下是我的代码:

下拉列表:

<asp:DropDownList runat="server" ID="ddlSalary" CssClass="ddlBox" 
    CausesValidation="true" AutoPostBack="true" 
    onselectedindexchanged="ddlSalary_SelectedIndexChanged" />

代码背后:

if (!IsPostBack)
    {
        ddlSalary.DataSource = Placements.DropDownPopulating("Placement_Salary_From");
        ddlSalary.DataBind();

        ddlSalary.Items.Insert(0, new ListItem("-- Salary --", "0"));

结果:

6.0000
200.0000
1000.0000

但我想:

£6
£200
£1000

我尝试过使用:

ddlSalary.DataTextFormatString = "{0:C}";

修改

填充下拉列表:

public static List<string> DropDownPopulating(string selectedFilter)
    {
        List<string> returnVal = new List<string> { };
        using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["websiteContent"].ConnectionString))
        {
            sqlCon.Open();
            string SQL = "SELECT DISTINCT " + selectedFilter + " FROM Placements";
            using (var CMD = new SqlCommand(SQL, sqlCon))
            {
                using (var DR = CMD.ExecuteReader())
                {
                    while (DR.Read())
                    {
                        returnVal.Add(DR[selectedFilter].ToString());
                    }
                }
            }
            sqlCon.Close();
        }
        return returnVal;
    }

2 个答案:

答案 0 :(得分:3)

如果希望格式化工作,则应使用numeric数据类型:

public static List<T> DropDownPopulating<T>(string selectedFilter)
{
    var returnVal = new List<T>();
    var connectionString = ConfigurationManager.ConnectionStrings["websiteContent"].ConnectionString;
    using (var con = new SqlConnection(connectionString))
    using (var cmd = con.CreateCommand())
    {
        con.Open();
        cmd.CommandText = "SELECT DISTINCT " + selectedFilter + " FROM Placements";
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                // if you are using .NET 4.5
                returnVal.Add(reader.GetFieldValue<T>(reader.GetOrdinal(selectedFilter)));

                // if you are using .NET 4.0 or older:
                // returnVal.Add((T)reader.GetValue(reader.GetOrdinal(selectedFilter)));
            }
        }
    }
    return returnVal;
}

然后:

ddlSalary.DataSource = Placements.DropDownPopulating<decimal>("Placement_Salary_From");
ddlSalary.DataTextFormatString = "{0:C}";
ddlSalary.DataBind();

答案 1 :(得分:0)

使用此查询获取数据.....

  select '$'+Cast((Cast(Price as int))as varchar) from TableName