How to set combobox first element in winform application in c# - c#

I am new in Winform application, here i am using Entity framework, when i binding values to a combobox from sql table, i need to set first combobox item as "Please select", how can i set this..?
var qry = context.Tbl_EmployeeDetails.Where(x => x.IsDeleted == false).ToList();
if(qry!=null)
{
drpname.ValueMember = "RecordId";
drpname.DisplayMember = "Name";
drpname.DataSource = qry;
}
how can i set this first item as "please select" and value '0'
another suggestion in winform that..
how can i set value in a datagridview linkbutton column when i set 'Edit', 'Delete' columns are as linkbutton

You can insert that item in the beginning of the list.
Code:
var items = db.Tbl_EmployeeDetails.Where(x => x.IsDeleted == false).ToList();
items.Insert(0,new Tbl_EmployeeDetail() { RecordId= 0, Name = "[Please Select an Item]" });
drpname.DropDownStyle = ComboBoxStyle.DropDownList; //optional
drpname.ValueMember = "RecordId";
drpname.DisplayMember = "Name";
drpname.DataSource = items;
drpname.SelectedIndex = 0;
Screenshot:
Note
To have a hint in ComboBox without adding an item, take a look at following post:
Set hint or watermark or default text for ComboBox without adding it as item:

After you load your var qry which will be a List<string>
you want to do the following
var qry = context.Tbl_EmployeeDetails.Where(x => x.IsDeleted == false).ToList();
if(qry!=null)
{
drpname.ValueMember = "RecordId";
drpname.DisplayMember = "Name";
drpname.DataSource = qry;
drpname.Items.Insert(0, "--Please Select--");
drpname.SelectedIndex = 0;
}
Or you could have easily added it to qry since you are returning the data ToList()
for example
var qry = context.Tbl_EmployeeDetails.Where(x => x.IsDeleted == false).ToList();
qry.Insert(0, "--Please Select--");
if(qry!=null)
{
drpname.ValueMember = "RecordId";
drpname.DisplayMember = "Name";
drpname.DataSource = qry;
drpname.SelectedIndex = 0;
}

Your combobox cannot contain additional items if you are binding it to a data source. You have a few options here:
Don't bind it to a data source, i.e. populate it manually from your data set by looping through the items in your query and adding them individually to the combobox; this will allow you the opportunity to first add your "Please Select" item. This can be complicated because you will actually have to add the string names as the items in the combobox, and then you can set the item's Tag property to the actual query row to reference it later.
Include a fake item returned from your query that has a display member of "please select". Note, I don't recommend this approach because you're allowing your presentation logic to leak into your data/business layer.
Use a third-party control instead of the win forms combobox. I've used Infragistics and they have the ability to display a "suggestion" that's not actually in the list when nothing is selected.

Related

How to insert first item in combo box with text "SELECT" with default value 0 in C# windows application

I am using C# windows application. My code is as below
var categoryList = _objCategoryManager.GetAll();
cmbCategory.DisplayMember = "Name";
cmbCategory.ValueMember = "Id";
cmbCategory.DataSource = categoryList;
Here categoryList is of type IEnumerable. I want to insert item in ComboBox at 0 index i.e."--SELECT--"
You cannot insert item to your ComboBox after data binding. Instead insert the item in a copy of your data source before, then do the binding.
If categoryList is IEnumerable<T> and not a List<T> then you should copy it to a List<T> so that you can add your default value at the first index:
var categoryList = _objCategoryManager.GetAll().ToList();
categoryList.Insert(0, new Category {Id = -1, Name = "--SELECT--"});
Simply insert it into your list, so something like
var categoryList = _objCategoryManager.GetAll().ToList();
cmbCategory.DisplayMember = "Name";
cmbCategory.ValueMember = "Id";
categoryList.Insert(0, new Category() { Name = "--SELECT--"} );
cmbCategory.DataSource = categoryList;
categoryList.ToList().Find(o => o.ID == Convert.ToInt32(0)).Name = "--SELECT--";
Using LINQ, you can find the object you want to change (after binding) and modify that item.
Otherwise if you are adding an object into the list:
categoryList.ToList().Add(obj); // This should show the new item in the combo box
Ultimately your .GetAll() method should have returned the first one to be "--SELECT--" instead of trying to modify it afterwards.

Linq-to-sql to Combobox binding (Winforms)

