how to edit the text of combobox from another view c# wpf - c#

I have three combobx for time and I want to edit the text of this comboboxes from another view this is the code for combobpx view
public partial class Combo : Window
{
public Combo()
{
InitializeComponent();
}
private void hrComboBox_Loaded(object sender, RoutedEventArgs e)
{
List<string> hours = new List<string>();
for (int i = 0; i <= 24; i++)
{
if (i < 10)
hours.Add("0" + i);
else
hours.Add(i + "");
}
var comboBox = sender as ComboBox;
comboBox.ItemsSource = hours;
comboBox.SelectedIndex = 0;
}
private void MinComboBox_Loaded(object sender, RoutedEventArgs e)
{
List<string> Minutes = new List<string>();
for (int i = 0; i <= 60; i++)
{
if (i < 10)
Minutes.Add("0" + i);
else
Minutes.Add(i + "");
}
var comboBox = sender as ComboBox;
comboBox.ItemsSource = Minutes;
comboBox.SelectedIndex = 0;
}
private void SecComboBox_Loaded(object sender, RoutedEventArgs e)
{
List<string> Seconds = new List<string>();
for (int i = 0; i <= 60; i++)
{
if (i < 10)
Seconds.Add("0" + i);
else
Seconds.Add(i + "");
}
var comboBox = sender as ComboBox;
comboBox.ItemsSource = Seconds;
comboBox.SelectedIndex = 0;
}
private void OKButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
DialogResult = true;
}
the second view invokes this view as dialog my problem is when I add the text to one of this comboboxes the text isn't set and still "00" the code I use as follows:
var dialog = new Combo();
string[] timeArr = delay.Split(':');
//here is my problem when the dialog is loading the text
//of three comboboxes isn't change
dialog.hr.Text = timeArr[0];
dialog.Min.Text = timeArr[1];
dialog.Sec.Text = timeArr[2];
if (dialog.ShowDialog() == true)
{
string time = dialog.hr.Text+":"+dialog.Min.Text+":"+dialog.Sec.Text;
delay = time;
nextDelay = time;
}
anyone help me, thanks :)

Related

How to annotate a changed item in a listbox with a *

I just need help on how to annotate a changed item in the list box if the user changes something using the text boxes provided.
namespace HW1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] values = new string[5];
values[0] = textBox1.Text;
values[1] = textBox2.Text;
values[2] = textBox3.Text;
values[3] = textBox4.Text;
values[4] = textBox5.Text;
string[] temp = new string[5];
temp[0] = textBox1.Text;
temp[1] = textBox2.Text;
temp[2] = textBox3.Text;
temp[3] = textBox4.Text;
temp[4] = textBox5.Text;
if(temp != values)
{
listBox1.SelectedIndex = 0 + "*";
listBox1.Text = values[1] + "*";
listBox1.Text = values[2] + "*";
listBox1.Text = values[3] + "*";
listBox1.Text = values[4] + "*";
}
listBox1.Items.Clear();
for (int i = 0; i < values.Length; i++)
{
listBox1.Items.Add(values[i].ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
The program will simply replace the old input from the text box with the new without displaying a * next to the item that has changed.
Your code doesn't actually compile... not sure how this line would ever work...
listBox1.SelectedIndex = 0 + "*";
Anyway - the main problem is that your for loop adds in values without the star to the list box
for (int i = 0; i < values.Length; i++)
{
listBox1.Items.Add(values[i].ToString()); //values[i] never has a star stored in it!
}
How about something like this...?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] values = new [] { textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text };
for (int i = 0; i < values.Length; i++)
{
if (listBox1.Items.Count < i + 1)
{
listBox1.Items.Add(values[i].ToString());
continue;
}
string unedited = listBox1.Items[i].ToString();
if (!string.IsNullOrEmpty(unedited) && unedited.Last() == '*')
unedited = listBox1.Items[i].ToString().Substring(0, listBox1.Items[i].ToString().Length - 1);
if (unedited != values[i])
listBox1.Items[i] = values[i] + "*";
else
listBox1.Items[i] = values[i];
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
This compares the list items to the textbox values.
If the textbox value doesn't exist, a listbox item is created.
If the listbox item doesn't match the textbox value, it has a * appended to it.
If an existing value (ignoring the star) is the same as the textbox value, it is updated to ensure the star is removed.

Search by DisplayMember in ListBox

I have a ListBox which I populate like this:
var dtCustomers = db.GetTableBySQL(query).AsEnumerable().Select(rows =>
new CustomersModel
{
Name = rows.Field<string>("Name"),
ProjectKey = rows.Field<int>("ProjectKey")
});
lstCustomers.DataSource = dtCustomers.ToList();
lstCustomers.DisplayMember = "Name";
lstCustomers.ValueMember = "ProjectKey";
lstCustomers.ClearSelected();
Now I want to create TextBox with search button to look inside this list and search by item selected as:
private void btnSearch_Click(object sender, EventArgs e)
{
lstCustomers.SelectedItems.Clear();
for (int i = lstCustomers.Items.Count - 1; i >= 0; i--)
{
if (lstCustomers.Items[i].ToString().ToLower().Contains(txtSearch.Text.ToLower()))
{
lstCustomers.SetSelected(i, true);
}
}
lblitems.Text = lstCustomers.SelectedItems.Count.ToString() + "items found";
}
Problem is it never finds anything. I think it is because it is comparing by ValueMember instead of DisplayMember. Can I search in the list by DisplayMember?
You can use pattern matching for this since the underlying items will be your CustomersModel:
private void btnSearch_Click(object sender, EventArgs e)
{
lstCustomers.SelectedItems.Clear();
int matchCount = 0;
for (int i = lstCustomers.Items.Count - 1; i >= 0; i--)
{
if (lstCustomers.Items[i] is CustomersModel customer &&
customer.Name.IndexOf(txtSearch.Text, StringComparison.OrdinalIgnoreCase) > -1)
{
matchCount++;
lstCustomers.SetSelected(i, true);
}
}
lblItems.Text = $"{matchCount} item{(matchCount > 1 ? "s" : "")} found";
}

values a re not being displayed in TextBox

in this program, when the Recall button (recallBtn_Click()) is clicked, it calls a method (that calculates directions) from another class which should then call the showPath() method. the show path method should then display its output in a textBox. But the values don't show even though i can see from debugging that the values are being sent to the text box. can anybody tell me where i went wrong?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
storeRetSelect.SelectedIndex = 0;
PrioritySelect.SelectedIndex = 0;
}
public void showPath(List<PathFinderNode> mPath)
{
var T = new Form1().directionsTextBox;
foreach (PathFinderNode node in mPath)
{
if ((node.X - node.PX) > 0) { T.Text += "Right" + System.Environment.NewLine ; }
if ((node.X - node.PX) < 0) { T.Text += "Left" + System.Environment.NewLine; }
if ((node.Y - node.PY) > 0) { T.Text += "UP" + System.Environment.NewLine; }
if ((node.Y - node.PY) < 0) { T.Text += "Down" + System.Environment.NewLine; }
}
}
private void recallBtn_Click(object sender, EventArgs e)
{
var path = new pathPlan();
string desigString = inputTextBox.Text;
int[] desig = new int[3];
for (int i = 0; i < desigString.Length; i++) { desig[i] = (int)char.GetNumericValue(desigString[i]); }
path.Recall(desig[1], desig[2], (-1) * desig[0]);
}
}
With this line you are initialising a new object and get the reference of the textbox there.
var T = new Form1().directionsTextBox;
But I assume you want to use the textbox of the form which is allready open. Change the line to the following to access the textbox of the current object.
var T = this.directionsTextBox;

