简体   繁体   中英

how to set default null value in combobox

dr = new MySqlDataAdapter("select tvl_code, 
   concat_ws(',', tvl_code, citi_name) citiname 
   from code_desc where travel_mode = 'BUS'", conn);
ds1 = new DataSet();
dr.Fill(ds1);
ddlfrom.DataSource = ds1;
ddlfrom.DataTextField = "citiname";
ddlfrom.DataValueField = "tvl_code";
ddlfrom.DataBind();

by this code i am binding my combobox to the database and i am able to populate the combobox from my database.But when i am opening the page the combobox contains one value by default from the database..means the first name from database list from where i am populating is shown on combobox..I want to show blank on the combobox..means it should not show anything printed until i will select some thing from dropdown.How to do that..??

Try this:

ddlfrom.Items.Insert(0, "Select...");

Like this:

dr = new MySqlDataAdapter("select tvl_code, concat_ws(',', tvl_code, citi_name) citiname from code_desc where travel_mode = 'BUS'", conn);
ds1 = new DataSet();
dr.Fill(ds1);
ddlfrom.DataSource = ds1;
ddlfrom.DataTextField = "citiname";
ddlfrom.DataValueField = "tvl_code";
ddlfrom.DataBind();
ddlfrom.Items.Insert(0, "Select...");

You can define your markup like this:

<asp:DropDownList AppendDataBoundItems="true" runat="server"  DataTextField="Text" DataValueField="Id">
    <asp:ListItem Text="Select..." Value="" />   
</asp:DropDownList>

By using the AppendDataBoundItems="true" you can append the bound collection with a static element.

I prefer this approach to adding a "fake" element to your business logic since it makes your logic more reusable if you have other consumers of the query that doesn't need the fake value. Also the default value sounds more like a UI concern than a data concern.

You can append null row before the actual data

dr = new MySqlDataAdapter("select null, null union select tvl_code, concat_ws(',', tvl_code, citi_name) citiname from code_desc where travel_mode = 'BUS'", conn);
...

Since your sample code is in code behind

// do the databinding
dr.Fill(ds1);

DataRow row = ds1.Tables[0].NewRow();
row["tvl_code"] = -1;
row["citiname"] = "Select City";

// insert the row at the top of the table
ds1.Tables[0].Rows.InsertAt(row, 0);

ddlfrom.DataSource = ds1;
ddlfrom.DataTextField = "citiname";
ddlfrom.DataValueField = "tvl_code";
ddlfrom.DataBind();

Hope this helps

您可以在数据绑定代码之后添加以下语句

ddlfrom.Items.Insert(-1,new ListItem("TEXT","-1"));

To add a blank value in your dropdown you can add below code after binding your control:

ddlfrom.Items.Insert(-1,new ListItem("","-1"));

This will add a blank text with -1 value at the -1 index means at top.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM