Format DropDownList.TextValue

后端 未结 7 1543
失恋的感觉
失恋的感觉 2020-12-15 10:54

My stored procedure is like this

SELECT Id, StudentName
FROM xyz

I have a drop down list in asp.net, which I am loading as :



        
相关标签:
7条回答
  • 2020-12-15 11:35

    it's very simple, only you have concat fields in the query

    SELECT Id ,Id || ' ' || StudentName ""TEXT"", 
    FROM xyz
    

    then you build a drop down list

    ddlA.DataSource = // Some source
    ddlA.DataTextField = "TEXT";
    ddlA.DataValueField = "Id";
    ddlA.DataBind();
    ddlA.Items.Insert(0, new ListItem(" Select one", "0"));
    
    0 讨论(0)
  • 2020-12-15 11:36

    If the DataSource is a DataTable, you can add an "expression" (calculated column) to the table. The expression for the new column would look like this:

    newcolumn.Expression = "Id + ' - ' + StudentName";
    
    0 讨论(0)
  • 2020-12-15 11:42

    If you have list of class to fill drop down list, this is probably best to do;

    List<FOO> foo = new List<FOO>();
    
    ddlFoo.DataSource = foo.Select(x => 
        new ListItem { Text = x.Text1 + " - " + x.Text2, Value = x.Id.ToString() });
    ddlFoo.DataBind(); 
    
    0 讨论(0)
  • 2020-12-15 11:45
    DropDownList1.DataTextFormatString = "{0} - {1}";
    DropDownList1.DataTextField = "Id,StudentName";
    

    It seems that it's not achievable automatically, e.g. see this MS Connect ticket.


    Thus do that programmatically:

    foreach (var row in table.Rows)
    {
        row.Field<string>("text") = String.Format(..);
    }
    

    or

    foreach (var item in data)
    {
        new ListItem { Text = String.Format(..); }; 
    }
    
    0 讨论(0)
  • 2020-12-15 11:46

    You can use LINQ to make a new datasource containing a displayfield which is formatted, the way you want it to be, like:

    var datasource = from x in products
                     select new {
                         x.Id,
                         x.Code,
                         x.Description,
                         DisplayField = String.Format("{0} ({1})", x.Code, x.Description)
                     };
    
    comboBox.DataSource = datasource;
    comboBox.DataValueField = "Id";
    comboBox.DataTextField = "DisplayField";
    comboBox.DataBind();
    
    0 讨论(0)
  • 2020-12-15 12:00

    You can achieve it by following code

    dsStudent.Tables[0].Columns.Add("IdWithStudenName",typeof(string),"Id + ' - ' + StudenName");
    DropDownList1.DataSource = dsStudent;
    DropDownList1.DataTextField = "IdWithStudenName";
    DropDownList1.DataBind();
    DropDownList1.Items.Insert(0, new ListItem("Please select"));
    

    For more understanding refer here.

    0 讨论(0)
提交回复
热议问题