Dan
Dan

Reputation: 11183

How to add empty or custom value to a bound combobox?

I am using a System.Windows.Forms.Combobox bound to Category table as search criteria. I need to have a value “All” or empty string that will be selected when user does not want to use this criteria. Since combo is bound, each time it is clicked, value added by combo1.Text = “All” is erased. Obviously, I can’t add “All” category to database. What is the best way to accomplish this?

Upvotes: 3

Views: 25807

Answers (6)

Neeraj
Neeraj

Reputation: 497

  1. If you do not want to add the item "All" into your data source, you can do the following:

Code Snippet

comboBox1.Text = "All";

It sets the text displayed in the comboBox to the value assigned but without changing the items in the comboBox and the bound data source.

  1. You can add "All" to your datasource as well. But you should do it in this way:

Code Snippet

private void button1_Click(object sender, EventArgs e)

{

DataRow dataRow = dataTable.NewRow();

dataRow["ItemId"] = "All";

dataTable.Rows.InsertAt(dataRow, 0);

comboBox1.SelectedIndex = 0;

}

The easiest way would be to insert a row into your ds.Tables[0] that is

  ds = StockDAL.BindItemId();

  DataRow dataRow = ds.Tables[0].NewRow();

  dataRow["ItemId"] = "All";

  ds.Tables[0].Rows.InsertAt(dataRow, 0);

  comboBox1.DataSource = ds.Tables[0];
  comboBox1.DisplayMember = "ItemId";
  comboBox1.ValueMember = "ItemId";
  comboBox1.selectedIndex=0;

hope this solve ur issue..

Upvotes: 6

Jidheesh Rajan
Jidheesh Rajan

Reputation: 4845

you can try this

ComboBox1.Items.Insert(0,"All");

while inserting to table you just check the selected index of the ComboBox1 ie,

if(ComboBox1.SelectedIndex>0)
{
//do the insert code here
}
else
{
//dont do anything
}

this will work fine...

Upvotes: 0

ProfK
ProfK

Reputation: 51063

I always 'manually' add an item to the data source before data binding. This avoids having 'artificial' data in your data source's query, so if you use the query for something other than a dropdown, you only get real data.

Upvotes: 0

Kostas Konstantinidis
Kostas Konstantinidis

Reputation: 13707

You would have to add another item:

ComboBox1.Items.Insert(0,"All");

Upvotes: 1

Asim Sajjad
Asim Sajjad

Reputation: 2534

  1. If you are using sql server then you can add extra value to the select command for the All option
  2. Or you can add All option by using comboBox1.Items.Insert(0,"All") to add new item as zero index. after binding the control

Hope that will help.

Upvotes: 0

MartW
MartW

Reputation: 12538

Either manually add the All entry to the bound dataset after the other values have been loaded, or unbind the combo and instead iterate through the data to populate it. It's just a search combo, so you don't really need all the benefits of binding.

Upvotes: 1

Related Questions