Get current ComboBox value - c#

Goal is to obtain current ComboBox value.
ComboBox is filled in this part of the code:
List<CategoryDTO> categories = new List<CategoryDTO>();
for (Int32 index = 0; index < response.Categories.Count(); index++)
{
categories.Add(response.Categories.ElementAt(index));
}
CboCategory.DisplayMemberPath = "Name";
CboCategory.SelectedValuePath = "Id";
CboCategory.ItemsSource = categories;
Output:
CboCategory.SelectedValue = c4617c70-fa21-48c3-81da-3ddb647941b0
CboCategory.SelectedItem = Interface.Me.DTO.CategoryDTO
Name is accessible in debug mode:
How to get CboCategory.SelectedItem.Name value?

As pointed out by ASh, you need to cast result like this:
((CategoryDTO)CboCategory.SelectedItem).Name

Related

How to show fields id and name from SQL table to combobox of C#

I would like to retrieve the value of fields 'Id' and 'name' of a SQL table show in a combobox, this is what I got so far:
public void LoadComboboxSite()
{
List<SITE> bp = new List<SITE>();
bp = BUS.BUS_Site.compoboxSite();
for (int i = 0; i < bp.Count; i++)
{
cmbSite.Items.AddRange(bp[i].ID_SITE, bp[i].TEN_SITE);
}
cmbSite.SelectedItem = bp[0].ID_SITE;
}
If you have a list of data from your database just use:
cmbSite.DisplayMember = "TEN_SITE";
cmbSite.ValueMember = "ID_SITE";
cmbSite.DataSource = bp;

Set selected value in dynamically created combo boxes

I have created dynamic combo boxes but i am not able to set the value of the combo box
var list = new List<string>() { "Add","Sub","Mul","Div"};
for (int i = 0; i < 10; i++)
{
var c = new ComboBox();
c.DataSource = list.ToList();
c.selectedvalue="Sub";
this.flowLayoutPanel1.Controls.Add(c);
}
You are setting the DataSource of your ComboBox and trying to set the SelectedValue but for this to work correctly you need to set the ValueMember to the name of a member property of your datasource. But, in your case, having a simple list of strings, you cannot use any meaningful property name for SelectedValue.
Change your code to
List<string> list = new List<string>() { "Add","Sub","Mul","Div"};
for (int i = 0; i < 10; i++)
{
var c = new ComboBox();
c.Items.AddRange(list.ToArray());
c.SelectedIndex = 1;
this.flowLayoutPanel1.Controls.Add(c);
}
Of course you could make this more generic using the IndexOf("Sub") to retrieve the index and replace the fixed 1 that I have used, but in this case it seems useless.
To select a default value of a combobox use the below code.
c.SelectedIndex = 1;
This will set the start position at the first item in your list.

Add items and value of the drop down list from the database

