Adding custom options in bound dropdown in asp.net - c#

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.

Related

Filling two nested drop dwon list when editing an entry in c#

i have two nested drop down list.
one drop down show group,the other show sub group.
i have coded data source of subgroup drop down list on group drop down list selected indexed change event.
What I'm trying to do is set a drop down list to be whatever its value is in the database when editing an entry.
i have used data row.
i have two tables.documentgroup(GroupId,parentId,groupTitle,subGroupTitle) and documents(DocID,GroupID,Title,url)
in my drop down lists i have added list item like this
<asp:ListItem Text = "--select group--" Value = ""></asp:ListItem>
when i click on editing a document,i have this.
protected void grdDocuments_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DoEdit")
{
GC.Collect();
GC.WaitForPendingFinalizers();
int DocID = Convert.ToInt32(e.CommandArgument);
ViewState["DocumentID"] = DocID;
ViewState["EditMode"] = "Edit";
DataTable dtDocuments = DataLayer.Documents.SelectRow(DocID).Tables["Documents"];
if (dtDocuments.Rows.Count != 0)
{
DataRow drDocuments = dtDocuments.Rows[0];
txtDocTitle.Text = drDocuments["DocTitle"].ToString();
txtDocPubYear.Text = drDocuments["DocPubYear"].ToString();
ddlDocGroupTitle.SelectedValue = drDocuments["ParentID"].ToString();
ddlDocSubGroupTitle.SelectedValue = drDocuments["DocGroupID"].ToString();
ViewState["DocCurrentUrl"] = drDocuments["DocUrl"].ToString();
mvDocuments.SetActiveView(vwEdit);
}
}
but i get this error
'ddlDocSubGroupTitle' has a SelectedValue which is invalid because it
does not exist in the list of items. Parameter name: value
and this is the same for ddldocgroupTitle.
i have made an inner join between two tables.
what should i do?
I could not really grasp your question, but it looks like you want to have 2 dropdown, and upon selection in the first, the second gets populated/filtered correct?!?
I recommend that you use javascript/Jquery to do so. Upon page load, issue a ajax get request to fill the "main" dropdown, and upon selection on the first one, you issue a second ajax request to fetch the possible values of the second one...
A alternative is to fetch the items for the first dropdown AND all the values possible for the second, storing the result in some hidden-field data. Then upon selection of the first value, you can only filter + display relevant data.

How to set combobox first element in winform application in 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.

Setting DataSource to DataGridViewComboBoxColumn

I'm trying to set DataSource to DataGridViewComboBoxColumn of my DataGridView. First I'm trying to bind a data source to my DataGridView, where bindingList is a List of my custom class Plugin with properties Name (string), Id (string) and Dependencies (List):
var bindingList = PluginsHandler.GetPlugins();
var source = new BindingSource(bindingList, null);
pluginsDataGridView.AutoGenerateColumns = false;
pluginsDataGridView.DataSource = source;
pluginsDataGridView.Columns["pluginName"].DataPropertyName = "Name";
pluginsDataGridView.Columns["pluginID"].DataPropertyName = "Id";
So I can set my first two columns, but now I want to bind data to a third column of type DataGridViewComboBoxColumn. I try to do it on DataBindingComplete event:
private void pluginsDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
for (int i = 0; i < pluginsDataGridView.Rows.Count; i++)
{
var comboCell = (DataGridViewComboBoxCell) pluginsDataGridView.Rows[i].Cells["pluginDependencies"];
var entry = pluginsDataGridView.Rows[i].DataBoundItem as IPlugin;
comboCell.DataSource = entry.Dependencies;
}
}
Sadly comboBox is empty. Funny thing happens when I incorrectly put these lines after the first block of code I posted:
var dependenciesColumn = (DataGridViewComboBoxColumn) pluginsDataGridView.Columns["pluginDependencies"];
dependenciesColumn.DataPropertyName = "Dependencies";
Then binding seem to start to work, as I can see that there are some entries in comboboxes, but when I try to hover mouse on combobox, I am getting an error that says DataGridViewComboBoxCell value is not valid).
How can I make it work?
Instead of assigning each ComboCell a data Source, set the DataSource of the column. I assume the Dependencies property of PlugIn class is a List<string>.
pluginsDataGridView.Columns["pluginDependencies"].DataSource = //list of dependencies
You have to set the DataPropertyName of the Dependencies ComboBoxColumn to get the initial values. If you don't set it you won't see any value in the column when the application is loaded.
pluginsDataGridView.Columns["pluginDependencies"].DataPropertyName = "Dependencies"
Edit:
You have a list of dependencies for a plug-in. i.e, more than one value. Usually, to select one value from list of values, you associate list with ComboBoxColumn. Achieving your requirement of multiple values from a list using standard ComboBoxColumn is difficult. Write a custom CheckedComboBoxColumn where you can display and select multiple values.

