I don't know any other way to explain this apart from providing an image of what I'm doing.
Basically, the Save Cheats button creates a text file that has the information from the 3 textboxes (cheattbox, cheatobox, cheatbbox) numbered respectably. There are 20 total boxes, and to save space only those with data should be saved. Let's say someone wants to save the information from boxes 4, 7, 8 and 13, with those checkboxes checked, I want the text file to only contain information from those given boxes.
Here is the code I have thus far.
public string savemagic(int i)
{
CheckBox tickbox = this.Controls.Find("ccheatcbox" + i.ToString(), true).FirstOrDefault() as CheckBox;
TextBox namebox = this.Controls.Find("ccheatname" + i.ToString(), true).FirstOrDefault() as TextBox;
ComboBox byteselect = this.Controls.Find("ccheatbytebox" + i.ToString(), true).FirstOrDefault() as ComboBox;
TextBox offsetbox = this.Controls.Find("ccheatofsetbox" + i.ToString(), true).FirstOrDefault() as TextBox;
TextBox bytebox = this.Controls.Find("ccheatbytes" + i.ToString(), true).FirstOrDefault() as TextBox;
fu[i] = string.Format("{0} - {1} - {2}\n",namebox.Text, offsetbox.Text, bytebox.Text);
return fu[i];
}
int checkint;
string[] fu = new string[9999];
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog _SD = new SaveFileDialog();
_SD.Filter = "Text File (*.txt)|*.txt|Show All Files (*.*)|*.*";
_SD.FileName = "Untitled";
_SD.Title = "Save As";
if (_SD.ShowDialog() == DialogResult.OK)
{
foreach(var controls in ccheattab.Controls)
{
if (controls is CheckBox && ((CheckBox)controls).Checked)
{
string tmp = ((CheckBox)controls).Name.Replace("ccheatcbox", "");
checkint = Convert.ToInt32(tmp);
File.WriteAllText(_SD.FileName, savemagic(checkint));
}
}
}
}
You could try just having the checkbox see if it's ticked or not like so
public string savemagic(int i)
{
CheckBox tickbox = this.Controls.Find("ccheatcbox" + i.ToString(), true).FirstOrDefault() as CheckBox;
if (tickbox.Checked) {
TextBox namebox = this.Controls.Find("ccheatname" + i.ToString(), true).FirstOrDefault() as TextBox;
ComboBox byteselect = this.Controls.Find("ccheatbytebox" + i.ToString(), true).FirstOrDefault() as ComboBox;
TextBox offsetbox = this.Controls.Find("ccheatofsetbox" + i.ToString(), true).FirstOrDefault() as TextBox;
TextBox bytebox = this.Controls.Find("ccheatbytes" + i.ToString(), true).FirstOrDefault() as TextBox;
string Cheats= string.Format("{0} - {1} - {2}\n",namebox.Text, offsetbox.Text, bytebox.Text);
return Cheats;
}
return "";
}
https://msdn.microsoft.com/en-us/library/system.windows.forms.checkbox.checked%28v=vs.110%29.aspx
Also, for actually writing to the file, think about using a StreamWriter instead of using File.WriteAllText unless you're going to use a StringBuilder to put these strings together.
This is what happens when you call File.WriteAllText:
Creates a new file, write the contents to the file, and then closes
the file. If the target file already exists, it is overwritten.
For a start it would help you a lot if you abstract your model and have a slight separation form UI, it's just going to confuse you when you are dealing with your business logic.
class CheatObject {
public string Name { get; set; }
public string SelectType { get; set; } // or use enum for this
public string OffsetStr{ get; set; }
public string ByteStr { get; set; }
public ExportToFile() {
// logic to export a CheatModel
}
}
...
Once you have this, it will be much simpler. Your question could be only, what is the best way to get which rows are checked.
Then: foreach (all checked boxes) cheatModelFromRow.ExportToFile();
Related
I have a datagrid that has lets say 2 columns for now. "App Name", and "App Location". At first there's no row just 2 columns, but when I click a button and a OpenFileDialog opens, I choose .exe file then I want that .exe filename and location(path) be in my datagrid.
At first I manage to do it but when I'm double clicking the row it gives me error says "'EditItem' is not allowed for this view.". So I searched it and found that I have to bind the row to a list. I did it and now nothings is display in rows when I add a .exe file.
my item class
public class ApplicationItem
{
//public bool isAppRun { get; set; }
public string appName { get; set; }
public string appLocation { get; set; }
}
my first code that works in adding but got error when Double clicked a row
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.DefaultExt = ".exe";
fileDialog.Filter = "Exe Files (*.exe)|*.exe";
Nullable<bool> selected = fileDialog.ShowDialog();
if (selected == true) //selected a file
{
fileName = fileDialog.SafeFileName.ToString();
filePath = fileDialog.FileName.ToString();
applications_grd.Items.Add(new ApplicationItem()
{
appName = fileName.Remove(fileName.Length - 4),
appLocation = filePath
});
2nd code where I use List then got no text in rows.
string fileName = "";
string filePath = "";
List<ApplicationItem> appItems = new List<ApplicationItem>();
appItems.Add(new ApplicationItem()
{
appName = fileName.Remove(fileName.Length - 4),
appLocation = filePath
});
applications_grd.Items.Add(appItems);
Thanks in advance. Any help will be much appreciated.
This might work In xaml page add
AutoGenerateColumns="True"
in grid and in .cs code set
applications_grd.ItemsSource = appItems;
I have a form with all button, label, I plan to make multi-language support by using INI files. I created Lang Class to hold value, if user change language, on-the-fly update without require restart the program.
my current code:
private void LangGet(string LangID)
{
IConfigSource Lng = new IniConfigSource(Globals.Path.FolderLang + "\\" + LangID + ".ini");
// Set
var g = Lng.Configs["general"];
Lang.Id.General.OK = g.GetString("OK");
Lang.Id.General.Cancel = g.GetString("Cancel");
Lang.Id.General.Error = g.GetString("Error");
...
Lang.Id.General.lblStart = g.GetString("lblStart");
...
what I wanted code more efficient, but I dont know how...
IConfigSource Lng = new IniConfigSource(Globals.Path.FolderLang + "\\" + LangID + ".ini");
var g = Lng.Config["general"];
forloop ( ... )
{
item = g.GetString(item);
}
if more powerful
IConfigSource Lng = new IniConfigSource(Globals.Path.FolderLang + "\\" + LangID + ".ini");
forloop ( ... )
{
forloop ( ... )
{
TheName = Lng.Config[TheClass].GetString(TheName);
}
}
After load INI loaded to Variable, time to control text get Variable value
forloop ( control )
{
forloop ( class )
{
if ( control name contain btn )
{
item.Text = Lng.Configs[TheClass].GetString(item.name?);
}
if ( control name contain lbl )
{
item.Text = Lng.Configs[TheClass].GetString(item.name?);
}
// So On...
I found my answer... so I answer my self,
using Ini-parser instead of Nini...
Make multi-language using INI file, allow language to be edited after compiled, easy to do correction.
Instead write code every control, use loop to do their job
CreateLang(); will scan all your form and it's child, using control Name as Ini Key
LoadLang(); will scan all your form control, once Ini Key equal control name, Value will apply to control.
During designing, all control must be change to {0} or multi-line {0}{1}{2}
Code:
private void frmMain_Load(object sender, EventArgs e)
{
CreateLang(); // Create new empty language
//LoadLang(); // Load language, GUI must use {0} {1} ... as place-holder
}
private void LoadLang()
{
var parser = new FileIniDataParser();
IniData data = parser.ReadFile("eng.ini");
Control ctrl = this;
do
{
ctrl = this.GetNextControl(ctrl, true);
if (ctrl != null)
if (ctrl is Label ||
ctrl is Button ||
ctrl is TabPage ||
ctrl is CheckBox)
if (data["Root"][ctrl.Name].Contains('|')) // Character | donated by New-Line, \n
ctrl.Text = String.Format(ctrl.Text, data["Root"][ctrl.Name].Split('|'));
else
ctrl.Text = String.Format(ctrl.Text, data["Root"][ctrl.Name]);
} while (ctrl != null);
}
private void CreateLang()
{
if (System.IO.File.Exists("eng.ini"))
System.IO.File.WriteAllText("eng.ini", "");
else
System.IO.File.WriteAllText("eng.ini", "");
var parser = new FileIniDataParser();
IniData data = parser.ReadFile("eng.ini");
data.Sections.AddSection("Info");
data.Sections["Info"].AddKey("Name", "Anime4000");
data.Sections["Info"].AddKey("Version", "0.1");
data.Sections["Info"].AddKey("Contact", "fb.com/anime4000");
string main = "Root";
data.Sections.AddSection(main);
Control ctrl = this;
do
{
ctrl = this.GetNextControl(ctrl, true);
if (ctrl != null)
if (ctrl is Label ||
ctrl is Button ||
ctrl is TabPage ||
ctrl is CheckBox ||
ctrl is GroupBox)
data.Sections[main].AddKey(ctrl.Name, "");
} while (ctrl != null);
parser.WriteFile("eng.ini", data);
}
I have 30 TextBox in my form. And i want to select correct one and write value there.
My textboxes names are :
tb_0_X, tb_0_Y,tb_1_X, tb_1_Y,tb_2_X, tb_2_Y, .... goes like this..
And i can create my textbox name :
string tbName = pointLoc.ToString();
string tbFirst = "tb_";
string tbLastX = "_X";
string tbLastY = "_Y";
string tbX = tbFirst + tbName + tbLastX;
string tbY = tbFirst + tbName + tbLastY;
Instead of writing all textbox such as :
tb_0_X.text = "";
tb_0_Y.text = "";
...
..
.
.
..
I want to write tbX or tbY but it is not possible to write ..
tbX.text = "someString";
how can i handle this issue ,?
EDIT :
To be more clearly ..
string tbName comes from radioButton. So i need to find which textbox i should change from tbX or tbY..
therefore i need to do something like tbX.text = "someString";
string tbX = "textBox1"; // or whatever you want to call it
TextBox tb = this.Controls.Find(tbX, false).FirstOrDefault() as TextBox;
if (tb != null)
{
tb.Text = "Test";
}
The this keyword obviously represents the form the textbox is on.
class TextColumn : ITemplate
{
private string controlId;
private string cssClass;
public TextColumn(string id, string cssClass = "inputFromTo")
{
controlId = id;
this.cssClass = cssClass;
}
public void InstantiateIn(Control container)
{
TextBox txt = new TextBox();
txt.ID = controlId;
txt.CssClass = cssClass;
container.Visible = true;
container.Controls.Add(txt);
}
}
/************************************ Add column code snippet ****************************/
TemplateField dentry = new TemplateField();
TemplateField dexit = new TemplateField();
TemplateField dslack = new TemplateField();
dentry.ItemTemplate = new TextColumn("txtHH" + nameCount + "DEntry");
dexit.ItemTemplate = new TextColumn("txtHH" + nameCount + "DExit");
dslack.ItemTemplate = new TextColumn("txtHH" + nameCount + "DSlack");
gvOfcBlowingReport.Columns.Insert(startPoint, dentry);
gvOfcBlowingReport.Columns.Insert(startPoint + 1, dexit);
gvOfcBlowingReport.Columns.Insert(startPoint + 2, dslack);
/********************************* Remove column code snippet ************************/
gvOfcBlowingReport.Columns.RemoveAt(startPoint - 1);
gvOfcBlowingReport.Columns.RemoveAt(startPoint - 2);
gvOfcBlowingReport.Columns.RemoveAt(startPoint - 3);
// after executing this code all the columns vanish.
Anyone know how to remove this text box template column?
In the above code I am adding templated field textbox and later on removing the same on button click but due to some reason all the templated field are getting affected and returning null when i am using FindControl in grid. In display also grid is displayed as empty.
Some other people are also facing the same problem over http://forums.asp.net/t/1162011.aspx but so far no valuable solution.
I would like to click on an item in a listbox and display the attributes that were passed into that listbox to a multiline textbox.
Below is the code I have written on form initialisation
public Form1()
{
InitializeComponent();
ReadFromFile.Read("sample.GED");
foreach (KeyValuePair<int, Individual> kvp in ReadFromFile.individuals)
{
listBox2.Items.Add("ID = " + kvp.Value.id + " Name = " + kvp.Value.name.givenName + " " + kvp.Value.name.surname + " DoB = " + kvp.Value.birth.date);
}
int testIndividual = 94;
string genderOut = "";
if (ReadFromFile.individuals[testIndividual].gender == "M")
{
genderOut = "MALE";
}
else if (ReadFromFile.individuals[testIndividual].gender == "F")
{
genderOut = "FEMALE";
}
try
{
textBox1.AppendText(
"Name = " + ReadFromFile.individuals[testIndividual].name.givenName + " "
+ ReadFromFile.individuals[testIndividual].name.surname
+ Environment.NewLine + "Gender = " + genderOut
+ Environment.NewLine + "Birth date = " + ReadFromFile.individuals[testIndividual].birth.date
+ Environment.NewLine + "Birth place = " + ReadFromFile.individuals[testIndividual].birth.place
+ Environment.NewLine + "Death date = " + ReadFromFile.individuals[testIndividual].death.date
+ Environment.NewLine + "Death place = " + ReadFromFile.individuals[testIndividual].death.place);
}
catch
{
MessageBox.Show("This individual doesnt exist");
}
}
}
I would like to add more so I can click on a listbox item and the details for that item will be shown in the textbox
I get the feeling I may have to override the ToString() method or regex it. Im still quite a novice programmer so go easy on me :) THANK YOU
You need to handle the SelectedIndexChanged event for your listbox.
One way to do this is to bring up Form1.cs[Design] and select the listbox. In the property grid (Alt+Enter) click the icon that looks like this:
Find the event SelectedIndexChanged and double click it. That will hook up an event handler for you in the auto generated Form1.cs.designer file.
Next, replace the code for your Form1 class with the following:
public partial class Form1 : Form
{
private Dictionary<int, Individual> _individuals;
public Form1()
{
InitializeComponent();
ReadFromFile.Read("sample.GED");
_individuals = ReadFromFile.individuals;
listBox1.DataSource = _individuals.Select(individual => individual.Value).ToList();
listBox1.DisplayMember = "name";
listBox1.ValueMember = "id";
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Clear();
var individual = listBox1.SelectedItem as Individual;
string genderOut = (individual.Gender == "M") ? "MALE" : "FEMALE";
var displayText
= String.Format("Name = {0} {1}\r\n" +
"Gender = {2}\r\n" +
"Birth date = {3}\r\n" +
"Birth place = {4}\r\n" +
"Death date = {5}\r\n" +
"Death place = {6}"
, individual.name.givenName
, individual.name.surname
, genderOut
, individual.birth.date
, individual.birth.place
, individual.death.date
, individual.death.place);
textBox1.AppendText(displayText);
}
}
A few notes about some of the things i've changed.
I've moved the code that was setting the textbox value into the SelectedIndexChanged event handler
I've refactored that code so that it's more readable by using the static String.Format method (all those Environment.NewLine repeats you had were messy).
I've setup the data for the list box using the DataSource property instead of your foreach loop.
Also, one thing you'll notice with this is that the list items in the listbox will not show the correct text. This is because you appear to be using some custom classes or structs for the name, birth and death of an Individual? To fix this, you need to add a new property to the Individual class like this:
public class Individual
{
// ... your code
public string DisplayName
{
get { return String.Format("{0} {1}), name.givenName, name.surname; }
}
// ... the rest of your code
}
Then you will need to change the line in my code above that looks like this:
listBox1.DisplayMember = "name";
to this:
listBox1.DisplayMember = "DisplayName";
Final note: You should probably be using "Upper Camel Case" for your property names. That means that they start with an upper case letter and then the first letter of each word is also upper case. For example, name.givenName should be Name.GivenName. This is a widely used convention.