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.
Related
I have a Windows form on which I put a flow layout panel. I also have a class that reads a local database and returns the corresponding values. Depending on the user input via a button(s) the panel gets filled with other buttons. The amount of these buttons depends on the values in the local database. The buttons are displayed correctly and with the correct information, but the order in which they are displayed is alphabetical even though the data-table, from the database class, is ordered in the correct way (via the numerical value of the "ID" column from the database).
I have also added a data-grid view to check and there the items are displayed in the correct way. I have tried to add a for-each loop but that just seems to randomize the order of the buttons.
Does anybody know how I can get the buttons to be displayed in the correct way, so that the button with the lowest "ID" value gets displayed first.
Here is the code for displaying the buttons:
//set the datagridview with the correct values/names. Order works perfectly
dataGridView_AttackName.DataSource = db.attackIDName(attackCategory, taughtOn);
DataTable dt = db.attackIDName(attackCategory, taughtOn);
//sort datable again because doesnt work from db class
dt.DefaultView.Sort = "ID";
dt.DefaultView.ToTable();
int horizontal = 0;
int vertical = 0;
Button[] buttonArray = new Button[dt.Rows.Count];
for (int items = 0; items < buttonArray.Length; items++)
{
buttonArray[items] = new Button();
buttonArray[items].Size = new Size(150, 50);
buttonArray[items].Location = new Point(horizontal, vertical);
buttonArray[items].Name = string.Format("Button_{0}", dt.Rows[items]["ID"].ToString());
buttonArray[items].Text = dt.Rows[items]["Name"].ToString();
buttonArray[items].Click += btn_msg;
if ((items + 1) < buttonArray.Length)
{
vertical += 50;
}
flowLayoutPanel_AttackName.Controls.Add(buttonArray[items]);
}
//get the correct ID value from the button name and try to order it that way
foreach (Button b in flowLayoutPanel_AttackName.Controls)
{
string name = b.Name;
string subname = name.Substring(name.IndexOf("_") + 1);
int i = Convert.ToInt32(subname);
flowLayoutPanel_AttackName.Controls.SetChildIndex(b, i);
}
I have searched around on this site but couldn't find anything that worked.
You've correctly sorted the DefaultView by the ID, but then haven't used the results!
You need to replace, for example, dt.Rows[items]["Name"]with dt.DefaultView[items].Row["Name"]. You then don't need the statement dt.DefaultView.ToTable().
Full code is below:
dt.DefaultView.Sort = "ID";
int horizontal = 0;
int vertical = 0;
Button[] buttonArray = new Button[dt.Rows.Count];
for (int items = 0; items < buttonArray.Length; items++)
{
buttonArray[items] = new Button();
buttonArray[items].Size = new Size(150, 50);
buttonArray[items].Location = new Point(horizontal, vertical);
buttonArray[items].Name = string.Format("Button_{0}", dt.DefaultView[items].Row["ID"].ToString());
buttonArray[items].Text = dt.DefaultView[items].Row["Name"].ToString();
buttonArray[items].Click += btn_msg;
if ((items + 1) < buttonArray.Length)
{
vertical += 50;
}
flowLayoutPanel_AttackName.Controls.Add(buttonArray[items]);
}
Using selectedIndexChange for Combobox to fill Textboxes in Access Database.
I've tried using the following:
txtEventDate.Text = cboEventName.SelectedValue.ToString();
but it doesn't fill in from the selected data.
// clear out listbox
cboEventName.Items.Clear();
// create instance of class
clsData myData = new clsData();
// send SQL statement to class
myData.SQL = "SELECT ID, EventName, EventDate FROM tblEvents ORDER BY EventName";
// loop through datatable to get values
for (int i = 0; i < myData.dt.Rows.Count; i++)
{
// add customer to list box
cboEventName.Items.Add(myData.dt.Rows[i]["EventName"].ToString());
// add customer id to list
string eventdate = ["EventDate"].ToString();
txtEventDate.Text = cboEventName.SelectedValue.ToString();
// txtEventDate trying to fill from combobox entry and it isn't showing the date from the access.
intEventID.Add(int.Parse(myData.dt.Rows[i]["ID"].ToString()));
}
Try like this to set EventDate for Selected Index value. If SelectedValue is Matching to MyData Row Index then set event Date.
for (int i = 0; i < myData.dt.Rows.Count; i++)
{
// add customer to list box
cboEventName.Items.Add(myData.dt.Rows[i]["EventName"].ToString());
// add customer id to list
if(cboEventName.SelectedValue.ToString() ==myData.dt.Rows[i]["EventName"].ToString())
string eventdate = ["EventDate"].ToString();
txtEventDate.Text = cboEventName.SelectedValue.ToString();
}
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
I have two ComboBox which I update the content of second ComboBox when the first one is changed. Everything works okay except that the updated ComboBox would always show an empty entry when it is updated.
Here is a screenshot from it:
Here is how I update it:
var comboBox = sender as ComboBox;
if(comboBox.SelectedIndex == 0)
comboDetail.ItemsSource = new List<string> { model.Detail[0] , model.Detail[1] };
else if (comboBox.SelectedIndex == 1)
comboDetail.ItemsSource = new List<string> { model.Detail[2] };
else if (comboBox.SelectedIndex == 2)
comboDetail.ItemsSource = new List<string> { model.Detail[3] , model.Detail[4] };
comboDetail.SelectedItem = 0;
comboDetail.Items.Refresh();
you want select the First element. but SelecteItem Determines which item-object is selected and not by position.
instead
comboDetail.SelectedItem = 0;
comboDetail.Items.Refresh();
write:
comboDetail.SelectedIndex = 0;
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();