Access Object created in another method C#

In this code I'm creating Few DataGridViews. Number of those depends on file which within each launch of application will be different, so is number of DataGridViews.
How can I Access particular dataGridView grid[i] and modify it from which event Form1_UserAddedRow was called in that method?
Code:
public void Form1_Load(object sender, EventArgs e)
{
string[] lines = System.IO.File.ReadAllLines(#"..\..\Base.txt");
int diet_num = 0;
int grid_num = 0;
foreach (string x in lines) diet_num++;
grid_num = (diet_num / Constant.DATAGRID_DIETS_IN_GRID) + 1;
DataGridView[] grid = new DataGridView[grid_num];
for (int i = 0; i < grid_num; i++)
{
grid[i] = new DataGridView();
grid[i].Tag = i;
grid[i].Parent = this;
grid[i].Location = new Point(12, 12 + (8 + Constant.DATAGRID_ROW_HEIGHT * 2) * i);
grid[i].Visible = true;
grid[i].RowHeadersVisible = false;
grid[i].Height = Constant.DATAGRID_ROW_HEIGHT * 2;
grid[i].Width = Constant.DATAGRID_COLUMN_SIZE * Constant.DATAGRID_DIETS_IN_GRID + 3;
grid[i].UserAddedRow += Form1_UserAddedRow;
}
this.Width = Constant.DATAGRID_COLUMN_SIZE * Constant.DATAGRID_DIETS_IN_GRID + 40;
foreach (string x in lines)
{
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.Width = Constant.DATAGRID_COLUMN_SIZE;
col.HeaderText = x;
int colIndex = grid[0].Columns.Add(col);
}
}
private void Form1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
//I want to access grid[i] and modify it here.
}
You should be able to cast the Sender object parameter in your event handler to the type of DataGridView to retrieve the grid which has been effected.
You are getting the DataGridViewRowEventArgs e as the argument to your event handler and thus you can access the Row property like
e.Row.Cells["somename"].Value = "some_value";
private void Form1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
var grid = sender as DataGridView;
if (grid == null) return;
//... do something
}

Display my filled array values into listbox and optionally delete them

