Items collection cannot be modified when the DataSource property is set - c#

I get this error while trying to add items to the combobox at runtime.Is there a way to add items on runtime , even if my combobox datasource is set .
Example:My combobox has items , but i want to display "Select Category" type of statement when my form loads .
Thanks !!!

Assuming
public class Product
{
public int Id {get;set;}
public string Name {get;set;}
}
with EF
var list = context.Products.Where(x = > x.Active == true).ToList();
list.Insert(0, new Product() { Id = -1, Name = "Please Select" });
selectBox.DataSource = list;
The idea is to get your database list of objects into List < Product > () first, then simply add fake item on top of that list.

If all you want to do is display "Select Category", try this.
DropDownList1.Items.Insert(0, new ListItem("Select Category"));
I'm not sure if it's possible to do this after the DataBind() but I think it should be OK.

Related

Retrieve a ListViewItem's value

I have a ListView populated with the code below. Ask you can see, I set both the DisplayMember and the ValueMember. What I am wanting to do is find a ListViewItem by its ValueMember. So essentially what I'm looking for is ListViewItem.Value. I know I can get SelectedValue for the ListView itself, but I just don't see any properties on the ListViewItem that give me what I'm looking for. Am I just missing something, or is there no way to do this?
private void PopulateList(Globals.DataFieldMappingTypes mappingType)
{
ListBox lst = GetListBox(mappingType);
ComboBox cbo = cboh.GetComboBox(new ComboBoxHandler.CboInfo(Globals.NodeTypes.DataField, mappingType));
string sql = "select DataFieldReferenceValueId, [Value] from DataFieldReferenceValueInfo where DataFieldId = " + cbo.SelectedValue.ToString();
DataTable tbl = dal.GetTable(sql, "DataFieldReferenceValue");
lst.DisplayMember = "Value";
lst.ValueMember = "DataFieldReferenceValueId";
lst.DataSource = tbl.DefaultView;
}
I think that you are not getting the values from DataTable correctly I guess.
I hope tbl.Rows[0][0].ToString() will have the DataFieldReferenceValueId and
tbl.Rows[0][1].ToString() will have the [Value]
Please check the below MSDN link
https://forums.asp.net/t/1188002.aspx?how+to+read+DataTable+Rows+value+and+put+it+into+the+string+
Instead of loading your dataTable straight in as the dataSource why don't you create a class to define the values?
public class SqlTable
{
public string Name {get;set;}
public string Value {get;set;}
}
var listPair = new List<SqlTable>();
Then load the list with your SqlDataReader and grab your desired pair with LINQ.
while (sdr.Read())
{
listPair.Add(new SqlTable() { Name = sdr[0].ToString(), Value = sdr[1].ToString() });
}
lst.DisplayMember = "Name";
lst.ValueMember = "Value";
lst.DataSoure = listPair;
SqlTable sqlTable = listPair.Find(x => x.Name == "Whatever name you are searching for") as SqlTable;
The SqlTable item is now the one you are searching for and you can get its properties by going:
string value = sqlTable.Value;
string name = sqlTable.Name;
Edit from comment begins here:
Well your first issue is that the 'lst' item in your example is a ListBox and not a ListView. It you switch it to a listview you can still feed your List of listPair items like so:
ListView lst = new ListView();
lst.View = View.Details;
foreach (var data in listPair)
{
lst.Items.Add(new ListViewItem(listPair.Name, listPair.Value);
}
So now you have a ListView that is a collection of your listPairs where each listPair is a ListViewItem. I assume you want to isolate the ListViewItem based on your value (or listPair.Value or sdr[1] or [Value] they are all the same now) in order to color it. You can now grab the listPair item like so:
SqlTable pair = listPair.Find(x => x.Value == "Whatever the Value value is that you want to color");
ListViewItem searchedItem = lst.FindItemWithText(pair.Name);
searchedItem.BackColor = System.Drawing.Color.Red; //or whatever color you choose
You can now use searchedItem to grab its index in the ListView and all its other properties. The ListPair just allows you to associate the values.

how to display list<> in drop down list?

I have a dropdownlist where I want to display a list of users. To call the users I use ChatUserDetails.GetPXPUsers()
Which brings me to this code:
public static List<ChatUserDetails> GetPXPUsers()
{
List<ChatUserDetails> Users = new List<ChatUserDetails>();
string SQL = SelectPXPUsers;
DataTable dtMainItems = ChatUserDetails.CustomFill(SQL, null);
foreach (DataRow dr in dtMainItems.Rows)
{
Users.Add(new ChatUserDetails(dr));
}
return Users;
}
But how to I display this list of users in my dropdownlist?
<asp:DropDownList runat="server" ID="DropDownListPXPUsers"></asp:DropDownList>
You can bind your list to your drop down at runtime by using the following code. You will need to specify which properties of the object are to be used.
DropDownListPXPUsers.DataSource = GetPXPUsers();
DropDownListPXPUsers.DateTextField = "PropertyOne"; // name of 'ChatUserDetails' property
DropDownListPXPUsers.DataValueField = "PropertyTwo"; // name of 'ChatUserDetails' property
DropDownListPXPUsers.DataBind();
Read more: See Examples in the DropDownList documentation.
First you'll need to set the DataSource for the DropDownList and then you will need to call DataBind().
if(!IsPostBack)
{
DropDownListPXPUsers.DataSource = GetPXPUsers();
DropDownListPXPUsers.DataBind();
}

Searching for an item in a dataset and showing it in a combo box

I have done combobox binding on form load.
I want to load ComboBox with numerous products, then based on a bar code i 'd like to select the corresponding product in the ComboBox.
I believe you were looking for this:
DataTable products = new DataTable();
products.Columns.Add("Product_Name");
products.Columns.Add("Product_BarCode");
products.Rows.Add("test1", 123456);
products.Rows.Add("test", 923456);
products.Rows.Add("test8", 823456);
products.Rows.Add("test", 723456);
products.Rows.Add("test0", 023456);
productname_tb.DataSource = products;
productname_tb.DisplayMember = "Product_Name";
productname_tb.ValueMember = "Product_BarCode";
// select the "test8" item by using it's Product_BarCode value of 823456
for (int i = 0; i < productname_tb.Items.Count; i++)
{
if (((System.Data.DataRowView)(productname_tb.Items[i])).Row.ItemArray[1].ToString() == "823456")
{
productname_tb.SelectedItem = productname_tb.Items[i];
break;
}
}
If I understand correctly you want to load your ComboBox with numerous products, then based on a bar code you'd like to select the corresponding product in the ComboBox. Try the following:
productname_tb.Items.IndexOf("<YOUR BARCODE>");
Does this work for you?

How to get all the records in a dropdown list?

I have a dropdown list that filters the records by category, but I need the "-- Filter by category --" option to act as the "view all", whereby all the records are returned.
This is in C# .NET. I don't expect it to be too difficult, but its just stumping me right now.
Here is the code-behind for the method:
protected void PopulateCategories()
{
category myCategory = new category();
category[] myCategoryList = myCategory.Listing("title ASC");
ddlCategories.Items.Add("-- Filter by category --");
foreach (category category in myCategoryList)
{
ListItem item = new ListItem(category.title, category.category_id);
ddlCategories.Items.Add(item);
}
}
Depending on what your data source is, and how it reacts to the category.category_id value, you should put a value as part of your "-- Filter by category --" entry...
ddlCategories.Items.Add(New ListItem("-- Filter by category --", "-1"));
Then when you use the ddlCategories.SelectedValue (or however you use it) make sure that if the value is -1 then return everything
In order to make your form more intuitive, you may want to populate the dropdown as shown below:
ddlCategories.Items.Add(new ListItem("- View all categories -", "-1"));
foreach (category category in myCategoryList)
{
ListItem item = new ListItem("View category: " + category.title, category.category_id);
ddlCategories.Items.Add(item);
}
Then, to answer your question, create 2 data access methods: #1 for retrieving all rows, #2 for retrieving rows filtered by the chosen category.
public DataTable GetData(int categoryId)
{
if(categoryId <= 0)
{
// #1
return CatProvider.FindAll(); // Ex. SELECT * FROM table_cats;
}
else
{
// #2
return CatProvider.FindByCategoryId(categoryId); // Ex. SELECT * from table_cats where id_category = #id_category;
}
}
However, I would consider using checkboxes instead (1 for each category), so the user can select any permutation of either all categories, just 1 category, or any combination of multiple categories.
(That's about all I can suggest for now based on the info you provided.)

How can I hide an option in my drop down without changing the query

I have a drop down in aspx that is binded using a class that has a function that retrieves a list of departments. There is a department Name "Audits and Verifying". I do not want to modify the query to do a select Name, DepatmentValueName from departments where DepartmentValueName <> 'AuditsVerifying' . Instead I want to hide it some how in the code in C# is this possible?
DepartmentsAdmin DepartmentName = new DepartmentsAdmin();
DepartmentType.DataSource = DepartmentName.GetAllDepartments();
DepartmentType.DataTextField = "Name";
DepartmentType.DataValueField = "DepartmentValueName";
DepartmentType.DataBind();
Thank you in advance
Try this-
ListItem removeListItem = DepartmentType.Items.FindByText("Audits and Verifying");
DepartmentType.Items.Remove(removeListItem);
You can remove an item from your dropdownlist control after you bind to it.
DepartmentType.Items.Remove(DepartmentType.Items.FindByText("AuditsVerifying"));
The dropdown.Items is an instance of a ListItemCollection. Below is an example of how to remove a ListItem from a ListItemCollection
ListItem myListItem = new ListItem(Delete.Text.ToLower(),Delete.Text.ToLower());
// Check whether the 'ListItem' is present in the 'ListBox' or not.
if(ItemCollection.Contains(myListItem))
{
String deleteString=Delete.Text;
// Delete the listitem entered by the user in textfield.
ItemCollection.Remove(deleteString.ToLower());
Message.Text="<font color='green'><b>Deleted Successfully</b></font>";
}
else
{
Message.Text="<font color='red'><b>No ListItem with the given name is present in the ListBox for deletion.</b></font>";
}
Or you may remove an item based on the Text it displays by using:
DropDownList.Items.Remove("<your string that you want to remove>");
ListItemCollection.Remove() Method

Categories