[c#] How to set combobox default value?

In windows form, It has a ComboBox, Which have data binded by the DataSource.

When going to set the text property for a ComboBox.

Selected ComboBox -> Property -> Text : "--Select--".

Design page shows the given text. But when run the application the given text disappeard and the initial index value of a comboBox item appeared, Which is from the DataSource.

So i gave the ComboBox text in the Form load. I mean in the Constructor

public myform()
{
     InitializeComponent();
     ComboBox.Text="--Select--";
}

link revised and more. But ..

Setting default item in combo box

https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.text(v=vs.110).aspx

Searched lot of question in SO depends to ComboBox. But those never solve my case

Edited

enter image description here

In that combobox, Click the right top corner , From that i choosed data for my combobox by using Datasouce. I didn't write any code for add items into combobox.

This question is related to c# winforms combobox

The answer is


You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

Questions with c# tag:

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array How can I add raw data body to an axios request? Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Convert string to boolean in C# Entity Framework Core: A second operation started on this context before a previous operation completed ASP.NET Core - Swashbuckle not creating swagger.json file Is ConfigurationManager.AppSettings available in .NET Core 2.0? No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization Getting value from appsettings.json in .net core .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Automatically set appsettings.json for dev and release environments in asp.net core? How to use log4net in Asp.net core 2.0 Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 Update .NET web service to use TLS 1.2 Using app.config in .Net Core How to send json data in POST request using C# ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response How to enable CORS in ASP.net Core WebAPI VS 2017 Metadata file '.dll could not be found How to set combobox default value? How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac ALTER TABLE DROP COLUMN failed because one or more objects access this column Error: the entity type requires a primary key How to POST using HTTPclient content type = application/x-www-form-urlencoded CORS: credentials mode is 'include' Visual Studio 2017: Display method references Where is NuGet.Config file located in Visual Studio project? Unity Scripts edited in Visual studio don't provide autocomplete How to create roles in ASP.NET Core and assign them to users? Return file in ASP.Net Core Web API ASP.NET Core return JSON with status code auto create database in Entity Framework Core Class Diagrams in VS 2017 How to read/write files in .Net Core? How to read values from the querystring with ASP.NET Core? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? ASP.NET Core Get Json Array using IConfiguration Entity Framework Core add unique constraint code-first No templates in Visual Studio 2017 ps1 cannot be loaded because running scripts is disabled on this system

Questions with winforms tag:

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager "Use the new keyword if hiding was intended" warning Click a button programmatically how to bind datatable to datagridview in c# Show message box in case of exception DataGridView AutoFit and Fill How do I write a backslash (\) in a string? "Input string was not in a correct format." Populate a datagridview with sql query results Close Form Button Event How to set the timeout for a TcpClient? Open File Dialog, One Filter for Multiple Excel Extensions? Fit Image into PictureBox Popup window in winform c# Setting focus to a textbox control DataGridView changing cell background color How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null) Get current folder path Reset all the items in a form Get single listView SelectedItem opening a window form from another form programmatically Playing a MP3 file in a WinForm application Using FileSystemWatcher to monitor a directory How to create many labels and textboxes dynamically depending on the value of an integer variable? Getting value of selected item in list box as string maxReceivedMessageSize and maxBufferSize in app.config Update label from another thread Invoke(Delegate) Make TextBox uneditable Close a MessageBox after several seconds How to close form Change the row color in DataGridView based on the quantity of a cell value Get the current date and time Check/Uncheck a checkbox on datagridview Adding new line of data to TextBox How to get full file path from file name? Search for value in DataGridView in a column How to properly exit a C# application? Saving image to file How to create exe of a console application How to get the selected row values of DevExpress XtraGrid?

Questions with combobox tag:

How to set combobox default value? PHP code to get selected text of a combo box How to add items to a combobox in a form in excel VBA? How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null) Get Selected value of a Combobox jQuery "on create" event for dynamically-created elements How to get the selected item of a combo box to a string variable in c# HTML combo box with option to type an entry twitter bootstrap autocomplete dropdown / combobox with Knockoutjs C# winforms combobox dynamic autocomplete ComboBox.SelectedText doesn't give me the SelectedText JavaScript code for getting the selected value from a combo box Clear ComboBox selected text How do I clear a combobox? Getting selected value of a combobox How to set selected value from Combobox? Get the value for a listbox item by index Binding Combobox Using Dictionary as the Datasource how to check if item is selected from a comboBox in C# Selecting default item from Combobox C# How to pass parameters on onChange of html select Get selected value from combo box in C# WPF QComboBox - set selected item based on the item's data ComboBox: Adding Text and Value to an Item (no Binding Source) How do I set combobox read-only or user cannot write in a combo box only can select the given items? How can I create an editable combo box in HTML/Javascript? How can I show a combobox in Android? Removing All Items From A ComboBox? ComboBox- SelectionChanged event has old value, not new value ComboBox SelectedItem vs SelectedValue Getting Serial Port Information VB.NET: how to prevent user input in a ComboBox Populating a ComboBox using C# How to get multiple selected values of select box in php? jQuery Combobox/select autocomplete? How do I style a <select> dropdown with only CSS? WPF - add static items to a combo box How to display default text "--Select Team --" in combo box on pageload in WPF? Binding an enum to a WinForms combo box, and then setting it WPF MVVM ComboBox SelectedItem or SelectedValue not working How to bind a List to a ComboBox? How to disable editing of elements in combobox for c#? Binding a WPF ComboBox to a custom list How do I set the selected item in a comboBox to match my string using C#? How can I create an editable dropdownlist in HTML? C# - Fill a combo box with a DataTable Professional jQuery based Combobox control? How can I make a ComboBox non-editable in .NET?