i want to write a program that somehow is like a designer where user can add textbox on the form and everything the user put into those textbox can be saved (like a setting) and after closing and opening the form again textboxs' text will remail unchanged.
so i decided to make a setting in project->settings and then make an array of it in my code.
but whenever i want to access my settings it gives me an exception:
"An unhandled exception of type 'System.NullReferenceException' occurred in FormDesigner.exe"
here is my code from defining the array:
Settings[] formsetting=new Settings[3];
and here is my code for handling the textchanged event for everytext box:
(i use the textboxs' tag to match the settings index with every textbox)
void t_TextChanged(object sender, EventArgs e)
{
TextBox temp = (TextBox)sender;
int s =(int) temp.Tag;
string str = temp.Text;
frmsetting[s].text = str;
}
the last line is where i get the error.
could someone explain to me what is the problem and how to fix it?
and if my way is wrong could you please show my another way of doing this.
thanks
You haven't initialized the objects in the array.
Doing this:
Settings[] formsetting = new Settings[3];
..creates the array. All 3 are null though. Do this:
var formsetting = new Settings[3] {
new Settings(),
new Settings(),
new Settings()
};
While you are initializing your array, you are not actually initializing any of the values. What you have currently is equivalent to the following:
Settings[] formsetting=new Settings[3];
formsetting[0] = null;
formsetting[1] = null;
formsetting[2] = null;
You need to initialize the value at the index you want to use before doing anything with it.
Related
Below is my current code for my winforms app. Here the user will click the button and then the system will land on a specific index to an array and then print to the text box the contents of that index in the array. The "if" statement is where I am trying to match a specific background image to the specific index. Below in my test "if" statement I am trying to match a specific image in my resource file but I can't seem to figure out what to set the bool to match. I have tried "if(Map_Text="Woods")" which I get CS0029 error. Any tips or online guides I can review?(I apologize if I mis-said anything I am new to coding)
private void button1_Click(object sender, EventArgs e)
{
int start1 = random.Next(0, Map_Array.Length);
Map_Text.Text = Map_Array[start1];
if(Map_Text = "Woods")
{
this.BackgroundImage = Properties.Resources.Woods;
}
}
In your if statement, you're attempting to assign the string "Woods" to Map_Name, which is the reason you're getting CS0029 (which means that the compiler can't implicitly convert the two types.)
Additionally, you'd need to check the Text property of Map_Name instead of checking Map_Name directly, as you're assigning the result of your random selection to that property above your if statement.
if (Map_Text.Text == "Woods") {
this.BackgroundImage = Properties.Resources.Woods;
}
EDIT - Sorry folks, i guess i wanted to "obscure" my work code too much... i don't know why it got so many downvotes but anyway. see below for update/edit with actual code.
I am trying to insert a piece of text into an existing section of a line (<data) which resides at the beginning of a line in my RichTextBox control. However, whenever i do that in the following manner:
private void AddSelectedIntellisense(object sender, EventArgs e)
{
ToolStripItem x = sender as ToolStripItem;
int cursorpos = this.txt_Body.SelectionStart;
string final = this.txt_Body.Text.Insert(cursorpos, x.Text);
//final var at breakpoint is equal to "<data log=\"Original\""
//then i assign it/that to the RTB.Text
this.txt_Body.Text = final;
//when checked with breakpoint, this.txt_Body.Text is equal to
//"log=\"\"<data log=\"Original\""
this.txt_Body.SelectionStart = cursorpos + x.Text.Length;
}
I am thinking that it is the < character that is causing issues when i assign the string to the .Text property (because if i replace the < with a [ in my logic, no problems), but i don't know how to fix it... if you could help me i would really appreciate it.
I also checked all of the indexes manually and they all lign up perfectly... so i don't know why the RTB.Text value is different than the string but if someone knows please tell me.
Cheers!
You are first setting:
txt = this.RTB1.Text.Substring(starts, length);
Then on the next line you are replacing the value of txt:
txt = this.RTB1.Text.Insert(index,"log='test'></data>");
You are probably looking to concatenate the strings:
string txt = this.RTB1.Text.Substring(starts, length);
txt += this.RTB1.Text.Insert(index,"log='test'></data>");
this.RTB1.Text = txt;
Ok folks... i suppose i'll give it to Aaron, since it's like somewhat related and nobody else answered.
The answer was:
I am using the RTB.On_TextChanged event to fire off the intellisense based on a condition. However, because i am also setting text the RTB.Text value within the Intellisense, the condition became true twice and added the specific text twice. So i setup a flag when i add intellisense text and check it in the on_textchanged event.
Cheers and sorry for the confusion.
I got stuck here,
i have dynamic table that i want to print. So i make session to pass it into web control.
Unfortunately, it doesn't run smooth.
Here are my code :
protected void bt_print_click(object sender, EventArgs e)
{
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
panelBilling.RenderControl(w);
string s = sw.GetStringBuilder().ToString();
Session["ctrl"] = s;
ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx?rep=1','PrintMe','height=680px,width=1024px,scrollbars=1');</script>");
}
And the Print.aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
Control ctrl = (Control)Session["ctrl"];
PrintHelper.PrintWebControl(ctrl);
}
I always got error message :
"Unable to cast object of type 'System.String' to type
'System.Web.UI.Control'."
on
(Control)Session["ctrl"]
part. I have use this method many time and no problems before. Anyone has any idea? Thanks.
This just doesn't make sense, casting a string value to a Control.
As far as I can see, you are not inserting a Control into the Sessiosn, not even the Control.ToString() value, which also wouldn't be working.
Before continuing, it might be usefull to check which type is retrieved from the Session without casting anything (remark: this is only possible with .NET 3.5 or higher):
var sessionValue = Session["ctrl"];
When doing so, you will find out the value is of type object, containing the value:
"<div>\r\n\r\n</div>"
The above output is not a Control, but a string/html value.
There are two solution paths which u can follow:
Change the "SET" call on the Session
Change the "GET" call on the Session
In the second example, you keep to the fact that you are inserting a string and therefor you would like to read out that string value:
string sessionValueAsString = string.Empty;
Object sessionValue = Session["ctrl"];
if (sessionValue != null)
sessionValueAsString = sessionValue.ToString();
The above example could suit ur needs, never the less I'm guessing you are in the need to save an object of type "Control" in the session. This can be achieved like so:
MyControl myControl = new MyControl {Title = "My custom control"};
Session["myControl"] = myControl;
// Read the Session value cross Postback
MyControl mySessionControl = (MyControl)Session["myControl"];
Apart from the above example, I'm not 100% sure what you are trying to do.
My guess is you made a mistake inserting the wrong value in the Session.
One remark: I'm not a fan of storing the WebControls in the session, it would be cleaner to store your data objects in the Session (e.g. store a Customer class instead of the CustomerUserControl, this way you can read out the Session and populate the required controls using the data found in the Session).
I am having problems deserializing a xaml file and get the following error
My code is as follows:
private void SerializeToXML()
{
FileStream filestream = File.Create(#"H:\test1.xaml");
StreamWriter streamwriter = new StreamWriter(filestream);
foreach (ListViewItem Item in slideListView.Items)
{
string mystrXAMLWrite = XamlWriter.Save(Item.Tag);
streamwriter.Write(mystrXAMLWrite);
}
streamwriter.Close();
filestream.Close();
}
private void DeSerialize()
{
FileStream filestream = File.Open(#"H:\test1.xaml", FileMode.Open);
XamlReader reader = new XamlReader();
slideListView = (ListView)reader.LoadAsync(filestream);
}
If I go to the XAML file after saving and change the various names it has problems with, for example changing slideCanvas to slideCanvas1 and ContextMenu to ContextMenu1, then it will load. But obviously this is not a solution and it also means that whatever is loaded back in is not pointing to the correct bits of code as they have had numbers added to the values.
Does anyone know what I need to do here?
UPDATED
Here is the xaml produced when saving one slide object
<Slide imageZIndex="0" editText="False" ClipToBounds="True" xmlns="clr-namespace:StoryboardTool;assembly=StoryboardTool" xmlns:av="http://schemas.microsoft.com/winfx/2006/xaml/presentation"><av:Canvas Background="#FFFFFFFF" Name="slideCanvas" /></Slide>
If I try to place this in a Slide Object for example
Var obj = (Slide)reader.LoadAsync(filestream);
I get this XmalParseExceptionOccured problem.
The error says cannot register duplicate name 'slideCanvas' in this scope. I can only assume that you have another control called 'slideCanvas' that is defined in your application somewhere. Have you tried searching through the entire solution for 'slideCanvas'?
Other than that, there are a few other issues that cause this exception:
Declaring a control in the Resources section using x:Name instead of x:Key.
Trying to serialize a control that has code behind.
You could also try simply removing the names from the controls and binding to them to replicate whatever functionality you named them for.
If you still have a problem, please show the XAML that is causing the error when you try to deserialize it.
How I solved this:
1. Make user control which inherits from your control
2. Add this in the constructor
static int counter = 0;
public TestControl()
{
InitializeComponent();
this.Name += counter.ToString();
counter ++;
}
in my Win Forms app I create an array of dynamic custom controls inside a loop. These, lets call them 'boxes', are like my basic pieces of information. I also create string arrays in other parts of the code that contain the information of this 'boxes', so that for example string[3] is a variable of box[3] and so does stringa[3], stringb[3], stringc[3]... all the arrays with the same index are related to the box with that index. Hope I make myself clear.
Only 2 of this strings are shown in 2 labels inside each custom control 'box' in the array, but the others are there because I want to make something so that when the user clicks one of these controls the other strings can be shown in another control. Sort of something like "More Information...". All the 'boxes' in the array need to have the same event handler because I create +100.
To put it more into context, each custom control 'box' in the array shows the Symbol and the Price of a stock and I want that when the user clicks on each stock more quote information is shown on another special control which is like a placeholder for "More info".
I am thinking of 2 ways to do it:
If I could "detect" the index of the clicked control (which is the same in the strings related to it), I could just set this to an int j and all I have to do is show all the strings a,b,c... with index j. Unfortunately I cannot find a way to do this, maybe it is not even possible.
The other way I have thought is to create some properties for my custom control which "store" this variables, and in my app instead of assigning strings I would set properties for each control, which I could later retrieve when the control is clicked. I haven't tryed this because I don't know exactly how to do it.
What do you think? Do you know how can I achieve this or do you have a different idea that will work? Please help! Thanks in advance.
It's kind of a broad implementation question since there are countless ways you could implement something like this.
If you are creating two collections, one with the buttons and one with the information, you potentially could just assign each of the buttons 'Tag' properties to point to the corresponding info and assign a generic OnClick event handler that displays the info.. something like:
infoControl.text = ((InfoClass)((Button)Sender.Tag)).pieceOfInformation;
But again there are many ways to do this, and the choice comes down to how you store your information.
For your first method, you could have a property of your custom control that is the index.
public class Box : Control
{
// ...existing code
private int index;
public int Index
{
get
{
return index;
}
set
{
index = value;
}
}
}
OR
For your second method, you could have a property of your custom control that is the additional info string.
public class Box : Control
{
// ...existing code
private string extraInfo;
public string ExtraInfo
{
get
{
return extraInfo;
}
set
{
extraInfo = value;
}
}
}
In either case, you could then access the proper information right in your click handler for the "box".
i don't know about the first way - got to noodle around more, but in the second way you can extended your custom or built-in control: for example:
public class ExtendedLabel: Label
{
public string[] MoreInfo { get; set; }
}
and initialize it
public TestForm()
{
InitializeComponent();
ExtendedLabel label = new ExtendedLabel();
label.MoreInfo = new string[] { "test" };
this.Controls.Add(label);
label.AutoSize = true;
label.Location = new System.Drawing.Point(120, 87);
label.Name = "label1";
label.Size = new System.Drawing.Size(35, 13);
label.TabIndex = 0;
label.Text = label.MoreInfo[0];
}
And later in your event handler you can use the inside information