I have a WinForm. At this form I show data from table row.
I have tables Comments and Users:
Comments :{ ID(int),Text(NVarchar), UserId(int) }
Users: { ID(int), Name(NVarChar) }
At a form I have TextBox and Combobox. In Textbox I won't show "Text" from Comments (user can edit this field, data must be saved in a table) and Name from table Users (where Comments.UserId = Users.ID).
I have following code:
FormDataClassesDataContext dc = new FormDataClassesDataContext();
_comment = (from comment in dc.Comments
where comment.ID == 1
select comment).FirstOrDefault();
_user = (from users in dc.Users
where users.ID == _comment.UserId
select users).FirstOrDefault();
textBoxComment.DataBindings.Add("Text", _comment, "Text"); // <-OK
comboBoxAssessor.DataSource = dc.Users;
comboBoxAssessor.DisplayMember = "Name";
comboBoxAssessor.ValueMember = "ID";
comboBoxAssessor.DataBindings.Add("SelectedItem", _comment, "UserId");
and then
dc.SubmitChanges();
but I become "Unable to pass "MyApp.Forms.User" to "Int32"
The selected item of a combobox is the current object in its data source, in this case: a User. You must use SelectedValue:
comboBoxAssessor.DataBindings.Add("SelectedValue", _comment, "UserId");
which returns the value of the property you define in the ValueMember.
SelectedItem should be of type User if I don't make a mistake. And you bind Comment.UserId (int) to it.

replace true/false in datagridview columns

I have a datagridview which I fill it as below :
var q= repository.GetStudents();//
dataGridView1.DataSource = null;
dataGridView1.Columns.Clear();
dataGridView1.DataSource = q;
dataGridView1.Columns.RemoveAt(1);
//Remove IsActive
//Cause I want to have my own implementation
dataGridView1.Columns[0].DataPropertyName = "StudentID";
dataGridView1.Columns[0].HeaderText = "Studunet ID";
dataGridView1.Columns[1].DataPropertyName = "IsActive";
dataGridView1.Columns[1].HeaderText = "Status";
The "IsActive" property is of boolean Type. When the "IsActive" cell is being displayed, it show true/false. I want to replace it with my own custom value.
I read this and this posts but I could not resolve my problem.
You can use the CellFormatting event of the DataGridView, e.g.:
void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
var grid = (DataGridView)sender;
if (grid.Columns[e.ColumnIndex].Name == "IsActive")
{
e.Value = (bool)e.Value ? "MY_TEXT_FOR_TRUE" : "MY_TEXT_FOR_FALSE";
e.FormattingApplied = true;
}
}
EDIT (as per comment):
It's very similar to what you're doing now, just remove the bound column and add a new column of the desired type and set the DataPropertyName properly e.g. :
this.dataGridView1.Columns.Remove("COL_TO_CUSTOMIZE");
var btnCol = new DataGridViewDisableButtonColumn();
btnCol.Name = "COL_TO_CUSTOMIZE";
btnCol.DataPropertyName = "COL_TO_CUSTOMIZE";
var col = this.dataGridView1.Columns.Add(btnCol);
Note that this append the column at the end, but you can decide the position of the column by using dataGridView.Columns.Insert method instead of Add.
One of the funky things about a DataGridViewComboBoxColumn is that you can give it one data source that has a column of values to lookup and a column of values to show, and you can bind it to another column of values and then it will perform the lookup for you
So, suppose your collection q of Students (or whatever they are) has an IsActive true/false and you want this to show as "All the time", or "Not a chance".. Let's hash together a combobox that does this:
var cb = new DataGridViewComboBoxColumn();
cb.DisplayMember = "DisplayMe"; //the related text to show in the combo
cb.ValueMember = "ValueToLookup"; //the name in the combo's lookup list
cb.DataPropertyName = "IsActive"; //the name of your property on Student, to look up
cb.DataSource = "All the time,Not a Chance"
.Split(',')
.Select(s => new { DisplayMe = s, ValueToLookup = (s[0] == 'A') } )
.ToList();
It doesn't really matter how we generat the combo's datasource; here I've made a string into a List<anonymous_string+bool> by splitting, then selecting a new anonymous type with the two property names I need; you can use anything that has some named properties - a List of KeyValuePair, Tuple, whatever..
The critical thing is that the combo can read the q.IsActive bool you cited in DataPropertyName, look that bool up in its list in the property named in the ValueMember, then display the property named in the DisplayMember. It works for editing too, so the user can choose a new item from the combo and the translation works back the other way - "what does the user choose? what is the value of its property named in ValueMember, put that value into the student IsActive property named in DataPropertyName".. And it doesnt stop at bools either; the value member can be anything - an int, date etc

Setting dropdownlist selecteditem programmatically

