how to set selected value of combo box in C# - c#

I have two combo box ( say cbo_zone & cbo_floor ) which are having table as the data source
private void load_cbo_zone()
{
clz_Common_References ccr = new clz_Common_References ();
DataTable dt_zone = ccr.get_zone_detail();
cbo_zone.DataSource = dt_zone;
cbo_zone.ValueMember = "ID";
cbo_zone.DisplayMember = "zone";
cbo_zone.SelectedIndex = -1;
}
`
private void load_cbo_floor()
{
int ID_zone_ref = Convert.ToInt16(cbo_zone.SelectedValue);
clz_Common_References ccr = new clz_Common_References();
DataTable dt_flr = ccr.get_floor_data_fr_Ref_IDZone(ID_zone_ref);
cbo_floor.DataSource = dt_flr;
cbo_floor.DisplayMember = "Floor";
cbo_floor.ValueMember = "ID";
cbo_floor.SelectedIndex = -1;
}
` . I wrote the code to update the cbo_floor as following .
private void cbo_zone_SelectionChangeCommitted(object sender, EventArgs e)
{
load_cbo_floor();
}
Now I need to update the cbo_zone & cbo_floor when I click a data row of datagridview .
int ref_area_id, ref_floor_id, ref_zone_id;
int.TryParse(dt_issued_mat.Rows[0][11].ToString(), out ref_area_id);
DataTable dt_area_detail = ccr.get_area_data_fr_area_id(ref_area_id);
int.TryParse(dt_area_detail.Rows[0][2].ToString(), out ref_floor_id);
DataTable dt_floor_detail = ccr.get_floor_data_fr_floor_id(ref_floor_id);
int.TryParse(dt_floor_detail.Rows[0][2].ToString(), out ref_zone_id);
DataTable dt_zone_detail = ccr.get_zone_data_fr_zone_id(ref_zone_id);
after that using
cbo_zone.Text = dt_zone_detail.Rows[0][1].ToString();
cbo_floor.Text = dt_floor_detail.Rows[0][1].ToString();
I was able to display the values on the combo boxes but once I tried to get the cbo_floor.SelectedValue code doesn't work .
Then I was able to get the relevant SelectedIndex by using ,
int index = cbo_zone.FindString(dt_zone_detail.Rows[0][1].ToString());
cbo_zone.SelectedIndex = index ;
still the combo box shows nothing & "cbo_zone.SelectedValue" doesn't
show a value.my target is to get the cbo_floor.SelectedValue .
Please help .

Instead of cbo_zone.Text = dt_zone_detail.Rows[0][1].ToString();
cbo_floor.Text = dt_floor_detail.Rows[0][1].ToString();
Use
cbo_zone.Items.Add( dt_zone_detail.Rows[0][1].ToString());
cbo_floor.Items.Add ( dt_floor_detail.Rows[0][1].ToString());

First working with indexes is not a good idea. You have the value, use them. Using the index will cause you trouble.
cbo_zone.SelectedValue = myValue.ToString();//find the value from your data
Secondly for selecting the floor, you need to fill it with the relevant values first, since it already has the data for the last selection.
load_cbo_floor();
cbo_floor.SelectedValue = myValue.ToString();//find the value from your data

Related

How to refresh dropdown list after setting index to 0?

I already have an event handler for a button that generates an excel report. (ExportExcel(filename); is the method that generates the excel report FYI) So that's fine and dandy. What I'm trying to do now is refresh the dropdown list so it reflects what the correct Dropdown selection is.
I got it to set the dropdown list to the 0th index but the dropdown list doesn't change for some reason. So I think I need to somehow individually reset the dropdown list.
Here's some code below. (I left in some comments and Debug.WriteLine()'s to show my thought process)
protected void GenerateButton1(object sender, EventArgs e)
{
// CustomerDropdown.ClearSelection();
// CustomerDropdown.Items.Clear();
// Page.Response.Redirect(Page.Request.Url.ToString(), true);
//////////
// Below is resetting the CustomerDropdown list.
ViewState["DropDownIndexSelection"] = CustomerDropdown.SelectedItem.Value.Trim();
DataSet dataSet = (DataSet)ViewState["DropDownListDs"];
var filename = "Customer ID - " + DateTime.Now + ".xlsx";
ExportExcel(filename);
// DataSet DropDownIndexSelection = (DataSet)ViewState["DropDownIndexSelection"];
CustomerDropdown.Items.Clear();
// CustomerDropdown.ClearSelection();
CustomerDropdown.DataTextField = dataSet.Tables[0].Columns["cust_id"].ToString();
CustomerDropdown.DataValueField = dataSet.Tables[0].Columns["cust_id"].ToString();
CustomerDropdown.DataSource = dataSet.Tables[0]; //assigning datasource to the dropdownlist
// CustomerDropdown.Items[0].Selected = true;
CustomerDropdown.DataBind(); //binding dropdownlist
CustomerDropdown.Items.Insert(0, new ListItem("Please select"));
CustomerDropdown.Items.Insert(1, new ListItem("All"));
CustomerDropdown.Items.FindByValue("Please select").Selected = true;
Debug.WriteLine(CustomerDropdown.Items.FindByValue("Please select").Selected == false);
Debug.WriteLine(CustomerDropdown.Items.FindByValue("Please select").Selected == true);
return;
}
How can I set the Dropdown back to "Please select" after running the ExportExcel(filename) method? I think basically what I'm asking is how do I refresh the CustomerDropdown after setting the selection to "Please select"
CustomerDropdown.SelectedIndex = 0;
after that it will select the 0th index selection, which is "Please select."
Have you tried adding to your code:
ExportExcel(filename);
// DataSet DropDownIndexSelection = (DataSet)ViewState["DropDownIndexSelection"];
CustomerDropdown.Items.Clear();
// CustomerDropdown.ClearSelection();
CustomerDropdown.DataTextField = dataSet.Tables[0].Columns["cust_id"].ToString();
CustomerDropdown.DataValueField = dataSet.Tables[0].Columns["cust_id"].ToString();
CustomerDropdown.DataSource = dataSet.Tables[0]; //assigning datasource to the dropdownlist
// CustomerDropdown.Items[0].Selected = true;
CustomerDropdown.DataBind(); //binding dropdownlist
CustomerDropdown.Items.Insert(0, new ListItem("Please select"));
CustomerDropdown.Items.Insert(1, new ListItem("All"));
CustomerDropdown.SelectedIndex=0; ---> Possible solution
?
Got from: Reference