I used this c# code to add items in dropdownlist(ddlSub) from the table sub_info. But what I want is to add the value of the items in dropdownlist(ddlSub) from the same table which also has a column named sub_id of datatype varchar(50).
private void bind_ddlSub()
{
ddlSub.Items.Insert(0, "-Choose-");
datatable_object = methodClassFunc.getData("select sub_name from sub_info");
for (int i = 0; i <= datatable_object.Rows.Count - 1; i++)
{
ddlSub.Items.Add(Convert.ToString(datatable_object.Rows[i]["sub_name"]));
}
}
You can use the ListItem object to add text and value for a dropdownlist item.
string subname = datatable_object.Rows[i]["sub_name"];
string subid = datatable_object.Rows[i]["sub_id"];
ddlSub.Items.Add(new ListItem(subname,subid));
Or you can bind your datasource like this:
ddlSub.DataSource = datatable_object;
ddlSub.DataTextField = "sub_name";
ddlSub.DataValueField = "sub_id";
ddlSub.DataBind();
You can do:
for (int i = 0; i <= datatable_object.Rows.Count - 1; i++)
{
ddlSub.Items.Add(new ListItem(Convert.ToString(datatable_object.Rows[i]["sub_name"]),
Convert.ToString(datatable_object.Rows[i]["sub_id"]));
}
Or you can bind the DataTable to your DropDownList and the specify DataTextField for display and DataValueField to get the value on index changed event like:
ddlSub.DataSource = datatable_object;
ddlSub.DataTextField = "sub_name";
ddlSub.DataValueField = "sub_id";
ddlSub.DataBind();

How to Add Value to a DataGrid that has a ComboBox Column

What i'm trying to do is collect the data base on the referrence of DocNumber and put it in a DataGrid the record can sometimes be single to many. dependes on how it takes by retrieving. here is my function code below:
internal void SelectDetailsRecord(string p)
{
SFCDataContext SFC = new SFCDataContext();
try
{
var DetailsRec = SFC.Sales_OrderFormDetails.Where(w => w.OrderDocNum == p)
.Select(t => new {
Ord = t.OrderDocNum,
Line = t.LineNumber,
Vcode = t.VariantCode,
Vdesc = t.VariantDesc,
Icode = t.Itemnmbr,
Idesc = t.ItemDesc,
Qty = t.Quantity,
UofM = t.UofM,
Kgs = t.KgsPerBag,
Post = t.Posted
});
int count = 0;
foreach (var r in DetailsRec)
{
decimal TotalKgs = Convert.ToDecimal(r.Qty) * Convert.ToDecimal(r.Kgs);
string[] row =
{
r.Qty.ToString(),
r.Icode,
r.Idesc,
r.UofM,
r.Vcode,
r.Vdesc,
r.Kgs.ToString(),
TotalKgs.ToString(),
r.Line.ToString()
};
//DataGridView1.Rows.Add(row); <-- Tried this one but returns me an error statement.
DataGridView1.Rows[count].Cells[0].Value = row[0];
DataGridView1.Rows[count].Cells[1].Value = row[1]; <-- this Part here is the combo box column
DataGridView1.Rows[count].Cells[2].Value = row[2];
DataGridView1.Rows[count].Cells[3].Value = row[3];
DataGridView1.Rows[count].Cells[4].Value = row[4];
DataGridView1.Rows[count].Cells[5].Value = row[5];
DataGridView1.Rows[count].Cells[6].Value = row[6];
DataGridView1.Rows[count].Cells[7].Value = row[7];
DataGridView1.Rows[count].Cells[8].Value = row[8];
count++;
}
}
catch (Exception) { }
SFC.Connection.Close();
}
Is there a way I could put the value of the record into the datagrid combobox like putting a value in a combobox like this: " ComboBox.Text = Value; " please help if anytone has an idea.
In order to populate a ComboBox with a List of items, you need to set its DataSource.
myComboBox.DataSource = myList;
See the relevant MSDN page: http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox%28v=vs.110%29.aspx
This code must work in this problem:
DataGridView1.Rows[count].Cells[1].Value = Convert.ToString(row[1]);
You have to convert object value into string value to set value in GridComboBox. Also make sure that value of row[1] present in collection GridComboBox

Adding data to a dataGridView row in which there is already a comboboxcolumn

I have a DataGridView that is populated at runtime with a couple of ComboBoxColumn columns. For example,
var newCountryColumn = new DataGridViewComboBoxColumn();
newCountryColumn.HeaderText = "Country";
newCountryColumn.DataSource = CountryListArray.ToArray();
newCountryColumn.DisplayMember = "Name";
newCountryColumn.ValueMember = "Code";
And so on. Now, at runtime the user selects a file to open up, and it is parsed, line by line, into an array.
var lines = File.ReadAllLines(path + "\\" + choosenFile);
foreach (string line in lines) {
numOfRecords++;
errorCounter = 0;
string[] items = line.Split('\t').ToArray();
int billState = headerIndex[0] - 1;
int billCountry = headerIndex[1] - 1;
int shipState = headerIndex[2] - 1;
int shipCountry = headerIndex[3] - 1;
for (int i = 0; i < headerIndex.Count; i++) {
int index = headerIndex[i];
/*Get the state and country codes from the files using the correct indices*/
Globals.Code = items[index - 1].ToUpper();
//If the code can't be found in either list
if (!CountryList.ContainsKey(Globals.Code) && !StateList.ContainsKey(Globals.Code)) {
errorCounter++;
if (errorCounter == 1){
dataGridView1.Rows.Add(items);
}
}
}
}
Now, that works great, except for when I scroll over in the DataGridView, over to where the comboboxes are. Apparently the code doesn't like having a value from the items array being added to a pre-existing comboboxcolumn. And I get an error dialog:
The following exception occurred in the DataGridView: System.ArguementException: DataGridViewComboBoxCell value is not valid.
Can the item from the items array be shown in the combo box column?
newCountryColumn.DisplayMember = "Name";
newCountryColumn.ValueMember = "Code";
Tells newCountryColumn.DataSource to expect a collection with properties named Name and Code. But you pass it a string[]. That is wrong, which is what the error message is telling you.
There are several ways of doing this right, the most straightforward is to declare your own class with properties Name and Code:
class CountryTuple
{
public string Code { get; private set; }
public string Name { get; private set; }
public CountryTuple(string code, string name)
{
this.Code = code;
this.Name = name;
}
}
Now you can instantiate your collection:
var cts = new List<CountryTuple>();
Add instances to your collection::
cts.Add(new CountryTuple(items[index - 1].ToUpper(), whatever));
And assign it to your DataSource:
newCountryColumn.DataSource = cts;

Categories