variable and textbox mapping in c# without using textbox changed event - c#

I'm trying a code which changes the TextBox values when variable mapped with it changes accordingly without using TextBox changed event. I am not finding any clue to where to start please help me.
Here is the code:
public void varChange(TextBox text)
{
String name;
name="sachin";
text.Text = name;
MessageBox.Show("" + text.Text);
}

You can "extend" TextBox :
public class MeTextBox : TextBox
{
public override string Text
{
get
{
return base.Text;
}
set
{
//base.Text = value; // use it or not .. whatever
MyTextWasChanged();
}
}
void MyTextWasChanged()
{
String name;
name="sachin";
//text.Text = name;
base.Text = name;
MessageBox.Show("" + text.Text);
}
}
If that's not what you're looking for then give some more details and I'll update this answer.

You can use a BindingSource
public partial class Form1 : Form
{
private System.Windows.Forms.BindingSource form1BindingSource;
public string BindedProp { get; set; } //Variable or property binded with TextBox
public Form1()
{
InitializeComponent();
this.form1BindingSource = new System.Windows.Forms.BindingSource(new System.ComponentModel.Container());
this.form1BindingSource.DataSource = typeof(binding.Form1);
this.textBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.form1BindingSource, "BindedProp", true));
this.form1BindingSource.DataSource = this;
}
//add a button control to assing value code event click
private void btAssingValueProperty_Click(object sender, EventArgs e)
{
BindedProp = "Value assigned";
form1BindingSource.ResetBindings(false);
}
//add a other button control to show value code event click
private void btShowValueProperty_Click(object sender, EventArgs e)
{
MessageBox.Show(BindedProp);
}
}

Related

Reload Windows Forms variables without reloading form layout

