I have looked at various answers, i have googled my nut off for a good few hours now, and still cant seem to get this to work.
I am trying to update a textbox on a form. i have simplified the code i am using in the hope that it was just something i was adding unnecessarily, but still cant get it to work.
I know the text is being passed to the textbox and stored in the box, but it will not display in the actual box.
In form one (Form_DMM);
private void BtnTest_Click(object sender, EventArgs e)
{
ErrorHandling EH = new ErrorHandling();
EH.updatetbtest();
}
in separate class;
public void updatetbtest()
{
string FailedMessagePB = "Test Message" + "\n";
Form_DMM FormDMM = new Form_DMM();
FormDMM.TextBoxAppend(FailedMessagePB);
FormDMM.TextBoxAppend2 = FailedMessagePB;
FormDMM = null;
}
passed back to form one;
public void TextBoxAppend(string WriteMessage)
{
TB_Issues.AppendText(WriteMessage + "\n");
System.Windows.Forms.Application.DoEvents();
TB_Issues.Invalidate();
TB_Issues.Update();
TB_Issues.Refresh();
MessageBox.Show(TB_Issues.Text);
}
public string TextBoxAppend2
{
get
{
return TB_Issues.Text;
}
set
{
TB_Issues.Text = TB_Issues.Text + value + "\n";
System.Windows.Forms.Application.DoEvents();
TB_Issues.Invalidate();
TB_Issues.Update();
TB_Issues.Refresh();
MessageBox.Show(TB_Issues.Text);
}
}
As you can see i have two separate attempts at updating the textbox, neither of which will display the test message in the textbox, but the messagebox that pops up will show the test message. it will even show the double test message from the TB_Issues.AppendText().
Can someone please help and tell me where i'm going wrong. This is driving me insane!
you can use like this
public void updatetbtest(Form_DMM FormDMM)
{
string FailedMessagePB = "Test Message" + "\n";
FormDMM.TextBoxAppend(FailedMessagePB);
FormDMM.TextBoxAppend2 = FailedMessagePB;
}
and in your buttontest_Click
private void BtnTest_Click(object sender, EventArgs e)
{
ErrorHandling EH = new ErrorHandling();
EH.updatetbtest(this);
}
From the problem posted the error is in the ErrorHandling class.
In the method updatetbtest you create a new Insance of the form object. So you create a separate form object, change the text and then you lose any reference because you set the variable to null. The message box is displayed because the TextBoxAppend method is called and the messagebox is a separate instance. The new instance you create is never displayed.
You have to hand over your calling form instance to the updatetbtest method.
Something like this:
private void BtnTest_Click(object sender, EventArgs e)
{
ErrorHandling EH = new ErrorHandling();
EH.updatetbtest(this);
}
public void updatetbtest(Form_DMM form)
{
string FailedMessagePB = "Test Message" + "\n";
form.TextBoxAppend(FailedMessagePB);
}
You try to create new form. But you must use existing.
You can pass existing form calling EH.updatetbtest(this);
And of course adding parameter to declaration like updatetbtest(Form_DMM FormDMM). And delete declaration and new in the function body.
Related
Im currently trying to make an instant messaging application.
There is a client and a server. the server works perfectly but for some reason when I call a certain function to update the UI the TextBox doesn't get text added to it.
Below is an example of my code - The Update UI is called from a different form in my applicaiton:
public ChatWindow()
{
InitializeComponent();
Thread timerThread = new Thread(Main.ReceiveLoop);
timerThread.Start();
}
private void txtChatLog_TextChanged(object sender, EventArgs e)
{
}
private void btnSendMessage_Click(object sender, EventArgs e)
{
string clientReply = txtReply.Text;
string Message = "ClientMsg§" + clientReply;
var time = DateTime.Now;
txtChatLog.AppendText($"{time} client: {clientReply}");
txtChatLog.AppendText(Environment.NewLine);
Main main = new Main();
main.ChatResponse(Message);
txtReply.Text = "";
}
public void UpdateChatLog(string message)
{
var time = DateTime.Now;
string newMessage = message.Split('$')[1];
string messageToDisplay = $"{time} Server: {newMessage}";
MessageBox.Show(messageToDisplay);
txtChatLog.AppendText(messageToDisplay);
txtChatLog.AppendText(Environment.NewLine);
}
private void ChatWindow_Load(object sender, EventArgs e)
{
}
The client is defiantly receiving the message from the server as I checked with a messagebox.show();
Also when the send message button is pressed the rich textbox is updated. But for some reason it just wont update through the UpdateChatLog method.
Any Help would be really appreciated.
Thankyou advance!
From code which you have pasted, you don`t call UpdateChatLog method.
Try to add UpdateChatLog(message); to btnSendMessage_Click method.
Try refreshing textbox : txtChatLog.Refresh()
I am fairly new to Visual Studio and C# in general but basically I need to check that the contents of the textbox are valid before proceeding to add the contents to a list with a button.
I am using the following objects:
A TexBox to enter the value
A Validating event linked to the TextBox to validate the data.
A Button to take action
A Click event associated to the button.
The problem is that I cannot check if the values in the box are valid or not and prevent the click event in the button to happen. In other words if the contents are not valid then do not take action.
This is my code.
public partial class mainForm : Form
{
public mainForm()
{
InitializeComponent();
}
private void addButton_Click(object sender, EventArgs e)
{
// I need to check if the content is valid before adding it to the form
ListViewItem item = new ListViewItem(this.nameTextBox.Text);
this.listView1.Items.Add(item);
}
private void nameTextBox_Validating(object sender, CancelEventArgs e)
{
int maxCharacters = 15;
String err = "";
String contents = this.nameTextBox.Text;
if (contents.Length == 0)
{
err = "I am sorry but the name cannot be empty";
e.Cancel = true;
}
else if (!contents.Replace(" ", "").Equals(contents, StringComparison.OrdinalIgnoreCase))
{
err = "I am sorry but the name cannot contain spaces";
e.Cancel = true;
}
else if (contents.Length > 15)
{
err = "I am sorry, but the name cannot have more than " + maxCharacters + " characters";
e.Cancel = true;
}
this.mainFormErrorProvider.SetError(this.nameTextBox, err);
}
}
You are confused about when the "name" text boxes' validation method is called.
See here
When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Selector SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order...
So clicking the button has nothing to do with the validation of the text box.
What you need to do is put the validation logic in a separate method, and then call it from both events.
Also, since you're new to C# here are some pointers.
Namespaces, Classes, methods, and properties are supposed to be Pascal Case.
Instead of using a long winded work around like this
!contents.Replace(" ", "").Equals(nameText, StringComparison.OrdinalIgnoreCase)
You could simply use
contents.Contains(" ")
There are tons of useful methods just like that, so in the future you should do more research on what you need before implementing something yourself, especially if it seems like a commonly used technique.
Also, you want to avoid if/else's as much as possible in favour of returning early.
Here's what your class might look with better practice in mind
const int NAME_MAX_CHARACTERS = 15;
public mainForm()
{
InitializeComponent();
}
private void addButton_Click(object sender, EventArgs e)
{
if(!Validate())
{
return;
}
// I need to check if the content is valid before adding it to the form
ListViewItem item = new ListViewItem(this.nameTextBox.Text);
this.listView1.Items.Add(item);
}
private void nameTextBox_Validating(object sender, CancelEventArgs e)
{
e.Cancel = !Validate();
}
private bool Validate()
{
string nameText = nameTextBox.Text;
if(String.IsNullOrEmpty(nameText))
{
this.mainFormErrorProvider.SetError(this.nameTextBox, "I am sorry but the name cannot be empty");
return false;
}
if(nameText.Contains(" "))
{
this.mainFormErrorProvider.SetError(this.nameTextBox, "I am sorry but the name cannot contain spaces");
return false;
}
if (nameText.Length > 15)
{
this.mainFormErrorProvider.SetError(this.nameTextBox, "I am sorry, but the name cannot have more than " + NAME_MAX_CHARACTERS + " characters");
return false;
}
return true;
}
I am appending the string failing_client to a RichTextBox control named report_output_box in a WinForms app using C#.
Is there a to make that string clickable inside the RichTextBox control, then pass a string to the onclick method?
What are my options here?
Update: I need to be more specific. I do not want to open a URL on the OnClick action, but instead, call a function.
Sample Code:
//... code before this
//failing_client_list is list of servers
foreach (string failing_client in failing_client_list)
{
//link onclick will call a method w/ a string argument
report_output_box.LinkClicked += new
LinkClickedEventHandler(open_inet_window(failing_client));
report_output_box.AppendText(failing_client + "\n");
}
//code after...
//method it would call
private void open_inet_window(object sender, EventArgs e, string failing_client)
{
//create a window object (w/ window consturctor) and then open it
inet_clients_window inizzy_window = new inet_clients_window(failing_client);
inizzy_window.Show();
}
Thanks!
Please take a look at: http://www.codeproject.com/Articles/9196/Links-with-arbitrary-text-in-a-RichTextBox
The article describes a way to create custom links in a RichTextBox that do not start with http:// or ftp://.
Generally however, if you want to add links that do start with http://, then all you need to do is make sure that the property DetectUrls of the RichTextBox is set to true, then you must add a handler for the LinkClicked event.
Doing a little search on StackOverFlow, you will find a very good source: How can I make a hyperlink work in a RichTextBox?
Here is a quick example I made, notice that throug e.LinkText you can create a Switch() statement for example to then decide on what to do depending on the link URL value?
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
richTextBox1.LinkClicked += new LinkClickedEventHandler(richTextBox1_LinkClicked);
}
void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
{
MessageBox.Show("You clicked the link: " + e.LinkText);
}
private void Form1_Load(object sender, EventArgs e)
{
richTextBox1.AppendText("This is link1: http://www.google.com");
richTextBox1.AppendText("\nThis is link2: http://www.stackoverflow.com");
}
}
}
And dammit, I'm getting frustrated. I'm doing my first mini-game, I think the name in english is Tic-Tac-Toe, and so, I have a main menu where I choose the option 2 players, then i get a inputbox asking for the 2 players names (i used a visual basic reference) and store it in 2 variables that i send to my constructor (?). I'm potuguese so I don't really know how you guys call it, but I'll show you the code.
So, in the first Form, I have:
private void doisJogadoresToolStripMenuItem_Click(object sender, EventArgs e)
{
jogadorTempUm = Microsoft.VisualBasic.Interaction.InputBox("Jogador 1");
jogadorTempDois = Microsoft.VisualBasic.Interaction.InputBox("Jogador 2");
jog = new DoisJogadores(jogadorTempUm, jogadorTempDois);
DoisJogadores novoDois = new DoisJogadores();
novoDois.ShowDialog();
}
That gets sent to the other Form:
public DoisJogadores(string teste1, string teste2)
{
jogador1 = teste1;
jogador2 = teste2;
}
And I save it in the class:
private string jogador1
private string jogador2
And the values get saved there. But I tried to place them in a textbox to show the players names and it just goes blank.
Anyone that can help me?
You are showing not that form which you are passing values to. Here is a fix
private void doisJogadoresToolStripMenuItem_Click(object sender, EventArgs e)
{
jogadorTempUm = Microsoft.VisualBasic.Interaction.InputBox("Jogador 1");
jogadorTempDois = Microsoft.VisualBasic.Interaction.InputBox("Jogador 2");
// pass values to form you are creating
DoisJogadores novoDois =
new DoisJogadores(jogadorTempUm, jogadorTempDois);
novoDois.ShowDialog();
}
Also make sure you are assigning jogador1 and jogador2 to textboxes. E.g. you can subscribe to form's load event in DoisJogadores form:
private void DoisJogadores_Load(object sender, EventArgs e)
{
textbox1.Text = jogador1;
textbox2.Text = jogador2;
}
I have a main Form with an event to open another Form.
Inside the first Form I define the event like this:
private void softToolStripMenuItem_Click(object sender, EventArgs e)
{
_frmSetting = new frmSetting();
_frmSetting.ShowDialog();
}
The event open a Form in the Dialog box. Everything is ok.
Inside the Form2 before the InitializeComponent();, I want to change the content of a TextBox on the Form 2.
So I do this this.textBox1.Text = "New text"; but it didn't work then I output to console:
this.textBox1.Text = "New text";
System.Console.WriteLine(this.textBox1.Text);
But this takes effect when immediately when the Form1 starts..I can see the console output.
Normally the Console output were supposed to ve viewed only when I call Form2.
Does someone understand my needs?
EDIT
public form2()
{
InitializeComponent();
try
{
this.txtServer = new TextBox();
//this._parameter = new Parameter();
//this._get_parameter = new Dictionary<string, string>();
String _server_name;
//this._parameter.get_db_connection_parameters().TryGetValue("server", out _server_name);
this.txtServer.Text = _server_name.ToString();
System.Console.WriteLine(txtServer.Text + "---");
}
catch (Exception er) { System.Console.WriteLine("An error occurs :" + er.Message + " - " + er.StackTrace); }
}
Please don't bother about the commented lines, it works _server_name variable is getting its value from a text file and it works at this stage. The problem is around this line:
this.txtServer.Text = _server_name.ToString();
You're overcomplicating this. First, as others have said, you can't do it before the call to InitializeComponent. Also, you don't need to create a new text box after the call to InitializeComponent. Once that method has been called, the txtServer text box will already be created and properly initialized. All you need to do then is set the value of its Text property:
public form2()
{
InitializeComponent();
try
{
String _server_name;
// set value of _server_name
txtServer.Text = _server_name;
}
catch (Exception er) { System.Console.WriteLine("An error occurs :" + er.Message + " - " + er.StackTrace); }
}
You can't set any values to textbox before initializeComponent();. If you look into initializeComponent function, you will see, that it does initialize all controls added in designer and your textbox as well.
You can't set the TextBox.Text property before initialisation, it will fail, that's it.
Many thanks to all,
everything works fine now. In fact, I was initialising Form2 in Form1() constructor and was getting this error Object reference to non object initialising (something like that).
I move it here:
private void softToolStripMenuItem_Click(object sender, EventArgs e)
{
_frmSetting = new frmSetting();
_frmSetting.ShowDialog();
}
and now inside the Form2() after initializeComponent()
I just do this
this.txtServer = _server_name;
and it works