Currently I have a comboBox that reads information from outlook, and stores a list as values that can be selected for the comboBox.
I would like to be able to set the text of a button to the values stored in this comboBox.
I have an array of buttons that stores the buttons to be changed. Below is the code, so that on a click, the values from the comboBox will be displayed as the text labels in the buttons, the ?? is where I am stuck.
private void Mmaptsks_Click(object sender, EventArgs e)
{
int count = cmb.Items.Count;
for (int i = 0; i < count; i++)
{
buttonArray[i].Visible = true;
buttonArray[i].Text = ??;
}
}
Thanks,
Tom
You can try:
buttonArray[i].Text = cmb.Items[i].ToString();
Or if your combo items are not string then you can:
buttonArray[i].Text = (cmb.Items[i] as YourType).SomeProperty;
Related
Im trying to get the selected value of my 4 comboboxes and add them together automatically in a windows form.
The comboboxes items are decimals, 0,75 , 0,8 etc.
How do i add all the values selected from the comboboxes together into a textbox?
I have tried for 5 hours now and really cant figure it out.
FYI im really a beginner.
Thanks!
You can handle TextChanged event on all combo boxes, calculate the sum and assign the result to the text box.
private void Form1_Load(object sender, EventArgs e)
{
foreach (var comboBox in this.Controls.OfType<ComboBox>())
{
comboBox.TextChanged += ComboBox_TextChanged;
InitializeComboBox(comboBox);
}
}
private void ComboBox_TextChanged(object sender, EventArgs e)
{
double result = 0;
foreach (var comboBox in this.Controls.OfType<ComboBox>())
{
if (!string.IsNullOrEmpty(comboBox.Text))
{
result += Convert.ToDouble(comboBox.Text);
}
}
textBox1.Text = result.ToString();
}
private void InitializeComboBox(ComboBox comboBox)
{
for (int index = 0; index < 10; index++)
{
comboBox.Items.Add(index + 0.5);
}
}
I have a dropdownlist that selects category list from Database and display the product name onto the checkedlistbox. But how do I grabs the checked items from the checkedlistbox to the DataGridView? This is how my design looks like:
Also, how do I make every medication that has been added to the Gridview has a default value of 1 Quantity?
Add this code to your Add button click event:
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemChecked(i))
{
dataGridView1.Rows.Add(checkedListBox1.Items[i], "1");
}
}
}
for (int i = 0; i <= checkedListBox1.SelectedItems.Count - 1; i++)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = checkedListBox1.SelectedItem.ToString();
}
I've got a DataGidView that's very tight on horizontal space, and a column that has rather lengthy descriptions.
What I'd like to do is create a ComboBox column that:
Displays a shortened version of the description
Has the full description in the drop-down
Behind the scenes deals with the actual value
So for example, I have this contrived example below. The real list can have 20-30 items with text that's quite lengthy:
Code Short DropDown Text
1 BigBox Boxes larger than 6' x 6'
2 SmBox Boxes smaller than 6' x 6'
3 BigBrl Barrel 55 gallons
4 SmBrl Barrel less than 55 gallons
So what I want to show is:
When I open the dropdown I want to see:
And of course, when I query the value for the cell, I want "1".
I could split hairs and make the "short" description the first part of the longer description ("BigBx Boxes larger than 6' x 6'") but that doesn't seem right.
I'm looking for suggestions on the best way to accomplish this. No code yet to show, since I'm not quite sure where to start.
You'll want to change the DisplayMember of the combobox on the events DropDown and DropDownClosed.
On the Event DropDown, You'll want to change the DisplayMember to your Long Name. One thing I discovered is that changing the DisplayMember resets the SelectedIndex, so you'll want to save that and then reset it after you've changed the display.
int i = comboBox1.SelectedIndex;
comboBox1.DisplayMember = "LongNm";
comboBox1.SelectedIndex = i;
You'll want to repeat this process with the DropDownClosed event and the Short Name to return to your closed display.
int i = comboBox1.SelectedIndex;
comboBox1.DisplayMember = "ShortNm";
comboBox1.SelectedIndex = i;
The last problem I encountered was changing the width of the combobox dropdown. I found code to do that here.
The final code I had looks like this:
public partial class Form1 : Form
{
List<ComboData> data;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
data = new List<ComboData>();
data.Add(new ComboData(1, "BigBox", "Boxes larger than 6x6"));
data.Add(new ComboData(2, "SmBox", "Boxes small than 6x6"));
data.Add(new ComboData(3, "BirBrl", "Barrel 55 Gallons"));
data.Add(new ComboData(4, "smBrl", "Barrel less than 55 gallons"));
comboBox1.DataSource = data;
comboBox1.DisplayMember = "ShortNm";
}
private void comboBox1_DropDown(object sender, EventArgs e)
{
int i = comboBox1.SelectedIndex;
comboBox1.DisplayMember = "LongNm";
comboBox1.SelectedIndex = i;
ComboBox senderComboBox = (ComboBox)sender;
int width = senderComboBox.DropDownWidth;
Graphics g = senderComboBox.CreateGraphics();
Font font = senderComboBox.Font;
int vertScrollBarWidth =
(senderComboBox.Items.Count > senderComboBox.MaxDropDownItems)
? SystemInformation.VerticalScrollBarWidth : 0;
int newWidth;
foreach (ComboData s in ((ComboBox)sender).Items)
{
newWidth = (int)g.MeasureString(s.LongNm, font).Width
+ vertScrollBarWidth;
if (width < newWidth)
{
width = newWidth;
}
}
senderComboBox.DropDownWidth = width;
}
private void comboBox1_DropDownClosed(object sender, EventArgs e)
{
int i = comboBox1.SelectedIndex;
comboBox1.DisplayMember = "ShortNm";
comboBox1.SelectedIndex = i;
}
}
public class ComboData
{
public int Code;
public string ShortNm
{
get;
set;
}
public string LongNm
{
get;
set;
}
public ComboData(int c, string s, string l)
{
Code = c;
ShortNm = s;
LongNm = l;
}
}
The end result looks like this:
I think I have nearly the thing you want. One small compromise: Whilr you're editing the value, the combobox displays the truncated long value. Otherwise this should suit you well.
My Source code is a slightly edited version of this example. In the example they have an enum that is editable via a comboboxcolumn. My extension now changes the combobox to have a display and value member (the displaymember is the long text and the value member is the actual enum value) and when displaying the cell normally, the cell formatting event comes into play that overrides the display
These are the main changes:
private static T GetAttribute<T>(Enum value)
{
T attribute = value.GetType()
.GetMember(value.ToString())[0].GetCustomAttributes(typeof(T), false)
.Cast<T>()
.SingleOrDefault();
return attribute;
}
DataGridViewComboBoxColumn CreateComboBoxWithEnums()
{
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
//combo.DataSource = Enum.GetValues(typeof(Title));
var datatable = new DataTable(); //Setup a DataTable for your ComboBox Column
datatable.Columns.Add("col1", typeof(string));
datatable.Columns.Add("col2", typeof(Title));
foreach (Title item in Enum.GetValues(typeof(Title)))
datatable.Rows.Add(GetAttribute<DescriptionAttribute>(item).Description, item);
combo.DisplayMember = "col1";
combo.ValueMember = "col2";
combo.DataSource = datatable;
combo.DropDownWidth = 200;
combo.DataPropertyName = "Title";
combo.Name = "Title";
return combo;
}
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 0)//where Column1 is your combobox column
{
var val = dataGridView1[e.ColumnIndex, e.RowIndex].Value;
if (val != null)
{
e.Value = ((Title)val).ToString();
e.FormattingApplied = true;
}
}
}
public enum Title
{
[Description("This better be thy king!")]
King,
[Description("aka wanna-be-king")]
Sir
};
Full code: http://pastebin.com/Mp9DRvDn
You can use the click event or the dropdown event to detect when the user tries to open the combobox. Then display a list box with the longer strings right below the combobox. When the user selects a string from the listbox, set the corresponding value in the combobox.
I am in a beginning C# class and I am having trouble figuring out why after the following code runs, the selected index is still -1 (i.e. the combobox at load is empty). It should be defaulting to selectedIndex = 1:
public string[,] GetArray()
{
//create array with conversion values
string[,] conversionInfo = { {"Miles","Kilometers", "1.6093"},
{"Kilometers","Miles", ".6214"},
{"Feet","Meters", ".3048"},
{"Meters","Feet","3.2808"},
{"Inches","Centimeters", "2.54"},
{"Centimeters","Inches",".3937"}};
return conversionInfo;
}
private void Form_Load(object sender, EventArgs e)
{
//get array to use
string[,] conversionChoices = GetArray();
//load conversion combo box with values
StringBuilder fillString = new StringBuilder();
for (int i = 0; i < conversionChoices.GetLength(0); i++)
{
for (int j = 0; j < conversionChoices.GetLength(1) - 1; j++)
{
fillString.Append(conversionChoices[i, j]);
if (j == 0)
{
fillString.Append(" to ");
}
}
cboConversion.Items.Add(fillString);
fillString.Clear();
}
//set default selected value for combobox
cboConversion.SelectedIndex = 0;
}
public void cboConversions_SelectedIndexChanged(object sender, EventArgs e)
{
LabelSet(cboConversion.SelectedIndex);
}
public void LabelSet(int selection)
{
//get array to use
string[,] labelChoices = GetArray();
//set labels to coorespond with selection
string from = labelChoices[selection, 0];
string to = labelChoices[selection, 1];
lblFrom.Text = from + ":";
lblTo.Text = to + ":";
}
This is a class assignment so I am not allowed to set anything using the designer, other than to link methods to event. Everything works correctly except for the default for the combobox.
Your code is completely correct, but you have one single fault in your mind. Consider, that you are loading the items into the ComboBox after you have initialized the control. At this point the control have no items, therefore the property "Text" is not setted automatically.
You have to differ between the SelectedIndex, which is the index of the item in the list of items, and the Text, which is the text, shown in the ComboBox. So think about when and how you should set the Text-property of the ComboBox.
Always set the Text-property to the first value of your item-list, after you changed it.
Greetings,
the answer of Mario can be interpreted also as:
put your code after the loading (example: on the shown event), in this way the control is initialized and has items.
Is there a way in dropdownlist to show the desired number on pageload?
eg.
I have a dropdownlist control
I am using a for loop to populate it
for (int i = 1; i <= 100; i++)
{
DropDownList1.Items.Add(i.ToString());
}
Now this displays 1 on page load ... but I want to display 7..
How do I do that?
If you mean that it is the default selected value, you would just need to set a default selected value in the page load, after the list has been populated. Make sure only to do this when it is not a postback or you will overwrite any user selections.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.SelectedValue = "7"
}
}
Would set it inside your for loop. Would also store the default somewhere outside the code (db, config) so if it changes you don't have to redeploy.
if(!IsPostBack)
{
for (int i = 1; i <= 100; i++)
{
var newItem = new ListItem(i.ToString());
newItem.Selected = (i == 7);
DropDownList1.Items.Add(newItem);
}
}
After your for loop
DropDownList1.Items.FindByText("7").Selected = true;
Use the SelectedItem or SelectedIndex property.