Is there a way to reload a form variables?
string a = ""
public form1()
{
InitializeComponent();
}
private void form1_load(object sender, EventArgs e)
{
a = "Something";
textbox1.Text = a;
}
Is there a way to reset the value of "a" to empty and the text displayed on the textbox? I can create a function to set the value of "a" to empty and empty the textbox but as I have many variables, I want to avoid doing that as I might miss one that will cause a bug. I was wondering if there is a way to do that.
I don't want to reinitialize the form as its kinda slow to reload the form graphics again. Thanks for any help.
I would work like this:
public struct Snapshot
{
public string a;
public int? b;
}
private Snapshot _initial;
private void form1_Load(object sender, EventArgs e)
{
_initial = this.CreateSnapshot();
}
private Snapshot CreateSnapshot()
{
return new Snapshot()
{
a = textbox1.Text,
b = int.TryParse(textbox2.Text, out int x) ? (int?)x : null
}
}
private void button1_Click(object sender, EventArgs e)
{
this.RestoreSnapshot(_initial);
}
private void RestoreSnapshot(Snapshot snapshot)
{
textbox1.Text = snapshot.a;
textbox2.Text = snapshot.b.HasValue ? snapshot.b.Value.ToString() : "";
}
Your _initial Snapshot happens at form1_Load to save where the form was at at the beginning. You then just call this.RestoreSnapshot(_initial); whenever you want to revert your values.
The advantage of this kind of approach is that it allows you to make multiple snapshots and implement an "undo" function and, because you have separated your form from your data, it makes testing easier.
Have you considered using a wrapper around your properties, with change notification? You can then use data binding to make the value and the text boxes update together. See the following:
public partial class Form1 : Form
{
public NotifyProperty<string> A { get; } = new NotifyProperty<string>();
public NotifyProperty<double> B { get; } = new NotifyProperty<double>();
public void Reset()
{
A.Value = "Something";
B.Value = 3.14d;
}
public Form1()
{
InitializeComponent();
textBox1.DataBindings.Add("Text", A, "Value", true, DataSourceUpdateMode.OnPropertyChanged);
textBox2.DataBindings.Add("Text", B, "Value", true, DataSourceUpdateMode.OnPropertyChanged);
Reset();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
Reset();
}
}
public class NotifyProperty<T> : INotifyPropertyChanged
{
private T _value;
public T Value
{
get => _value;
set
{
if (_value != null && _value.Equals(value)) return;
_value = value;
PropertyChanged?.Invoke(this,new PropertyChangedEventArgs("Value"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
When Reset() is called, both the values in A and B and textBox1 and textBox2 will be updated. Also, when you are obtaining the results from the form, you can use A and B (you don't need to use the textboxes, because when the user types text, A and B will be updated automatically).
First Form
public partial class FrmCasher : XtraForm
{
public static FrmCasher instanceC;
public SimpleLabelItem num;
public FrmCasher()
{
InitializeComponent();
num = lableTableID; // We want to change lableTableID's text value
instanceC = this;
}
}
Second Form
public partial class FrmHall : DevExpress.XtraEditors.XtraForm
{
private void FrmHall_FormClosing(object sender, FormClosingEventArgs e)
{
FrmCasher.instanceC.num.Text = "Our new String value...";
}
}

Loaded an object into a listbox with 2 variables, listbox show only the name

I have a Class where there a 2 variables int ID and string name. I made a list of several objects and loaded them onto a listbox. The listbox only show the name. Is there a way to retrieve the ID from the listbox?
class Show
{
private int _Id;
private string _Naam;
private string _Genre;
public override string ToString()
{
return Naam;
}
}
from a database i make a list of objects.
private void bttn_zoek_Click(object sender, EventArgs e)
{
foreach (object a in List<show> List)
{
listbox1.Items.Add(a);
}
}
I hope this is enough
Assuming WinForms, here is a super simple example of overriding ToString() to control how the class is displayed in the ListBox, and also how to cast the selected item in the ListBox back to your class type so you can extract values from it. There are other ways to accomplish this task, but you should understand a bare bones example like this first:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SomeClassName sc1 = new SomeClassName();
sc1.ID = 411;
sc1.Name = "Information";
listBox1.Items.Add(sc1);
SomeClassName sc2 = new SomeClassName();
sc2.ID = 911;
sc2.Name = "Emergency";
listBox1.Items.Add(sc2);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
SomeClassName sc = (SomeClassName)listBox1.Items[listBox1.SelectedIndex];
label1.Text = "ID: " + sc.ID.ToString();
label2.Text = "Name: " + sc.Name;
}
}
}
public class SomeClassName
{
public int ID;
public string Name;
public override string ToString()
{
return ID.ToString() + ": " + Name;
}
}
Posting some of your code would be nice. Have you tried listBox.items[index].ID?
Here I'm assuming that index is whatever index you're currently searching for.
You can also try listBox.SelectedItem[index].ID if you're doing something like an event.

c# ComboBox, save item with value and text

I am trying to add an object ITEM with TEXT and VALUE to a ComboBox so I can read it later
public partial class Form1 : Form
{
ComboboxItem item;
public Form1()
{
InitializeComponent();
comboBox1.Items.Add(new ComboboxItem("Dormir", 12).Text);
}
private void button1_Click(object sender, EventArgs e)
{
ComboboxItem c = (ComboboxItem)comboBox1.SelectedItem;
label1.Text = c.Text;
label2.Text = c.Value.ToString();
}
}
The problem is, I cant add the full Item because isn't a string...and give an exception at beginning of click event
Extra information:
This ComboboxItem, its a class that I created with 2 parameters, string, and int
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public ComboboxItem(string texto, double valor)
{
this.Text = texto;
this.Value = valor;
}
}
You could (should) set the displaymember and valuemember in another place, but...
public Form1()
{
InitializeComponent();
comboBox1.DisplayMember="Text";
comboBox1.ValueMember ="Value";
comboBox1.Items.Add(new ComboboxItem("Dormir", 12));
}
Create the ComboboxItem class and override the ToString method.
The ToString method will be called to visualize the item. By default, ToString() returns the typename.
public class ComboboxItem
{
public object Value{get;set;}
public string Text {get;set;}
public override string ToString(){ return Text; }
}
Then, you can do this:
var item = new CombobxItem { Value = 123, Text = "Some text" };
combobox1.Items.Add(item);
you dont need to add .Text at the end of ("text","value")
so add it as :
comboBox1.Items.Add(new ComboBoxItem("dormir","12"));
You are on the right lines by creating your own ComboBoxItem class.
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
}
There are two ways to use this, (Constructor aside):
Method 1:
private void button1_Click(object sender, EventArgs e)
{
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.Value = 12;
comboBox1.Items.Add(item);
}
Method 2:
private void button1_Click(object sender, EventArgs e)
{
ComboboxItem item = new ComboboxItem
{
Text = "Item text1",
Value = 12
};
comboBox1.Items.Add(item);
}
Have you tried adding it like this instead? Then when ever you get the Item out just cast it as a ComboboxItem :)
...
var selectedItem = comboBox1.SelectedItem as ComboboxItem;
var myValue = selectedItem.Value;
...
Alternative KeyValuePair:
comboBox1.Items.Add(new KeyValuePair("Item1", "Item1 Value"));
Question based on returnign string value and other combobox answers..
ComboBox: Adding Text and Value to an Item (no Binding Source)