Datagridview not updating correctly

I'm new-ish to C# and I'm trying to input a list of objects into a datagridview. I constantly add items to this list each time I click a button and the datagridview should refresh by setting it's data source back to the list.
Here is the list:
List<Models.OrderItem> orderitemlist = new List<Models.OrderItem>();
And here is the code that adds to the list and refreshes the list:
private void btnAddToOrder_Click(object sender, EventArgs e)
{
int quantity = Convert.ToInt32(tbAddOrderQuantity.Text);
int stock = Convert.ToInt32(ItemDataGrid.CurrentRow.Cells[6].Value);
int newstock = stock - quantity;
if (newstock < 0)
MessageBox.Show("You do not have enough items in stock for this.");
else
{
ItemDataGrid.CurrentRow.Cells[6].Value = newstock;
int itemID = Convert.ToInt32(ItemDataGrid.CurrentRow.Cells[0].Value);
string itemname = Convert.ToString(ItemDataGrid.CurrentRow.Cells[1].Value);
int sellprice = Convert.ToInt32(ItemDataGrid.CurrentRow.Cells[5].Value);
Models.OrderItem item = new Models.OrderItem(itemID, itemname, sellprice, quantity);
orderitemlist.Add(item);
RefreshItemsOnOrderData();
RefreshPrice();
}
}
private void RefreshItemsOnOrderData()
{
ItemOnOrderDataGrid.DataSource = orderitemlist;
}
The list will update with the first item however when I try to add another item it seems to run the block of code however doesn't actually add it to the datagrid view. Is anyone able to help? Have I made a simple error I just can't see?
As mentioned,
Set the source to null, re-ref the list, then reset bindings
ItemOnOrderDataGrid.DataSource = null;
ItemOnOrderDataGrid.DataSource = orderitemlist;
ItemOnOrderDataGrid.ResetBindings();
You may want to try omitting the null. I can't recall if this works without the null.

how to get value of selected row in DropDown and Grid view

i have 2 question...
1. i have a gridview that bind some data form database that way
DataSource = Company.GetAllCompany();
dgvCompanys.AutoGenerateColumns = false;
dgvCompanys.DataSource = _DataSource;
dgvcolNameEn.DataPropertyName = "MyEnglishName";
dgvcolAddress.DataPropertyName = "MyAddress";
dgvcolCode.DataPropertyName = "MyCode";
dgvcolKeyId.DataPropertyName = "MyKeyId";
it's worked now i want get the KeyId of selected row
private void dgvCompanys_SelectionChanged(object sender, EventArgs e)
{
if (dgvCompanys.SelectedRows.Count > 0)
{
mtxtCode.Text=dgvCompanys.SelectedRows[0].Cells[1].Value.ToString();
}
}
this code have this error Object reference not set to an instance of an object.
what i have to do for this?
question 2.i have textboxdropdownlist(devComponent)
and sourced that way:
List<Company> _DataCompany;
_DataCompany = Company.GetAllCompany();
cmbCompany.DisplayMember = "MyEnglishName";
cmbCompany.DataSource = _DataCompany;
that worked correctly but i want get KeyId of rows selected in dropdown now what i have to do?
Question 1 : perhaps your dataset have only one column, so the right code is :
dgvCompanys.SelectedRows[0].Cells[0].Value.ToString();
Question 2 is not clear for me, but you can access to the selected item with :
DropDown.SelectedItem.ToString()

Selected index combobox winforms

