Combobox index and value of non continued index - c#

Not Sure how to explain the situation but its something like this
I am fetching (INT)category_id and (VARCHAR)categories_code from database and trying to push data inside Combobox using Index(category_id) and Value(categories_code). Now my problem starts when database doesn't have continued number index Eg. 0,1,3 and it throws Exception
InvalidArgument=Value of '3' is not valid for 'index'.
Parameter name: index
My Code is something like this
String query = "SELECT * FROM `category`";
productCategory.Items.Insert(0, "--- SELECT ---");
using (MySqlDataReader mysqlData = con.Select(query))
{
if (mysqlData.HasRows)
{
while (mysqlData.Read())
{
int id = mysqlData.GetInt32("category_id");
String name = mysqlData.GetString("category_code");
productCategory.Items.Insert(id, name);
}
}
}
What can be the expected solutions for this?

Use a counter instead ?
int i = 1;
using (MySqlDataReader mysqlData = con.Select(query))
{
if (mysqlData.HasRows)
{
while (mysqlData.Read())
{
int id = mysqlData.GetInt32("category_id");
String name = mysqlData.GetString("category_code");
productCategory.Items.Insert(i++, name);
}
}
}
or why don't you just use Add method?
productCategory.Items.Add(name);
If you want to get category id of selected item, then you should use a class for that.Create a class that has two properties, CategoryId and CategoryCode. Then have a List<YourClass> populate it, set the DataSource, ValueMember and DisplayMember properties of combobox.
productCategory.DataSource = yourList;
productCategory.DisplayMember = "CategoryCode";
productCategory.ValueMember = "CategoryId";

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.

Import ForeignKey values by ComboBox

I'm trying to import a ForeignKey values using ComboBox, but the ComboBox loads string values and the ForeignKey type is int,I tried to convert ToString(),then I got error:
"The left hand side of an assignment must be a variable property or indexer"
ShippingDocumentDataClassesDataContext dc = new ShippingDocumentDataClassesDataContext();
t_tracking newInvoice = new t_tracking();
newInvoice.SupplierId.ToString() = comboBox1.Text;
dc.t_trackings.InsertOnSubmit(newInvoice);
dc.SubmitChanges();
Any help would be appreciated.
This line is wrong:
newInvoice.SupplierId.ToString() = comboBox1.Text;
you are trying to assign value to method call.
Instead this line should be:
newInvoice.SupplierId = Int32.Parse(comboBox1.Text);
or safer way:
int id = 0;
if (Int32.TryParse(comboBox1.Text, out id))
{
//we get valid integer from combobox
newInvoice.SupplierId = id;
dc.t_trackings.InsertOnSubmit(newInvoice);
dc.SubmitChanges();
}
else
{
//wrong value handling code goes here
}

How to set Selected item of ComboBox in C# Windows Forms?