Passing value from one form to a textbox in another form

Well I know this question has been asked a couple of times but none of the solutions worked for me. I simply want to pass a value from one form to a textbox in a different form.
On the first form I have a data grid when double-clicked on it obtains a value from the datagrid column.
public partial class AvailableRooms : Form
{
private void DCRoom(object sender, DataGridViewCellMouseEventArgs e)
{
var roomnum = dgRooms.Rows[e.RowIndex].Cells["iRoomNum"].Value.ToString();
RoomBooking rb = new RoomBooking();//The second form
rb.roomnumber = roomnum;
rb.Show();
}
}
On the second form I have set the properties of the textbox
public partial class RoomBooking : Form
{
public RoomBooking()
{
StartPosition = FormStartPosition.CenterScreen;
InitializeComponent();
}
public string roomnumber
{
get { return txtRoomNum.Text; }
set {txtRoomNum.Text = value;}
}
}
Thanks in advance for the help?
You have to find the control to edit it as it does not belong to the class.
private void DCRoom(object sender, DataGridViewCellMouseEventArgs e)
{
//new value
var roomnum = dgRooms.Rows[e.RowIndex].Cells["iRoomNum"].Value.ToString();
//The second form
RoomBooking rb = new RoomBooking(this);
//The textbox
TextBox roomnumber = (TextBox)rb.Controls.Find("roomnumber", true)[0];
//set the value of the textbox
roomnumber.Text = roomnum;
//show second form
rb.Show();
}
I would define the RoomBookingclass like this:
public partial class RoomBooking : Form
{
public RoomBooking() // WinForms Designer requires a public parameterless constructor
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
}
public RoomBooking(string roomNumber) : this() // Constructor chaining
{
RoomNumber = roomNumber;
txtRoomNum.Text = RoomNumber;
}
public string RoomNumber { get; set; }
}
Then:
public partial class AvailableRooms : Form
{
private void DCRoom(object sender, DataGridViewCellMouseEventArgs e)
{
var roomNumber = dgRooms.Rows[e.RowIndex].Cells["iRoomNum"].Value.ToString();
var roomBooking = new RoomBooking(roomNumber);
roomBooking.Show();
}
}
Hope this helps.

Properties are 'reset' with two forms?

I'm using MainWindow and Settings. MainWindow is the startup window from which I can open Settings. I'm trying to share some properties between both windows. Right now, I have the public properties declared in Settings:
public partial class Settings : Form
{
private string property1
public Settings()
{
InitializeComponent();
this.changeSettings();
}
public string property1
{
get { return property1; }
set { property1 = value; }
}
public void changeSettings()
{
textbox.Text = property1;
}
}
I can create an instance of Settings in MainWindow and change the properties from there:
public partial class Mainwindow : Form
{
private Settings settings;
public MainWindow()
{
InitializeComponent();
settings = new Settings();
this.changeSettings();
}
private void changeSettings()
{
settings.property1 = "value";
textbox.Text = settings.property1;
}
private void openSettings_Click(object sender, EventArgs e)
{
settings.ShowDialog();
}
}
Say, I want to change the contents of the textboxes in both forms. For MainWindow this works, i.e. I can store the value in the property and access it again. However, I open up Settings and try to change its textbox, the property is empty!
What could explain this?
You never called changeSettings() after setting the property.
You should probably get rid of that method and update the textbox directly in the setter.
The flaw is in Settings.property1, it doesn't update the text box that displays its value. A simple solution is:
public string property1
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
You'll also need to update your MainWindow's text box after displaying the dialog:
private void openSettings_Click(object sender, EventArgs e)
{
settings.property1 = textbox.Text;
if (settings.ShowDialog() == DialogResult.OK) {
textbox.Text = settings.property1;
}
}

Categories