Repository item lookUpEdit resets after losing focus

I have this problem for days and can't find solution for it. I tried all possible solutions i found on internet, but seems like none suits this one.
Thing is that i added repository item to gridControls (i added it through designer, not through code). Then, in code i added data source to that repository lookUpEdit and i have items in dropDown in that column. But when i select item in repository and click on other cell, Selected item in repository is cleared and repository shows null value again...
Any ideas what i did wrong ?
EDIT:
Also, when i click on any cell in my grid, i have delay of second or two, and after that delay clicked cell is focused... Any solutions for all of this?
EDIT:
Don't know what code to show You, because I did all in devExpress designer. Here is part of the code where I set data source to repository item, and i will give You code from designer of that repository item.
private void ConfigureRepositoryItems()
{
BetService.SportManagerClient dbSportManager = new BetService.SportManagerClient();
BetService.BLOddsControlSettings[] oddsControlSettings = dbSportManager.GetOddsControlSettings("", "");
repositoryOddsControlSettings1.DataSource = oddsControlSettings;
}
And here is code from designer:
//
// repositoryOddsCalculationSettings1
//
this.repositoryOddsCalculationSettings1.AutoHeight = false;
this.repositoryOddsCalculationSettings1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.repositoryOddsCalculationSettings1.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("ID", "ID", 20, DevExpress.Utils.FormatType.None, "", false, DevExpress.Utils.HorzAlignment.Default),
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "Name")});
this.repositoryOddsCalculationSettings1.DisplayMember = "Name";
this.repositoryOddsCalculationSettings1.Name = "repositoryOddsCalculationSettings1";
this.repositoryOddsCalculationSettings1.NullText = "Select Settings";
this.repositoryOddsCalculationSettings1.PopupSizeable = false;
this.repositoryOddsCalculationSettings1.ValueMember = "ID";
For starters check whether the column name in your Grid datasource and the column in your grid control match. The match is case sensitive so name and Name are not same and hence can cause this issue. Secondly make sure the Grid datasource column datatype matches the value type of the LookUpEdit. If the LookupEdit is returning int and the Grid datasource column datatype is string, this alone can cause lots of headaches.

problem with drop down list

I have a drop down list control populated with items and some code to take the currently selected item value. The problem is I only get the value of the first item in the list regardless of what item is actually selected.
Here is my code to populate the drop down:
protected void displayCreateCategories()
{
StoreDataContext db = new StoreDataContext();
var a = from c in db.Categories
orderby c.Name
select new{catName= c.Name,
catId=c.CategoryID};
ddlCategory.DataSource = a;
ddlCategory.DataTextField = "catName";
ddlCategory.DataValueField = "catId";
ddlCategory.DataBind();
}
To get the value of the currently selected item which in my case is always of type integer I do label1.text=Convert.toInt32(ddlCategory.SelectedValue);
I get the selected value, but it is always for the 1st item in the list. I'm pulling my hair out over this. :(
I suspect you're running the list loading code every time the page loads, which is destroying the list, repopulating the list, and auto-selecting the first item before your selection retrieval code gets run.
Use this construction in Page_Load:
if (!IsPostBack)
{
// Initial control population goes here
}
Data binding will reset the control's selected value so make sure you retrieve the selected value before data binding on postback.

Categories

Resources