I want to set the selecteditem attribute for an ASP.Net dropdownlist control programmatically.
So I want to pass a value to the dropdownlist control to set the selected item where the item is equal to the passed value.
Assuming the list is already data bound you can simply set the SelectedValue property on your dropdown list.
list.DataSource = GetListItems(); // <-- Get your data from somewhere.
list.DataValueField = "ValueProperty";
list.DataTextField = "TextProperty";
list.DataBind();
list.SelectedValue = myValue.ToString();
The value of the myValue variable would need to exist in the property specified within the DataValueField in your controls databinding.
UPDATE:
If the value of myValue doesn't exist as a value with the dropdown list options it will default to select the first option in the dropdown list.
ddlData.SelectedIndex will contain the int value To select the specific value into DropDown :
ddlData.SelectedIndex=ddlData.Items.IndexOf(ddlData.Items.FindByText("value"));
return type of ddlData.Items.IndexOf(ddlData.Items.FindByText("value")); is int.
Here is the code I was looking for :
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByText("PassedValue"));
Or
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByValue("PassedValue"));
Well if I understood correctly your question. The Solution for setting the value for a given dropdownlist will be:
dropdownlist1.Text="Your Value";
This will work only if the value is existing in the data-source of the dropdownlist.
If you need to select your list item based on an expression:
foreach (ListItem listItem in list.Items)
{
listItem.Selected = listItem.Value.Contains("some value");
}
Just Use this oneliner:
divisions.Items.FindByText("Some Text").Selected = true;
divisions.Items.FindByValue("some value").Selected = true;
where divisions is a dropdownlist control.
Hope it helps someone.
var index = ctx.Items.FirstOrDefault(item => Equals(item.Value, Settings.Default.Format_Encoding));
ctx.SelectedIndex = ctx.Items.IndexOf(index);
OR
foreach (var listItem in ctx.Items)
listItem.Selected = Equals(listItem.Value as Encoding, Settings.Default.Format_Encoding);
Should work.. especially when using extended RAD controls in which FindByText/Value doesn't even exist!
ddList.Items.FindByText("oldValue").Selected = false;
ddList.Items.FindByText("newValue").Selected = true;
On load of My Windows Form the comboBox will display the ClassName column of my DataTable as it's the DisplayMember also has its ValueMember (not visible to user) with it.
private void Form1_Load(object sender, EventArgs e)
{
this.comboBoxSubjectCName.DataSource = this.Student.TableClass;
this.comboBoxSubjectCName.DisplayMember = TableColumn.ClassName;//Column name that will be the DisplayMember
this.comboBoxSubjectCName.ValueMember = TableColumn.ClassID;//Column name that will be the ValueMember
}
Safety check to only select if an item is matched.
//try to find item in list.
ListItem oItem = DDL.Items.FindByValue("PassedValue"));
//if exists, select it.
if (oItem != null) oItem.Selected = true;
ddlemployee.DataSource = ds.Tables[0];
ddlemployee.DataTextField = "Employee Name";
ddlemployee.DataValueField = "RecId";
ddlemployee.DataBind();
ddlemployee.Items.Insert(0, "All");

Adding custom options in bound dropdown in asp.net

I have a bound dropdown list populated with a table of names through a select, and databinding. it shoots selectedindexchanged that (through a postback) updates a certain gridview.
What happens is, since it runs from changing the index, the one that always comes selected (alexander) can only me chosen if you choose another one, then choose alexander. poor alexander.
What I want is to put a blanc option at the beginning (default) and (if possible) a option as second.
I can't add this option manually, since the binding wipes whatever was in the dropdown list and puts the content of the datasource.
Set the AppendDataBoundItems property to True. Add your blank, then data bind.
ddl.AppendDataBoundItems = true;
ddl.Items.Add("Choose an item");
ddl.DataSource = foo;
ddl.DataBind();
The AppendDataBoundItems property
allows you to add items to the
ListControl object before data
binding occurs. After data binding,
the items collection contains both the
items from the data source and the
previously added items.
protected void SetAddrList()
{
TestDataClassDataContext dc = new TestDataClassDataContext();
dc.ObjectTrackingEnabled = false;
var addList = from addr in dc.Addresses
from eaddr in dc.EmployeeAddresses
where eaddr.EmployeeID == _curEmpID && addr.AddressID == eaddr.AddressID && addr.StateProvince.CountryRegionCode == "US"
select new
{
AddValue = addr.AddressID,
AddText = addr.AddressID,
};
if (addList != null)
{
ddlAddList.DataSource = addList;
ddlAddList.DataValueField = "AddValue";
ddlAddList.DataTextField = "AddText";
ddlAddList.DataBind();
}
ddlAddList.Items.Add(new ListItem("<Add Address>", "-1"));
}
I created this code example using adventure works to do a little practice with Linq and it is very similar to the previous answer. Using linq still shouldn't matter for the answer the last dddlAddList.Items.Add is what you need. "Add Address" = first selected option and -1 = the value.

Categories

Resources