I have a dropdown list on my windows form application that holds the manufacturer's names. Upon editing a given record, I want the user to be able to edit (change) the manufacturer as well. The rest of values are working fine and I can easily assign them to the text boxes where they will be edited and stored in the database again.
I have queried the dropdown list item (the manufacturer name that needs to be edited) from the database and now I want to show it as the selected item on the dropdown list. I used the following code to query a particular manufacturer based on id from the database and assign it to a string variable, manufacturerName
.
DataTable dtMName = Products.SelectByManufacturerId(manufacturerId);
if (dtMName.Rows.Count > 0)
{
foreach (DataRow item in dtMName.Rows)
{
string manufacturerName = item[0].ToString();
}
}
Upon debugging this piece of code, the string manfuacturerName
hold the exact manufacturer name that I want to change in the dropdown list. Now, I want to mark this particular item as the selected item in the dropdown list. I want to pass it to the list so that it can select this particular manufacturer in the list.
So far, I have tried the following code but it is not working.
childEditProduct.cmbManufacturer.SelectedIndex = childEditProduct.cmbManufacturer.FindString(manufacturerName);
Note: I have marked the first item as the selectedIndex on childEditProduct form load. I have commented that code as well but nothing works. Is there any issue in my code or let me try something more effective that can solve my problem.
As I was loading the manufacturer dropdown list on my childForm load event using the following function:
private void LoadManufacturers()
{
cmbManufacturer.Items.Clear();
DataTable dtManufacturers = DataAccess.Select("select manufacturername from tblmanufacturer order by manufacturername asc");
foreach (DataRow dr in dtManufacturers.Rows)
{
cmbManufacturer.Items.Add(dr[0].ToString());
}
//cmbManufacturer.SelectedIndex = 0;
}
While loading manufacturers on the page load event, I was also specifying the selected index of the dropdown list using the code cmbManufacturer.SelectedIndex = 0;
which I commented out later.
Once done, I then recalculate (re-query) the selected manufacturer (which the user want to update) within the load event of the dropdown list like this:
private void frmChildEditProduct_Load(object sender, EventArgs e)
{
LoadManufacturers(); // Calling the loadManufacturers function to load all the manufacturers to the dropdown list.
string manufacturerID = lblManufacturerId.Text;
DataTable dtMName = Products.SelectByManufacturerId(manufacturerID);
if (dtMName.Rows.Count > 0)
{
foreach (DataRow manufacturer in dtMName.Rows)
{
string manufacturerName = manufacturer[0].ToString();
cmbManufacturer.SelectedIndex = Convert.ToInt32(cmbManufacturer.FindStringExact(manufacturerName));
}
}
}
And my problem was solved. Thanks for the support I got on Stackoverflow.