Message Box unable to call local variable - c#

I'm going to preface this by saying I'm sure the question has already been asked but I've tried all the suggestions and nothing seems to work for me. It just keeps returning a blank message box. If the answer were just a nice snippet of code I can add to my answer that would be fantastic.
private string Text1;
public void Button_Click(object sender, RoutedEventArgs e)
{
TextBox txtbx = new TextBox();
txtbx.Height = 50;
txtbx.Width = 200;
txtbx.Margin = new Thickness(771, 282, 0, 0);
txtbx.Background = new SolidColorBrush(Colors.White);
txtbx.Foreground = new SolidColorBrush(Colors.Black);
Text1 = txtbx.Text;
if (EditChecked == true)
{
LayoutRoot.Children.Add(txtbx);
Button Save = new Button();
Save.Height = 25;
Save.Width = 50;
Save.Content = "Save";
Save.Margin = new Thickness(771, 382, 0, 0);
LayoutRoot.Children.Add(Save);
txtbx.Text = Text1;
Save.Click += delegate
{
txtbx.Visibility = Visibility.Collapsed;
Save.Visibility = Visibility.Collapsed;
};
}
else if (ViewChecked == true)
{
MessageBox.Show(Text1);
}
}
Edit: Thanks to mjwills I moved the "Text1 = txtbx.Text;" line so this is what ended up working fyi:
private string Text1;
public void Button_Click(object sender, RoutedEventArgs e)
{
TextBox txtbx = new TextBox();
txtbx.Height = 50;
txtbx.Width = 200;
txtbx.Margin = new Thickness(771, 282, 0, 0);
txtbx.Background = new SolidColorBrush(Colors.White);
txtbx.Foreground = new SolidColorBrush(Colors.Black);
if (EditChecked == true)
{
LayoutRoot.Children.Add(txtbx);
Button Save = new Button();
Save.Height = 25;
Save.Width = 50;
Save.Content = "Save";
Save.Margin = new Thickness(771, 382, 0, 0);
LayoutRoot.Children.Add(Save);
txtbx.Text = Text1;
Save.Click += delegate
{
txtbx.Visibility = Visibility.Collapsed;
Save.Visibility = Visibility.Collapsed;
Text1 = txtbx.Text;
};
}

You declare:
private string Text1;
However you only assign it on the chance:
EditChecked = True
And you only display the message if
EditChecked = False
So, you need to assign Text1 on if the EditChecked = False. Perhaps on the declaration:
private string Text1 = "My default message";

Related

C# won't allow me to add event handler to a button into a form class

This is a C# web form project I am starting with after a long time away from IDE coding...
I am trying to make a simple custom dialog box class. This is my code.
public static class Dialogo
{
public static int show ()
{
Form dialogo = new Form();
dialogo.Width = 300;
dialogo.Height = 300;
Button btnSim = new Button() { Text = "Sim", Left = 30, Width = 100 };
Button btnNao = new Button() { Text = "Não", Left = 150, Width = 100 };
dialogo.Controls.Add(btnSim);
dialogo.Controls.Add(btnNao);
dialogo.ShowDialog();
// the following two lines are the problematic ones
btnSim += new EventHandler(btnSim_Click);
btnNao += new EventHandler(btnNao_Click);
return -1;
}
}
It's underlining the text within parenthesis and the message says:
The name btnSim_Click' does not exist in the current context
The problem is that I tried to add the following in my code but it doesn't let me put it anywhere (it always says that is something wrong):
private int btnNao_Click (object sender, EventArgs e)
{
return 0;
}
private int btnSim_Click (object sender, EventArgs e)
{
return 1;
}
My objective is that each of the both buttons btnSim and btnNao return a different value (say 1 and 0).
What am I doing wrong?
EventHandler is a delegate for a method that returns void.
Your methods return int.
Try something like this:
public static int show()
{
int returnValue = -1;
using (Form dialogo = new Form())
{
dialogo.Width = 300;
dialogo.Height = 300;
Button btnSim = new Button() { Text = "Sim", Left = 30, Width = 100 };
Button btnNao = new Button() { Text = "Não", Left = 150, Width = 100 };
dialogo.Controls.Add(btnSim);
dialogo.Controls.Add(btnNao);
btnSim.Click += (s, e) => { returnValue = 0; dialogo.DialogResult = DialogResult.OK; };
btnNao.Click += (s, e) => { returnValue = 1; dialogo.DialogResult = DialogResult.OK; };
dialogo.Disposed += (s, e) =>
{
btnSim?.Dispose();
btnSim = null;
btnNao?.Dispose();
btnNao = null;
};
dialogo.ShowDialog();
}
return returnValue;
}

How to create custom message in C#?

I am design a custom message box. This message box will show a list of string. But it's not work. Can you hep me to fix it.
You can see in the picture, I have a list with 7 items. When i click the "Grade Project", the Message box don't show any item.
And this is the result I need
//Main form
private void btnGrade_Click(object sender, EventArgs e)
{
List<string> result = new List<string>();
result.Add("True");
result.Add("False");
result.Add("True");
result.Add("False");
result.Add("True");
result.Add("False");
result.Add("False");
MsgBox.Show(result,"Project 1",MsgBox.Buttons.OK);
}
This is code in msgbox form
//MsgBox form
public partial class MsgBox : Form
{
private static MsgBox _msgBox;
// Header, Footer
private Panel _plHeader = new Panel();
private Label _lblTitle;
private Panel _plFooter = new Panel();
private Panel _plIcon = new Panel();
// Panel
private FlowLayoutPanel _flpButtons = new FlowLayoutPanel();
// button
private List<Button> _buttonCollection = new List<Button>();
// Kết quả
private static DialogResult _buttonResult;
// Message
private List<String> _lblMessage;
private MsgBox()
{
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.BackColor = Color.FromArgb(45, 45, 48);
this.StartPosition = FormStartPosition.CenterScreen;
this.Padding = new System.Windows.Forms.Padding(3);
this.Width = 800;
// Header
_lblTitle = new Label();
_lblTitle.ForeColor = Color.White;
_lblTitle.Font = new System.Drawing.Font("Segoe UI", 18);
_lblTitle.Dock = DockStyle.Top;
_lblTitle.Height = 60;
// Message
_lblMessage = new List<string>();
for (int i = 0; i < _lblMessage.Count; i++)
{
TextBox txt = new TextBox(); //Create Textbox có name txt
txt.Text = _lblMessage[i];
txt.ForeColor = Color.Red;
txt.Font = new System.Drawing.Font("Segoe UI", 30);
this.Controls.Add(txt); //add control txt
}
_flpButtons.FlowDirection = FlowDirection.RightToLeft;
_flpButtons.Dock = DockStyle.Fill;
_plHeader.Dock = DockStyle.Fill;
_plHeader.Padding = new Padding(20);
// _plHeader.Controls.Add(_lblMessage);
_plHeader.Controls.Add(_lblTitle);
_plFooter.Dock = DockStyle.Bottom;
_plFooter.Padding = new Padding(20);
_plFooter.BackColor = Color.FromArgb(37, 37, 38);
_plFooter.Height = 80;
_plFooter.Controls.Add(_flpButtons);
// Add controls vào form
this.Controls.Add(_plHeader);
//this.Controls.Add(_plIcon);
this.Controls.Add(_plFooter);
}
public static DialogResult Show(List<String> message, string title, Buttons buttons)
{
_msgBox = new MsgBox();
_msgBox._lblMessage = message;
_msgBox._lblTitle.Text = title;
_msgBox._plIcon.Hide();
MsgBox.InitButtons(buttons);
_msgBox.ShowDialog();
return _buttonResult;
}
Thank you for your watching.
Something wrong with your codes:
private MsgBox()
{
...
// Message
_lblMessage = new List<string>();
...
}
Your _lblMessage will always be an empty list so you see no message at all.
You can change your codes like this:
private MsgBox(List<String> messages)
{
...
// Message
_lblMessage = messages;
...
}
public static DialogResult Show(List<String> message, string title)
{
_msgBox = new MsgBox(message);
//_msgBox._lblMessage = message;
....
}
And also, you'd better set TextBox position otherwise all the TextBox will overlap with each other.

How to return a value only when "ok" is clicked

I have created a custimazibale prompt
public static class Prompt
{
public static string ShowDialog(int columnnumber, string columnname)
{
Form prompt = new Form();
prompt.Width = 500;
prompt.Height = 150;
prompt.FormBorderStyle = FormBorderStyle.FixedDialog;
prompt.Text = columnname;
prompt.StartPosition = FormStartPosition.CenterScreen;
Label textLabel = new Label() { Left = 50, Top = 20 };
ComboBox comboBox = new ComboBox() { Left = 50, Top = 50, Width = 400 };
comboBox.Items.AddRange(new string[] { "a","b","c" });
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox.SelectedItem = columnname;
Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 80 };
confirmation.Click += (sender, e) => { prompt.Close(); };
textLabel.Text = "Colonne " + (columnnumber + 1).ToString() + " : " + columnname;
prompt.Controls.Add(comboBox);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.AcceptButton = confirmation;
prompt.ShowDialog();
prompt.AcceptButton = confirmation;
return comboBox.Text;
}
}
then I call it in my main form when a header is clicked
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
dt.Columns[e.ColumnIndex].ColumnName = Prompt.ShowDialog(e.ColumnIndex, dataGridView1.Columns[e.ColumnIndex].Name);
}
The problem is my text change even if the button close is clicked.
But I want it to change only when the user click the button "OK".
You could evaluate the DialogResult and return null if it is not OK:
public static class Prompt
{
public static string ShowDialog(int columnnumber, string columnname)
{
using (Form prompt = new Form())
{
// other code
return prompt.DialogResult == DialogResult.OK ? comboBox.Text : null;
}
}
}
and then in your other method:
private void dataGridView1_ColumnHeaderMouseClick(object sender, EventArgs e)
{
var result = Prompt.ShowDialog(e.ColumnIndex,
dataGridView1.Columns[e.ColumnIndex].Name);
if (result != null)
dt.Columns[e.ColumnIndex].ColumnName = result;
}
And inside your prompt you should set the DialogResult accordingly:
confirmation.Click += (sender, e) =>
{
prompt.DialogResult = DialogResult.OK;
prompt.Close();
};
HINT: Instead of result != null you could also use !String.IsNullOrWhiteSpace(result) to only update the column name if something was entered.
I would go for something like this:
using(Form prompt = new Form())
{
//Initialize the components of your form
DialogResult result = prompt.ShowDialog();
if(result == DialogResult.OK)
{
//return whatever it is you want to return
}
}
Inside your form you can set the DialogResult via prompt.DialogResult = DialogResult.OK and some more options (DialogResult.Cancel, DialogResult.Retry etc.)
You can set a bool when it is confirmed, and use that to return null if it wasn't confirmed, like this:
public static string ShowDialog(int columnnumber, string columnname)
{
Form prompt = new Form();
prompt.Width = 500;
prompt.Height = 150;
prompt.FormBorderStyle = FormBorderStyle.FixedDialog;
prompt.Text = columnname;
prompt.StartPosition = FormStartPosition.CenterScreen;
Label textLabel = new Label()
{
Left = 50,
Top = 20
};
ComboBox comboBox = new ComboBox()
{
Left = 50,
Top = 50,
Width = 400
};
comboBox.Items.AddRange(new string[] { "a", "b", "c" });
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox.SelectedItem = columnname;
Button confirmation = new Button()
{
Text = "Ok",
Left = 350,
Width = 100,
Top = 80
};
bool confirmed = false;
confirmation.Click += (sender, e) =>
{
prompt.Close();
confirmed = true;
};
textLabel.Text = "Colonne " + (columnnumber + 1).ToString() + " : " + columnname;
prompt.Controls.Add(comboBox);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.AcceptButton = confirmation;
prompt.ShowDialog();
prompt.AcceptButton = confirmation;
return confirmed ? comboBox.Text : null;
}
Your calling code will need to check the return value for null, and only do something if the returned value is not null.

