I'm working on setting up a login form for an existing application. I'm currently having issues with getting the value of one of the text boxes in a class.
For example Form9 has a textbox called txtchannel. I'm wanting to get the value of what's in txtchannel in the class.
// Revision
I was finally able to get it to take the command using the following
// Class
private void DoConnect()
{
try
{
jtvClient.Connect();
jtvClient.JoinChannel("#" + this.mainForm.txtChan.Text);
}
catch (Exception ex)
{
op.Post(x => OnExceptionThrown((Exception)x), ex); // TODO: double check that exceptions
} // actually show up at this level
}
private Login mainForm = null;
public JtvClient(Login derp)
{
mainForm = derp as Login;
}
////
This is allowing me to at the very least call the what is in Login(Now Formally Form9). However it gives an error "Object reference not set to an instance of an object.". I'm at a complete loss.
I think the Text property of the TextBox class is what you are looking for. See MSDN for the full documentation on TextBox.Text.
The best way to get the value in another class (if you mean another class), is to expose a property called Channel in Form9. The would look like this:
public string Channel
{
get
{
return txtChannel.Text;
}
}
Related
Wanted to know how to get caller information for a property
for a method it is easy
public void TraceMessage([CallerMemberName] string memberName = "") {
Console.Println(memberName);
}
and you will get who called the method.
I want the same thing for a property
public MySqlConnection Connection { get; set; }
I tried getting the caller name by calling a function from the getter like this
public Connection connection { get { TraceMessage()
return _someVariable;}
set; }
But by doing this the TraceMessage prints
Connection
as the method name
Is there any way to either pass a parameter to the getter or something else to achieve this?
You get the name of the property because it is the previous method in the stack trace. To trace it in the property you can use System.Diagnostics.StackTrace:
using System.Diagnostics;
.
.
public Connection connection
{
get
{
Console.WriteLine(new StackTrace().GetFrame(1).GetMethod().Name);
return _connection;
}
}
Example can be found in this link
Furthermore if you want to create a separate method for that you can create a method that gets the frame before the frame. The frames are indexed so that current method/property frame is 0, the caller is 1, caller of the caller is 2 and so forth.
public void LogCaller()
{
Console.WriteLine(new StackTrace().GetFrame(2).GetMethod().Name);
}
And then call that method from the property.
I'd like to trigger a method every-time a value is changed in my list.
The top answer on other questions related to this is to use a property, which I have (example below)
However, I think it would help me prevent any accidental bugs if I deny anything other than that property having access to the 'core' list it changes (for lack of better understanding what the term is) .
Below is my example property with a get and set accessor.
private List<Things>myPrivateList; // Only the Property should be able to access
private List<Things>MyPrivateList // Only the class its in can touch this
{
get { return myPrivateList; }
set
{
myPrivateList = value;
coolMethodThatNeedsToRunEverytime();
}
}
public List<Things>getMyPrivateList // Any class outside can read this
{
get { return myPrivateList; }
}
I might be going about this the wrong way though, it would useful to know if you have any suggestions for what I'm trying to achieve. Thanks very much in advance for any advice / example you may have.
You can do what you want with one property :
public List<Things>MyPrivateList // Only the class its in can touch this
{
get { return myPrivateList; }
private set
{
myPrivateList = value;
coolMethodThatNeedsToRunEverytime();
}
}
Doing this, the setter will be private and the getter public
I have a method created in class1 called method1.
Im trying to display method1 in a label object. Hopefully I described this properly. Any help would be appreciated. Thanks in advance.
Here is my class Ticket User.
//property accessors
public string CreateAccountMessage
{ get{
return "Congratulations" + firstName + "Your account has been created. Your username is" + username;
} set
{ CreateAccountMessage = value;
}
}
//CreateAccount method
public string CreateAccount()
{ return CreateAccountMessage;
}}}
This is where i need to return CreateAccountMessage
protected void btnCreateAccount_Click(object sender, EventArgs e)
{
lblsomelabel.Text = TicketUser. (this is where it only shows Equals and ReferenceEquals
}
ok there are a few issues - on the property set for CreateAccountMessage, CreateAccountMessage = value is setting the property, you almost certainly want a private variable and a full property here...read here for more info on properties
Though I think your real issue is that you are trying to access a static functions of the class TicketUser - when it should be a normal instance method call -
e.g. you should be able to do the following in code:
TicketUser user = new TicketUser ();
user. (and then intellisense will kick in)
The fact you have no intellisense is because you are accessing the class directly (and its static methods, which don't match) - you probably need to re-think your architecture - maybe passing the instance in as a field of a custom event arg
Could I add some custom control to the standard Message Box for read input value, for example text fields for user name and password, or I should create custom winform with "Ok,Cancel" buttons and text fields?
Related: Which control to use for quick text input (inputbox)?
you can use the Interaction.InputBox method wich is located in the Microsoft.VisualBasic namespace
try this
Microsoft.VisualBasic.Interaction.InputBox("Enter a Value Here", "Title", "Your Default Text",200,100);
You will need to create a custom WinForm to do this. You can make it work the same way as a MessageBox by returning a DialogResult on the Show method.
Create your own.
Creating a custom modal (or otherwise) input dialog isn't all that difficult and you can built the extensibility you need for reuse.
public class ValueHolder {
public string SomeInput { get; set; }
public DialogResult Result { get; set; }
}
public class GimmeValues : Form {
//... HAS A TEXTBOX and Okay Buttons...
private GimmeValues() {
okButton.DialogResult = DialogResult.OK;
cancelButton.DialogResult = DialogResult.Cancel;
// ... other stuff
}
public static ValueHolder GetInput(IWin32Window owner) {
using (GimmeValues values = new GimmeValues()) {
DialogResult result = values.ShowDialog(owner);
return new ValueHolder {
SomeInput = values.Textbox1.Text,
Result = result
};
}
}
}
Okay I just wrote that all in this editor so forgive any syntax mistakes.
You could do something like the above but clean it up a little, add the extensibility you need (in terms of buttons and inputs showing that you need etc)... then just call it like ValueHolder value = GimmeValues.GetInput(this); where this would represent an IWin32Window...
The resulting value of value would be the selected nonsense and you could perform your logic..
if(value.Result == DialogResult.OK && !string.IsNullOrEmpty(value.SomeInput)){
//TODO: Place logic....
}
You'll have to create a custom form to handle that.
If you want the Form to behave like MessageBox, just create a static Show() method on your Form that creates an instance and shows the box to the user. That static method can also handle returning the values you are interested in from your custom form (much like DialogResult).
I want to create an error class. And it has some static properties. For example : Message, InnerException, Stacktrace, Source. But I want to add some dynamic properties.
If exception is a FileNotFoundException, I want to add FileName property.
Or if it is a SqlException, I want to add LineNumber property. And I can't inherit that class from Exception because, I return that class from a web service. How can I do that?
C# is a statically typed language. This means you generally cannot dynamically add properties to classes at run-time without some really funky IL injection (which you definitely want to avoid).
In your case it seems that you need to understand exceptions a bit better - we usually throw a specific type of exception to indicate the cause of an exceptional problem. For example, if you are looking for a file and it's not there you would throw a FileNotFoundException or if there is some application-specific problem you could create your own exception class and throw that exception.
Keep in mind that exceptions should be exceptional.
Instead of trying to do something C# currently doesn't handle very well, I suggest you take a somewhat different approach.
Why don't you add those extra properties as data in a dictionary? Your class could expose an interface to get a number of "properties" (in the general sense of the word), i.e. the keys and your calling code could then examine these and use them to look up values as necessary.
you can create type dynamically using new features in C# like anonymous types
I am not sure if you are trying to do some thing similar, but can achieve the requirement as follows
public interface IError { }
public class ErrorTypeA : IError
{ public string Name; }
public class ErrorTypeB : IError
{
public string Name;
public int line;
}
public void CreateErrorObject()
{
IError error;
if (FileNotFoundException) // put your check here
{
error = new ErrorTypeA
{
Name = ""
};
}
elseif (InValidOpertionException) // put your check here
{
error = new ErrorTypeB
{
Name = "",
line = 1
};
}
}
Hope this helps
My take on this would be to use a dictionary where you can store all extra data.
public class Logging
{
private Dictionary<string, string> _ExtraInfo = new Dictionary<string, string>();
public Dictionary<string, string> ExtraInfo {
get { return _ExtraInfo; }
set { _ExtraInfo = value; }
}
}
To use:
Logging MyLogger = new Logging();
MyLogger.ExtraInfo.Add("Filename", thefilename);
MyLogger.ExtraInfo.Add("ClientTime", now);
And so on.
It's very unclear what you're trying to achieve. Reconsider your design in favor of non-static classes and use inheritance.
And you do remember that there are lots of ready-made exception classes in the .NET BCL, right?
Create a new exception type, derived from Exception. Throw this exception, and set the InnerException property to the exception that caused all the ruckus.
You can check for the type of the inner exception and display data accordingly.
If possible, you could of course also just throw the original excpetion to have the caller handling it.