How to use a string in an if statement with properties Settings? - c#

I am currently working in winforms c#. I have a string "Flippo1SN" and that string is determined in my form. "Flippo1SN" can change in 'serial number names' that matches the same name as in Properties.Settings . The value of the serial numbers in Properties.Settings are integers. I want to use an if statement without summing up all the integers in my Properties.Settings, instead, I want to use a string so I could write my code in 1 if statement instead of more. I tried to use a code like this:
if (Properties.Settings.Default.Flippo1SN == 0) {}
Which, as you may have guessed, did not work. I've tried more ways as:
if (Properties.Settings.Default.(Flippo1SN) == 0) {}
if (Properties.Settings.Default.("Flippo1SN") == 0) {}
if (Properties.Settings.Default.[Flippo1SN] == 0) {}
if (Properties.Settings.Default.["Flippo1SN"] == 0) {}
It gives me an error saying that there is an indentifier expected.
How can I solve this? This question may have already been asked in the past but I couldn't find it.
Thanks in advance.
Edit 1:
Flippo1SN Does not exist in Properties.Settings, it is its value that does. Its value is something like: GF01, GF02, ... I am trying to refer to those.
Edit 2:
These are the variables I am trying to refer to. Flippo1SNs name changes to GF01 or GF02 etc. I don't want to put a code like this:
if (Flippo1SN == "GF01")
{
if (Properties.Settings.Default.GF01 == 0) {//Do action}
}
Instead, I want to refer to GF01 immediately by using Flippo1SN in the second if statement. That would cost me a lot of time and writing because I have a lot of Integers in Properties.Settings .
Edit 3
I'm going to explain what I am creating so you guys understand what I'm doing.
I am creating a 'Collecting Game' where you collect Flippos (Pogs or milk caps is what it's called in English I guess?). To get those Flippos, you open a giftbox and receive 3 random flippos. The output is something like this:
Screenshot ("Verzamel" means collect)
In this image, you see 3 flippos. In the top left corner, you see the Serial Numbers of each flippo (MF06, GF16, OF12). 'MF' stands for 'Mega Flippo', 'GF' for Green Flippo and 'OF' stands for 'Orange Flippo'.
In the code, I have used random to choose which one you get (50% chance for green, 30% chance for orange and 20% chance for mega. The percentage is determined by the amount of a specific group). I have also 3 strings in my code that holds the serial number of these flippos (Flippo1SN, Flippo2SN, and Flippo3SN). These serial numbers refer to the ones in my database (or just the properties.settings tab). In this scenario, MF06, GF16 and OF12 increments by 1.
Now, I want to check if you've received a flippo you didn't have before. If you do so, a label will appear above the picture and the text of that label will be "New".
To do so, I first need to check which one you have received, then check if you already have that in your database. The first if checks if you have received GF01 and the second if checks if you already have it:
if (Flippo1SN == "GF01")
{
if (Properties.Settings.Default.GF01 == 0)
{
label1.Show();
}
}
else if (FLippo1SN == "GF02") {//ETC}
Flippo1SN is already determined. I am not trying to change the Flippo1SNs value. I am just using this string to check which flippo you have received. All flippos have a serial number and Flippo1SN holds a serial number to refer to which flippo you have received.
What I now am asking is, is there a more fast way to do this? Can't I use the value of Flippo1SN immediately in an if statement so I could avoid multiple if statements?
I really hope I made things clear now.

First you have to check if it exists then you can do whatever you want with it:
if(Properties.Settings.Default.ContainsKey(Flippo1SN))
{
if(Properties.Settings.Default[Flippo1SN] == 0)
{
// ....
}
}
You can also write handlers to get rid of the if checks:
interface ISettingsHandler
{
void Handle(int value);
bool CanHandle(string name);
}
class GF1Handler : ISettingsHandler
{
public void Handle(int value){
// do action
}
public bool CanHandle(string propertyName){
return propertyName.Equals("GF1");
}
}
class GF2Handler : ISettingsHandler
{
public void Handle(int value){
// do action
}
public bool CanHandle(string propertyName){
return propertyName.Equals("GF2");
}
}
You can then initialize a list of handlers, and use the one that can handle the selected property:
var handler = listOfHandler.FirstOrDefault(h => h.CanHandle(Flippo1SN))
if( != null)
handler.Handle(Properties.Settings.Default[Flippo1SN]);

By using Properties.Settings.Default you can retrieve all the properties in your Project.
Then, by iterating through them you can check the Name of each property to see if it matches your Flippo1SN like so:
string Flippo1SN = "GF02";
var props = Properties.Settings.Default;
foreach(var prop in props.Properties)
{
var settingProperty = (SettingsProperty)prop;
if (settingProperty.Name == Flippo1SN)
{
// Now you found the property that matches Flippo1SN.
// Get its value.
var value = settingProperty.DefaultValue;
}
}
Edit:
How to check if value of the property is zero:
string Flippo1SN = "GF02";
foreach (SettingsProperty prop in Properties.Settings.Default.Properties)
{
if (prop.Name == Flippo1SN)
{
if (int.TryParse(prop.DefaultValue.ToString(), out int result))
{
if (result == 0)
{
// The value is zero.
}
}
}
}

EDIT: NEW CODE AND SCREENSHOTS
using System;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
dynamic props = Properties.Settings.Default;
string Flippo1SN = "200";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string output = "Properties.Settings.Default.test : ";
if (Flippo1SN == props.test.ToString())
{
output += $"{props.test}";
}
if (Flippo1SN == props.test2.ToString())
{
output += $"{props.test2}";
}
if (Flippo1SN == props.test3.ToString())
{
output += $"{props.test3}";
}
MessageBox.Show(output);
}
}
}