Ok, so with the help of awesome guys here on Stackoverflow I have created my array like this.
public partial class Form1 : Form
{
string[] Brands = new string[10];
int brandNo;}
public Form1()
{
InitializeComponent();
Brands[0] = "Yamaha"; //ok
Brands[1] = "Suzuki"; //ok
Brands[2] = "Harley"; //ok
Brands[3] = "Kawasaki"; //ok
brandNo = 4;
}
private void buttonAddbrand_Click(object sender, EventArgs e)
{
if (brandNo >= 10)
return; //cannot add more brand
Brands[brandNo++] = textBoxMerk.Text;
var Merk = Brands
listBoxMotoren.Items.Clear();
listBoxMotoren.Items.AddRange(Merk);
With this code I want to display the filled values of the array in my listbox. But I get the following error:
value can not be null.
Help will be much appreciated.
Firstly, be careful of where you put your curly bracket as to ensure that the code can be compiled.
public partial class Form1 : Form
{
string[] Brands = new string[10];
int brandNo;} //<- off-placed
Secondly, since you start with making the array as your DataSource (and not using Items.Add or Items.AddRange to your listBoxMotoren, it may be consistent if you doing so on addition or removal of your item in the listBoxMotoren.
private void buttonAddbrand_Click(object sender, EventArgs e) {
if (brandNo >= 10)
return; //cannot add more brand
Brands[brandNo++] = textBoxMerk.Text;
listBoxMotoren.DataSource = null; //the cheapest and dirtiest trick to do this
listBoxMotoren.DataSource = Brands; //Maintaining the style, use `DataSource` to accommodate new data
}
Lastly, if you want to remove the brand item at will, you might need another Control in your Form1 as an input for which item in the brand you want to get optionally delete. But beware that this may "destroy" the sequence of your items and thus you may need to "re-sequencing" your item.
Now, suppose you use NumericUpDown to delete and trigger the deletion using buttonDeletebrand then you should do something like this
private void buttonDeletebrand_Click(object sender, EventArgs e) {
int indexToDelete = (int)numericUpDownMotorenNumberDeleted.Value; //note the casting to (int)
if (indexToDelete < 0 || indexToDelete >= brandNo || brandNo <= 0) //can only delete index no [0] to [brandNo-1], and if the brand no > 0
return; //invalid index
for (int i = indexToDelete; i < brandNo - 1; ++i)
Brands[indexToDelete] = Brands[indexToDelete + 1]; //resequencing
Brands[brandNo - 1] = string.Empty; //removes the last element after resequencing
listBoxMotoren.DataSource = null; //remember the cheapest and dirtiest trick?
listBoxMotoren.DataSource = Brands;
--brandNo; //reduce the brandNo by 1
}
In total, you need all of them combined:
public partial class Form1 : Form {
string[] Brands = new string[10];
int brandNo;
public Form1() {
InitializeComponent();
Brands[0] = "Yamaha";
Brands[1] = "Suzuki";
Brands[2] = "Harley";
Brands[3] = "Kawasaki";
brandNo = 4;
listBoxMotoren.DataSource = Brands;
}
private void buttonAddbrand_Click(object sender, EventArgs e) {
if (brandNo >= 10)
return;
Brands[brandNo++] = textBoxMerk.Text;
listBoxMotoren.DataSource = null;
listBoxMotoren.DataSource = Brands;
}
private void buttonDeletebrand_Click(object sender, EventArgs e) {
int indexToDelete = (int)numericUpDownMotorenNumberDeleted.Value;
if (indexToDelete < 0 || indexToDelete >= brandNo || brandNo <= 0)
return;
for (int i = indexToDelete; i < brandNo - 1; ++i)
Brands[indexToDelete] = Brands[indexToDelete + 1];
Brands[brandNo - 1] = string.Empty;
listBoxMotoren.DataSource = null;
listBoxMotoren.DataSource = Brands;
--brandNo;
}
}
i'm pretty sure this code do not even compile....
int brandNo;} <- "}" ???
var Merk = Brands <- ";" missing and (var Merk) not needed
locking at this code i guess the problem is in
check
if (listBoxMotoren != null && listBoxMotoren.Items.Any())
listBoxMotoren.Items.Clear();
and of cource
if (listBoxMotoren != null && Brands != null)
listBoxMotoren.Items.AddRange(Brands);
if listboxMotoren is null the form is not initialized yet as long listBoxMotoren is a form Control
public partial class Form1 : Form
{
string[] Brands = new string[10];
int brandNo;
public Form1()
{
InitializeComponent();
Brands[0] = "Yamaha"; //ok
Brands[1] = "Suzuki"; //ok
Brands[2] = "Harley"; //ok
Brands[3] = "Kawasaki"; //ok
brandNo = 4;
listBoxMotoren.DataSource=Brands;//asssiign the current list to //listbox
}
private void buttonAddbrand_Click(object sender, EventArgs e)
{
if (brandNo >= 10)
return; //cannot add more brand
Brands[brandNo++] = textBoxMerk.Text;
listBoxMotoren.DataSource = null; //make the list empty
listBoxMotoren.DataSource = Brands;// assgin it new list
}

Categories

Resources