I am trying to set selected item of comboBox on click event of DataGrid, but I could not. I have googled and tried different ways but without success.
For me SelectedIndex is working, but I could not find the index of items in ComboBox, so I could not select the item.
Not working code:
for (int i = 0; i < cmbVendor.Items.Count; i++)
if (cmbVendor.Items[i].ToString() == Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor")))
{
cmbVendor.SelectedIndex = i;
break;
}
You can get your item index by the .Items.IndexOf() method. Try this:
comboBox1.SelectedIndex = comboBox1.Items.IndexOf(gridView1.GetFocusedRowCellValue("vVendor"));
You don't need to iterate.
You can find more information in Stack Overflow question How do I set the selected item in a comboBox to match my string using C#?.
The following is working for me perfectly. Pass any value or Text which is available in the combobox.
comboBox1.SelectedIndex = comboBox1.FindString(<combobox value OR Text in string formate>);
You have it in your if:
cmbVendor.SelectedItem = cmbVendor.Items[i];
At last I found it out. It's:
cmbVendor.Text = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.
If you have set ValueMember property for the ComboBox control, you can simply assingn the Value to the ComboBox control's SelectedValue property. You don't have to find the index explicitly.
Here's an example:
public class Vendor{
public int VendorId {get; set;}
public string VendorName {get; set;}
}
// Inside your function
var comboboxData = new List<Vendor>(){
new Vendor(){ vendorId = 1, vendorName = "Vendor1" },
new Vendor(){ vendorId = 2, vendorName = "Vendor2" }
}
cmbVendor.DataSource = comboboxData;
cmbVendor.DisplayMember = "VendorName";
cmbVendor.ValueMember = "ValueId";
// Now, to change your selected index to the ComboBox item with ValueId of 2, you can simply do:
cmbVendor.SelectedValue = 2;
Assuming gridView1.GetFocusedRowCellValue("vVendor") really works as expected, the following code should fix the problem.
string selected = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
foreach ( var item in cmbVendor.Items )
{
if (string.Compare(item.ToString(), selected, StringComparison.OrdinalIgnoreCase) == 0)
{
cmbVendor.SelectedItem = item;
break;
}
}
The original code had multiple calls to gridView1.GetFocusedRowCellValue("vVendor"), whereas you only need one.
The suggested "comboBox1.Items.IndexOf(" assumes too much about the content of cmbVendor.Items.
I had a similar problem and worked it out partially with the help of the other answers here. First, my particular problem was that
combobox1.SelectedItem = myItem;
was not working as expected. The root cause was that myItem was an object from a group which was effectively the same list as the items in the combobox, but it was actually a copy of those items. So myItem was identical to a valid entry, but itself was not a valid object from the combobox1 container.
The solution was to use SelectedIndex instead of SelectedItem, like this:
combobox1.SelectedIndex = get_combobox_index(myItem);
where
private int get_combobox_index(ItemClass myItem)
{
int i = 0;
var lst = combobox1.Items.Cast<ItemClass >();
foreach (var s in lst)
{
if (s.Id == myItem.Id)
return i;
i++;
}
return 0;
}
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String From DataGrid Cell value")
Try this this will work fine in C# Windows application
this works for me.....
string displayMember = ComboBox.DataSource.To<DataTable>().Select("valueMemberColumn = '" + value + "'")[0]["displayMember"].ToString();
ComboBox.FindItemExact(displayMember, true).Selected = true;

Items collection cannot be modified when the DataSource property is set

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.

C#: assigning text and value to combobox member

I think i knew how to do this once upon a time but I can't figure it out right now. I'm trying to assign a list item in a combo box that has an associated value. Reason being is because i am populating it with a list of names from a database but I want it to store the primary key as a value so that I can call it directly in a subsequent query. For example, you select a name from a list of supervisors which will store the primary key for that supervisor in a variable for use in an event that will list all employees that have that key assigned to them as a supervisor. That make sense? Pretty standard. Here's what I have that is loading just the text portion of the names in:
The query:
static string sql = "select rtrim(elname),rtrim(efname) from employee where pos_id = 2";
The code that populates the list:
try
{
conn.Open();
//determine how many records affected/returned
int records = dbAdapter.Fill(results); //fills the datatable with results and returns the number of records
if (records > 0)
{
//do something with the results (stored in the datatable)
foreach (DataRow dr in results.Rows)
{
cboSupervisor.Items.Add(dr[0] + ", " + dr[1]);
}
cboSupervisor.Sorted = true;
}
}
catch { }
This fills the dropdown with lastname, firstname
The best way is create a class containing the information you want to display and the one you want to keep, then specialize ToString():
public class ComboItem : object
{
protected String name;
....
....
protected int id;
public ComboItem(String name, int id)
{
this.name= name;
this.id = id;
}
public override string ToString()
{
return name;
}
};
Could you use a ComboBoxItem, use the Content Property to set the name, and use the Tag Property to set the Value? Then add the ComboBoxItem to your ComboBox's Items collection?

Categories