Related

(Unity)How to pass variables, that are variable without a bunch of If Else Statements

for (int m = 0; m < materialObjects.Length; m++)
{
for (int i = 0; i < materialModifiers.Count; i++)
{
if(materialModifiers[i].valueType == LittleSubstanceModifier.ValueType.Float)
{
if (materialModifiers[i].valueFloat[0] != materialModifiers[i].oldValueFloat[0])
{
materialObjects[m].material.SetFloat(materialModifiers[i].identifier, materialModifiers[i].valueFloat[0]);
materialModifiers[i].valueFloat = materialModifiers[i].oldValueFloat;
}
}
else if (materialModifiers[i].valueType == LittleSubstanceModifier.ValueType.Float2 || materialModifiers[i].valueType == LittleSubstanceModifier.ValueType.Float3 || materialModifiers[i].valueType == LittleSubstanceModifier.ValueType.Float4)
{
if (materialModifiers[i].valueFloat != materialModifiers[i].oldValueFloat)
{
materialObjects[m].material.SetFloatArray(materialModifiers[i].identifier, materialModifiers[i].valueFloat);
materialModifiers[i].valueFloat = materialModifiers[i].oldValueFloat;
}
}
else if (materialModifiers[i].valueType == LittleSubstanceModifier.ValueType.Int)
{
if (materialModifiers[i].valueInt != materialModifiers[i].oldValueInt)
{
materialObjects[m].material.SetInt(materialModifiers[i].identifier, materialModifiers[i].valueInt[0]);
materialModifiers[i].valueFloat = materialModifiers[i].oldValueFloat;
}
}
else if (materialModifiers[i].valueType == LittleSubstanceModifier.ValueType.Int2 || materialModifiers[i].valueType == LittleSubstanceModifier.ValueType.Int3 || materialModifiers[i].valueType == LittleSubstanceModifier.ValueType.Int4)
{
}
else if (materialModifiers[i].valueType == LittleSubstanceModifier.ValueType.Bool)
{
}
else if (materialModifiers[i].valueType == LittleSubstanceModifier.ValueType.ColorField)
{
}
else if (materialModifiers[i].valueType == LittleSubstanceModifier.ValueType.Vector2)
{
}
else if (materialModifiers[i].valueType == LittleSubstanceModifier.ValueType.Vector3)
{
}
else if (materialModifiers[i].valueType == LittleSubstanceModifier.ValueType.Vector4)
{
}
}
}
I'm making a tool right now, and the user is able to pick a variable type that the user can edit in the inspector window.
To pick the variable I'm using an Enum, but then to check which type of variable they chose, I'm using a bunch of Else Ifs. Now to pick the variable, its ok doing it with Else If, but when it comes time to changing the value I can't be doing 10 else ifs every time they add a letter, or change a number.
So my question, how can I pass the variable type that is selected, without finding out what they chose without a bunch of else ifs? It would be nice if I could use var, but it is being changed from another script.
Sorry for the long sloppy post, I really don't know what to call this and how to ask.
Edit: Here is my code, what would be a better way of doing this?
Edit2: Response to Robyn - I just wrote that code for an example, its basically the only way I would know how to do this. Sorry, I will try to explain as best I can.
In the image I posted, there is the Identifier text box, which has opacity in it.
Then the drop down with all the variable types. Then it has a text box. You hit the button add Mod, and a row of those pops up. You pick either your variable type, put in the materials identifier (example opacity). So to change opacity it needs to be a float. So when you change the float boxes value, it will change the materials opacity.
I basically need a value, that can be used as a float, int, bool, etc...
I've never used Switch or Case, so I don't really know what it does exactly. But I will look it up try! So Thanks.
I just uploaded 2 more images trying to visually explain it a little better.
Tool
Code
You only need to check the type when the selected element changes.
enum SupportedTypes
{
Color,
Int
}
SupportedTypes selectedType;
void OnEnable()
{
// If the user still didn't select anything, select Int
selectedType = SupportedTypes.Int;
// See below to know what this is
methodUsedToDrawTheLastPart = DrawIntChooser;
}
// One field for each type
// Not elegant but we don't know the type beforehand
Color colorValue;
int intValue;
// ...
// Delegate defining a method signature: in this case "void XXX(string)"
delegate void SetValue(string propertyId);
// Instance of the delegate: think of it as a pointer to a method
// with the signature defined earlier
// You can set this field to any method being "void XXX(string)"
SetValue methodUsedToDrawTheLastPart;
// Then One method to draw each property chooser
// They will just draw the last part of the modifier
void DrawColorChooser(string propertyId)
{
Color newColorValue = EditorGUILayout.ColorField(colorValue);
if (newColorValue != colorValue)
{
colorValue = newColorValue;
// Replace this with a call to the renderer
Debug.Log("Set color to " + colorValue);
}
}
void DrawIntChooser(string propertyId)
{
int newIntValue = EditorGUILayout.IntField(intValue);
if (newIntValue != intValue)
{
intValue = newIntValue;
Debug.Log("Set int to " + intValue);
}
}
// All the other types choosers ...
// Finally, the method to put pieces together
void DrawModifier()
{
EditorGUILayout.BeginHorizontal();
string propertyId = "propId";
EditorGUILayout.TextField(propertyId);
SupportedTypes newModifierType = (SupportedTypes)EditorGUILayout.EnumPopup(selectedType);
// We only do if-else statements if the type changed
// So when the user changes only the value, this will be skipped
if (newModifierType != selectedType)
{
// Here, based on the chosen type, we set the delegate
if (newModifierType == SupportedTypes.Int)
{
methodUsedToDrawTheLastPart = DrawIntChooser;
}
else if (newModifierType == SupportedTypes.Color)
{
methodUsedToDrawTheLastPart = DrawColorChooser;
}
selectedType = newModifierType;
}
// And then we call it
methodUsedToDrawTheLastPart(propertyId);
EditorGUILayout.EndHorizontal();
}
public override void OnInspectorGUI()
{
DrawModifier();
}
You could use Switch and Foreach statements instead of If and For statements to make that code a little easier to read, to something like this:
foreach (var materialObject in materialObjects)
{
foreach (var materialModifier in materialModifiers)
{
switch (materialModifier.valueType)
{
case LittleSubstanceModifier.ValueType.Float:
if (materialModifier.valueFloat[0] != materialModifier.oldValueFloat[0])
{
materialObject.material.SetFloat(materialModifier.identifier, materialModifier.valueFloat[0]);
materialModifier.valueFloat = materialModifier.oldValueFloat;
}
break;
case LittleSubstanceModifier.ValueType.Float2:
case LittleSubstanceModifier.ValueType.Float3:
case LittleSubstanceModifier.ValueType.Float4:
if (materialModifier.valueFloat != materialModifier.oldValueFloat)
{
materialObject.material.SetFloatArray(materialModifier.identifier, materialModifier.valueFloat);
materialModifier.valueFloat = materialModifier.oldValueFloat;
}
break;
etc etc
}
}
}
(Also your code looks like it might not do exactly what you want... but I haven't changed what it does, because I don't know what you want it to do)