Mediaelement Playlist repeat how to?

I Can't find any solution how to reset the index when last file has been opened.
I have a mediaelement that reads images from a listbox and when last image has been played I want it to restart. Like a repeatable Mediaelement playlist.
Please help, I really need help with this one.
Dictionary<string, string> Listbox1Dict = new Dictionary<string, string>();
public static List<string> images = new List<string> { ".JPG", ".JPE", ".BMP", ".GIF", ".PNG" }; // Bildtyper som stöds
public static List<string> movies = new List<string> { ".WMV", ".WAV", ".SWF", ".MP4", ".MPG", ".AVI" }; // Filmtyper som stöds
List<string> paths = new List<string>();
DispatcherTimer dispatcherTimer = new DispatcherTimer();
DispatcherTimer NextImageTimer = new DispatcherTimer();
int x = 20; //Ställa in antal sekunder per bild
private int currentSongIndex = -1;
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
ShowNextImage();
}
private void dispatch()
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, x);
}
private void ShowNextImage()
{
if (currentSongIndex == -1)
{
currentSongIndex = Listbox1.SelectedIndex;
}
currentSongIndex++;
var selected = Listbox1.Items[currentSongIndex];
string s = selected.ToString();
if (Listbox1Dict.ContainsKey(s))
{
if (images.Contains(System.IO.Path.GetExtension(s).ToUpperInvariant()))
{
if (currentSongIndex < Listbox1.Items.Count)
{
mediaElement1.Visibility = Visibility.Visible;
SearchBtn.Visibility = Visibility.Hidden;
Listbox1.Visibility = Visibility.Hidden;
FileNameTextBox.Visibility = Visibility.Hidden;
mediaElement1.Source = new Uri(Listbox1Dict[s]);
mediaElement1.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
mediaElement1.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
this.Background = new SolidColorBrush(Colors.Black);
this.WindowStyle = WindowStyle.None;
this.WindowState = WindowState.Maximized;
mediaElement1.StretchDirection = StretchDirection.Both;
mediaElement1.Stretch = Stretch.Fill;
dispatcherTimer.Start();
}
}
else if (movies.Contains(System.IO.Path.GetExtension(s).ToUpperInvariant()))
{
if (currentSongIndex < Listbox1.Items.Count)
{
dispatcherTimer.Stop();
mediaElement1.Visibility = Visibility.Visible;
Listbox1.Visibility = Visibility.Hidden;
FileNameTextBox.Visibility = Visibility.Hidden;
mediaElement1.Source = new Uri(Listbox1Dict[s]);
mediaElement1.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
mediaElement1.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
this.Background = new SolidColorBrush(Colors.Black);
this.WindowStyle = WindowStyle.None;
this.WindowState = WindowState.Maximized;
mediaElement1.StretchDirection = StretchDirection.Both;
mediaElement1.Stretch = Stretch.Fill;
}
}
}
}
Cant you do something like:
private void ShowNextImage()
{
if (currentSongIndex == -1)
{
currentSongIndex = Listbox1.SelectedIndex;
}
if (currentSongIndex == ListBox1.Items.Count)
{
currentSongIndex = 0;
}
currentSongIndex++;
....
}