Ok, very dumb question but i haven't really found an answer on internet.
I have multiple comboboxes on a form. The binding of each combobox is on form_load.
When the form loads, the first item is selected on the form. This is obvious, but I don't want this. So i used in the form_load the following code:
private void InvoiceView_Load(object sender, EventArgs e)
{
// Bind list of customers to combobox
CustomerComboBox.DataSource = invoicePresenter.getCustomers();
CustomerComboBox.DisplayMember = "CustomerName";
CustomerComboBox.ValueMember = "CustomerId";
// Bind list of products to combobox
productCombobox.DataSource = invoicePresenter.getProducts();
productCombobox.DisplayMember = "ProductName";
productCombobox.ValueMember = "ProductId";
// Bind list of vat codes to combobox
vatComboBox.DataSource = invoicePresenter.getTaxCodes();
vatComboBox.DisplayMember = "taxCodeShortDescr";
vatComboBox.ValueMember = "taxCodeId";
// Set comboboxes empty
CustomerComboBox.SelectedItem = null;
productCombobox.SelectedItem = null;
vatComboBox.SelectedItem = null;
}
This works. But the textboxes are still giving me the data of the first item ? My guess is because its in the selectedIndexChanged. But i have no clue what to use else.
If I put the combobox.selectedIndex = -1; I face the same issue.
the code:
private void CustomerComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Bind the selected customer itemvalues to the texboxes
txtCustomerName.Text = ((tbl_customer)CustomerComboBox.SelectedItem).CustomerName.ToString();
txtAddress.Text = ((tbl_customer)CustomerComboBox.SelectedItem).CustomerAddress.ToString();
txtPostalCode.Text = ((tbl_customer)CustomerComboBox.SelectedItem).CustomerPostalCode.ToString();
txtCity.Text = ((tbl_customer)CustomerComboBox.SelectedItem).CustomerCity.ToString();
txtCountry.Text = ((tbl_customer)CustomerComboBox.SelectedItem).CustomerCountry.ToString();
txtVatNumber.Text = ((tbl_customer)CustomerComboBox.SelectedItem).CustomerCountryCode.ToString() + ((tbl_customer)CustomerComboBox.SelectedItem).CustomerVat.ToString();
}
One would think, because im using selecteditem in the textbox binding, it would be null also. But this is not the case.
Interestingly, seems like you've hit one of the WF data binding quirks. The problem is caused by the fact that the CurrencyManager class which maintains every list data source does not allow setting the Position property to -1 (thus Current to null) when the list count is not zero. Since the ComboBox is synchronizing the SelectedIndex with the CurrencyManager.Position, this effectively prevents having an unselected item.
As a workaround, if the data bound mode of the list portion is not essential for you, replace the line
CustomerComboBox.DataSource = invoicePresenter.getCustomers();
with
foreach (var customer in invoicePresenter.getCustomers())
CustomerComboBox.Items.Add(customer);
Do the same for the other comboboxes that need such behavior.
You can remove the handler for the SelectedIndex_Changed event of combobox, bind data, then add the handler back. like this :
private void InvoiceView_Load(object sender, EventArgs e)
{
this.CustomerComboBox.SelectedIndexChanged -= new EventHandler(CustomerComboBox_SelectedIndexChanged);
this.productCombobox.SelectedIndexChanged -= new EventHandler(productCombobox_SelectedIndexChanged);
this.vatComboBox.SelectedIndexChanged -= new EventHandler(vatComboBox_SelectedIndexChanged);
// Bind list of customers to combobox
CustomerComboBox.DataSource = invoicePresenter.getCustomers();
CustomerComboBox.DisplayMember = "CustomerName";
CustomerComboBox.ValueMember = "CustomerId";
// Bind list of products to combobox
productCombobox.DataSource = invoicePresenter.getProducts();
productCombobox.DisplayMember = "ProductName";
productCombobox.ValueMember = "ProductId";
// Bind list of vat codes to combobox
vatComboBox.DataSource = invoicePresenter.getTaxCodes();
vatComboBox.DisplayMember = "taxCodeShortDescr";
vatComboBox.ValueMember = "taxCodeId";
this.CustomerComboBox.SelectedIndexChanged += new EventHandler(CustomerComboBox_SelectedIndexChanged);
this.productCombobox.SelectedIndexChanged += new EventHandler(productCombobox_SelectedIndexChanged);
this.vatComboBox.SelectedIndexChanged += new EventHandler(vatComboBox_SelectedIndexChanged);
}

DataGridView Winform c#

every time, i press btnAgregar, add "productos" to list.
only the first time the gridview show the first record of the list
after the list grows, but the datagridview don't refrash, showing only the first record.
List<Entidades.Productos> ProductosVenta = new List<Productos>();
private void btnAgregar_Click(object sender, EventArgs e)
{
Entidades.Productos productos = new Entidades.Productos();
productos = Datos.Productos.ObtenerFormaPagoPorId(int.Parse(txtId.Text));
ProductosVenta.Add(productos);
gvVenta.DataSource = ProductosVenta;
}
the solution is make null the data source before asing the list
ProductosVenta.Add(productos);
gvVenta.DataSource = null; // this does the trick
gvVenta.DataSource = ProductosVenta;

Categories