Prevent saving an invalid field value in Sitecore

I have a custom validator class, which checks the following:
The value of the text field should have a length 5 characters.
The
first 2 chars. should be numbers.
The last 3 chars. should be
alphabets.
When setting the Standard Value of the template (eg: 12a), the indicator shows Red and the appropriate message. But after pressing Ctrl + S, it shows a dialog asking to save even when there is an error. After clicking OK, there is a similar dialog. Clicking on OK, saves 12a as the standard value for the field. When I refresh the content editor the value is 12a.
Is this normal Sitecore behavior. I'm expecting that the value shouldn't be saved at all, if it is invalid.
namespace CustomValidators
{
[Serializable]
public class testValidator : StandardValidator
{
private readonly Regex numbersRegex = new Regex(#"^\d+$");
private readonly Regex lettersRegexnew = new Regex(#"^[A-Za-z]+$");
protected override ValidatorResult Evaluate()
{
string value = base.GetControlValidationValue();
if (!string.IsNullOrEmpty(value) && value.Length == 5)
{
string firstPart = value.Substring(0, 2);
string secondPart = value.Substring(3, 3);
if (numbersRegex.IsMatch(firstPart) && lettersRegexnew.IsMatch(secondPart))
{
return ValidatorResult.Valid;
}
}
base.Text = "invalid value";
return base.GetFailedResult(ValidatorResult.FatalError);
}
protected override ValidatorResult GetMaxValidatorResult()
{
return base.GetFailedResult(ValidatorResult.FatalError);
}
public override string Name
{
get { return "testValidator"; }
}
}
}
Only people in certain roles, even get the option of forcing a save. Admins and I think people in the "Sitecore Developer" role.
As such, you are given the option of forcing a save through. This is normal behaviour.
Your regular editor users would not be able to save.

C# Windows Form search txt file for passed data and pass to textboxes

I'm relatively new to C# and have spent an inordinate amount of time trying to figure this out myself with no luck. Hoping you guys can help.
I have 2 windows forms. In the first form, the user enters a citation number. I want to take that citation number, search for it in an external text file, and then return all of the data in the row for that citation into separate textboxes.
The text file looks something like this:
S8729936 , 6JXV123 , 10/1/2015 , 10/31/2015 , PAID , 49.5
A7472601 , 2NXP234 , 10/12/2015 , 11/11/2015 , UNPAID , 99
W2041810 , 5JPB345 , 10/19/2015 , 11/18/2015 , UNPAID , 99
And the second form has 6 textboxes. I have it so that the citation number, let's say S8729936 is passed into the first textbox, but I cannot seem to figure out how to then search the text file for S8729936 and give me the rest of the data in the row inside the textboxes.
Here are some examples of things I've tried. I've been copying and pasting and then messing with code all day, so if the details don't seem to match, that's probably the reason.
public Form2(string citation)
{
InitializeComponent();
txtCitation2.Text = citation;
const string FILENAME = #"\Path\ProjectData.txt";
FileStream fsInFile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
StreamReader srReader = new StreamReader(fsInFile);
const char CH_DELIM = ',';
string strRecordIn;
string[] strFields;
if (strFields != null)
{
strRecordIn = srReader.ReadLine();
strFields = strRecordIn.Split(CH_DELIM);
txtLicense2.Text = strFields[1];
}
strRecordIn = srReader.ReadLine();
srReader.Close();
fsInFile.Close();
}
No luck there, how about something along the lines of this:
string whole_file = File.ReadAllText(#"Path\ProjectData.txt");
whole_file = whole_file.Replace('\n', '\r');
string[] lines = whole_file.Split(new char[] { '\r' });
int num_rows = lines.Length;
int num_cols = lines[0].Split(',').Length;
string[,] values = new string[num_rows, num_cols];
for (int r = 0; r < num_rows; r++)
{
string[] line_r = lines[r].Split(',');
for (int c = 0; c < num_cols; c++)
{
values[r, c] = line_r[c];
}
}
txtLicense2.Text = lines[1];
Nope. Maybe something along the lines of this:
const string FILENAME = #"C:\Users\rfranklin\Documents\ProjectData.txt";
FileStream fsinfile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
StreamReader srReader = new StreamReader(fsinfile);
const string CH_DELIM = " ,";
string strRecordIn;
string[] strFields = new string[10];
string citnum = citation;
bool found = false;
strRecordIn = srReader.ReadLine();
foreach(string x in strFields)
{
if (x == citation)
{
found = true;
break;
}
}
if (found)
{
txtLicense2.Text = strFields[1];
}
Still no luck. And on and on. It seems as though I'm mostly missing how to tell the program what to search for and I am not sure what else to do. Like I said, I've been Googling various ways to do it all day, but I can't seem to make anything work right.
I'm doing this in Visual Studio 2013, if that helps.
Any help would be immensely appreciated. Thanks.
If the number of lines in the CSV file is not too large (I wouldn't know what "too large" is), then you could leverage a few .NET constructs, such as Data Binding and Linq to achieve this.
For starters, I would create a class that implements INotifyPropertyChanged:
namespace Citations
{
public class Citation : INotifyPropertyChanged
{
public static Citation ParseLine(string line)
{
Citation cit = new Citation();
if (string.IsNullOrEmpty(line))
throw new ArgumentException("Invalid argument", nameof(line));
string[] vals = line.Split(',');
if (vals.Length != 6)
throw new ArgumentOutOfRangeException(nameof(line), "Invalid format");
cit.CitationNumber = vals[0].Trim();
cit.PlateNumber = vals[1].Trim();
cit.DateCreated = DateTime.Parse(vals[2].Trim());
cit.DateExpired = DateTime.Parse(vals[3].Trim());
cit.Status = vals[4].Trim();
cit.Amount = Decimal.Parse(vals[5].Trim());
return cit;
}
void RaisePropertyChanged(string prop)
{
if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); }
}
public event PropertyChangedEventHandler PropertyChanged;
string citationNumber;
public string CitationNumber
{
get
{
return citationNumber;
}
set
{
if (citationNumber != value)
{
citationNumber = value;
RaisePropertyChanged(nameof(CitationNumber));
}
}
}
string plateNumber;
public string PlateNumber
{
get
{
return plateNumber;
}
set
{
if (plateNumber != value)
{
plateNumber = value;
RaisePropertyChanged(nameof(PlateNumber));
}
}
}
DateTime dateCreated;
public DateTime DateCreated
{
get
{
return dateCreated;
}
set
{
if (dateCreated != value)
{
dateCreated = value;
RaisePropertyChanged(nameof(DateCreated));
}
}
}
DateTime dateExpired;
public DateTime DateExpired
{
get
{
return dateExpired;
}
set
{
if (dateExpired != value)
{
dateExpired = value;
RaisePropertyChanged(nameof(DateExpired));
}
}
}
string status;
public string Status
{
get
{
return status;
}
set
{
if (status != value)
{
status = value;
RaisePropertyChanged(nameof(Status));
}
}
}
Decimal amount;
public Decimal Amount
{
get
{
return amount;
}
set
{
if (amount != value)
{
amount = value;
RaisePropertyChanged(nameof(Amount));
}
}
}
}
}
This class is responsible for splitting a line from the CSV file, and converting it to an object of type Citation, which will be used to data bind the textboxes in Form2 later on.
Then in the first Form, I would simply read the file, and using some Linq operators, convert the file to a Dictionary of Citation objects, the key of the Dictionary being the Citation number:
private void button1_Click(object sender, EventArgs e)
{
string[] allLines = File.ReadAllLines("Citations.csv");
Dictionary<string, Citation> dict = allLines.Select(l => Citation.ParseLine(l)).ToDictionary(c => c.CitationNumber, k => k);
Citation cit = dict["W2041810"];
Form2 frm2 = new Form2();
frm2.SetCitation(cit);
frm2.ShowDialog();
}
In the code above, we're using the ToDictionary Linq operator to create a Disctionary from your Citation objects, and the Dictionat key is the Citation number.
Here I'm hardcoding one of the citations for lookup and passing to Form2, which would have a SetCitation method like this:
public void SetCitation(Citation citation)
{
this.citationBindingSource.DataSource = citation;
}
The code to Form2 is a bit difficult to show because I have used the Form designer to setup the data binding for each TextBox, and if I wanted to show that, I'd basically have to show the whole Form2.Designer.cs file.
Instead, I propose to guide you through the process of creating a Project DataSource, then drag & drop the TextBoxes onto Form2 from the Data Sources dialog in Visual Studio.
So, after adding the Citation class to your solution, make sure to compile at leat once so that the "Add data source" wizard will pick that class up as a possible data source.
Then, make sure the Data Sources dialog is displayed by going to View > Other Windows > Data Sources (assuming Visual Studio 2015 here).
From the Data Sources dialog, click the "Add New Data Source button" tolaunch the Data SOurce Configuration Wizard. From the list of possible data sources, you will choose "Object":
Then click the Next button. From the next Wizard step, you will select the Citation class:
and then click the Finish button.
In the Data Sources dialog, you should now have something like this:
From this Data Sources dialog, you can now drag & drop the individual fields onto Form2, which should give you something like this:
You will also notice in the Component tray of Form2, a BindingSource object has been added:
Under the hood, Visual Studio will have set all the Data Binding for your Citation object properties to be displayed in the corresponding TextBox.
This is the "glue" that makes it possible to call Form2.SetCitation() with a Citation object, and have all the fields displayed where they should.
I know this is quite a mouthful to chew on, but believe me, once you understand the principles behind this, you will not want to go back to the kind of spagethi code that you started implementing (no offense, we've all been there).
If you would like me to clarify any specific section of my answer, just let me know, and I'll edit accordingly.
Cheers
A simple winForm version:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
List<string> matchedList = new List<string>();
public Form1(string citation)
{
InitializeComponent();
string filePath = #"C:\Users\rfranklin\Documents\ProjectData.txt";
string[] linesArr = File.ReadAllLines(filePath);
//find matches
foreach(string s in linesArr)
{
if(s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
//output
foreach(string s in matchedList)
{
Console.WriteLine(s); //write to console
//or output to wherever you wish, eg.
//richTextBox.Text += s + "\n";
}
}
}
}
Note that Form1 needs to be called from somewhere else and take in citation argument. To test it standalone, change it to
public Form1()
{
InitializeComponent();
string citation = "S8729936";
The suggestion from #interceptwind did it for me. Inside the //output section of the code he provided, I basically just created a second array from the matched line, with the elements separated by the comma. The code looks like this:
//output
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
txtLicense2.Text = lineData[1];
txtIssued2.Text = lineData[2];
txtDue2.Text = lineData[3];
txtStatus2.Text = lineData[4];
txtAmount2.Text = lineData[5];
}
This allowed me to put the data in the textboxes I needed. Thank you all for the assistance!

How to access a windows forms comboboxes' variables? C#

I have a small problem regarding C# and WindowsForms.
I'm trying to get string SelectedItemName = combobox2.SelectedItem.ToString(); this variable in another class. For example I have this in my Form1.cs Class.
public void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
FileIniDataParser fileParser = new FileIniDataParser();
IniData data = fileParser.ReadFile("config.ini");
IniProgram classReference = new IniProgram();
string SelectedItemName = (string)comboBox2.SelectedItem.ToString();
// string _SelectedItemName = (string)comboBox2.SelectedText;
Console.WriteLine(SelectedItemName);
if (comboBox2.SelectedIndex > -1)
{
testvariabel2.GetSessionName();
}
}
And than my other Class CTestRack.cs looks like this:
if (_form1Object.comboBox2.SelectedIndex.ToString() != null)
{
string SelectedItemName = _form1Object.comboBox2.SelectedItem.ToString();
System.Threading.Thread.Sleep(1000);
if (newDictionary.ContainsKey(SelectedItemName))
Now I've tried getting and setting the variable in the Form1 class but I was just getting Loop errors, now with this method I'm getting a NULLReferenceException.
By the way I was already looking into several related posts here in SO but didn't found my answer yet.
My question is just how do I get the active Text from the Combobox in my other Class as a String?
Ensure that _form1Object, is indeed set to the instance of form you want to access... It's hard to tell from above code if correct initialization of _form1Object is the problem here.
Assuming _form1Object, is correctly initialized, one bug in above code is that ComboBox.SelectedIndex property is an int.
See http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindex(v=vs.110).aspx
It doesn't matter if there is SelectedItem or not, comboBox2.SelectedIndex.ToString() != null will always be true, but comboBox2.SelectedItem could still be null, and hence comboBox2.SelectedItem.ToString() would fail with NullReferenceException.
It's possible that comboBox2 doesn't have SelectedItem, you can check it
either by
comboBox2.SelectedItem != null
Or by
comboBox2.SelectedIndex >= 0
Something like that
if (comboBox2.SelectedItem != null) {
string SelectedItemName = comboBox2.SelectedItem.ToString();
Console.WriteLine(SelectedItemName);
testvariabel2.GetSessionName();
}
else {
// No selected item in the ComboBox
}
...
if (_form1Object != null)
if (_form1Object.comboBox2.SelectedIndex >= 0) {
string SelectedItemName = _form1Object.comboBox2.SelectedItem.ToString();
System.Threading.Thread.Sleep(1000);
if (newDictionary.ContainsKey(SelectedItemName))
...
}

Correct way to implement web part personalisation for listboxes

Trying to work out this whole web part personalisation, and trying to implement it for a list box.
Well the end result will be two list boxes, with interchangeable values (ie, a value will only exist in one of the listboxes)
But I can't maintain the datasource for it. So maybe I'm going about it wrong?
This is what I have for a test H2 tag on the page
[Personalizable(PersonalizationScope.User)]
public string LabelText {
get { return h2Test.InnerText; }
set { h2Test.InnerText = value; }
}
And it works fine, if I have a textbox and use it to change the value of LabelText, then when I close the browser it automagically persists the change.
So I thought, ok, then maybe the same will work with a list box
[Personalizable(PersonalizationScope.User)]
public DomainList Domains {
get { return (DomainList)lstBxDomains.DataSource; }
set {
lstBxDomains.DataSource = value;
lstBxDomains.DataBind();
}
}
Where DomainList is just a class which extends List, and Domain is just a three field class, int, string, string.
But it doesn't, so is this too complicated for the webpart personalisation automagican, or have i just implement it wrongly (Which is more than likely)
This is my event handler to remove the items from the list:
protected void btnRemDomain_Click(object sender, EventArgs e) {
if (IsPostBack && lstBxDomains.SelectedIndex > -1) {
for (int i = 0; i < lstBxDomains.Items.Count; i++) {
if (lstBxDomains.Items[i].Selected) {
Domains.Remove(Domains.Find(d => d.ID.ToString() == lstBxDomains.Items[i].Value));
}
}
Domains = Domains;
}
}
The Domains=Domains; line is in there to see if explicitly setting the value made a difference (as Removing doesn't acutally reset the value of the field), but it doesn't. I've also tried creating a new local DomainList setting it to the global one, and then doing the remove/find on it, and then setting the local one to the global. But not working either.
I have managed to resolve this by using WebPart.SetPersonalizationDirty(this); in the set accessor of Domains, but would someone mind confirming if this is an appropriate way to do it?

Categories

Resources