Easiest way to create a custom dialog box which returns a value?

I want to create a custom dialog box for my C# project. I want to have a DataGridView in this custom dialog box, and there will also be a button. When the user clicks this button, an integer value is returned to the caller, and the dialog box then terminates itself.
How can I achieve this?
There is no prompt dialog box in C#. You can create a custom prompt box to do this instead.
public static class Prompt
{
public static int ShowDialog(string text, string caption)
{
Form prompt = new Form();
prompt.Width = 500;
prompt.Height = 100;
prompt.Text = caption;
Label textLabel = new Label() { Left = 50, Top=20, Text=text };
NumericUpDown inputBox = new NumericUpDown () { Left = 50, Top=50, Width=400 };
Button confirmation = new Button() { Text = "Ok", Left=350, Width=100, Top=70 };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.Controls.Add(inputBox);
prompt.ShowDialog();
return (int)inputBox.Value;
}
}
Then call it using:
int promptValue = Prompt.ShowDialog("Test", "123");
On your button set the DialogResult property to DialogResult.OK
On your dialog set the AcceptButton property to your button
Create a public property in your form called Result of int type
Set the value of this property in the click event of your button
Call your dialog in this way
using(myDialog dlg = new myDialog())
{
if(dlg.ShowDialog() == DialogResult.OK)
{
int result = dlg.Result;
// whatever you need to do with result
}
}
public static DialogResult InputBox(string title, string promptText, ref string value,bool isDigit=false)
{
Form form = new Form();
Label label = new Label();
TxtProNet textBox = new TxtProNet();
if (isDigit == true)
textBox.TypeNumricOnly = true;
textBox.Width = 1000;
Button buttonOk = new Button();
Button buttonCancel = new Button();
form.Text = title;
label.Text = promptText;
textBox.Text = value;
buttonOk.Text = "OK";
buttonCancel.Text = "Cancel";
buttonOk.DialogResult = DialogResult.OK;
buttonCancel.DialogResult = DialogResult.Cancel;
label.SetBounds(9, 20, 372, 13);
textBox.SetBounds(12, 36, 372, 20);
buttonOk.SetBounds(228, 72, 75, 23);
buttonCancel.SetBounds(309, 72, 75, 23);
label.AutoSize = true;
textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
form.ClientSize = new Size(396, 107);
form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });
form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
form.MinimizeBox = false;
form.MaximizeBox = false;
form.AcceptButton = buttonOk;
form.CancelButton = buttonCancel;
DialogResult dialogResult = form.ShowDialog();
value = textBox.Text;
return dialogResult;
}
//combo box dialog c#
//
public static string DialogCombo(string text,DataTable comboSource,string DisplyMember,string ValueMember)
{
//comboSource = new DataTable();
Form prompt = new Form();
prompt.RightToLeft = RightToLeft.Yes;
prompt.Width = 500;
prompt.Height = 200;
Label textLabel = new Label() { Left = 350, Top = 20, Text = text };
ComboBox combo = new ComboBox { Left = 50, Top = 50, Width = 400 };
combo.DataSource = comboSource;
combo.ValueMember = ValueMember;
combo.DisplayMember = DisplyMember;
Button confirmation = new Button() { Text = "تایید", Left = 350, Width = 100, Top = 70 };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.Controls.Add(combo);
prompt.ShowDialog();
return combo.SelectedValue.ToString();
}
public partial class DialogFormDisplay : Form
{
public DialogFormDisplay()
{
InitializeComponent();
}
string dialogcode;
public void Display(string code, string title, string description)
{
dialogcode = code;
switch (code)
{
case "YesNo":
btnLeft.Text = "Yes";
btnLeft.BackColor = Color.ForestGreen;
btnLeft.ForeColor = Color.White;
btnRight.Text = "No";
btnRight.BackColor = Color.Red;
btnRight.ForeColor = Color.White;
break;
default:
break;
}
displayTitle.Text = title;
displayMessage.Text = description;
}
private void btnLeft_Click(object sender, EventArgs e)
{
dialogResultLeft(dialogcode);
}
private void btnRight_Click(object sender, EventArgs e)
{
dialogResultRight(dialogcode);
}
void dialogResultLeft(string code)
{
switch (code)
{
case "YesNo":
DialogResult = DialogResult.Yes;
MessageBox.Show("You pressed " + DialogResult);
break;
default:
break;
}
}
void dialogResultRight(string code)
{
switch (code)
{
case "YesNo":
DialogResult = DialogResult.No;
MessageBox.Show("You pressed " + DialogResult);
break;
default:
break;
}
}
}
You can check this out on https://github.com/gurvirlochab/CustomNotifications Here is a sample screenshot of the DialogBox

Categories