I have tried lots of codes posted here. And another places.
It doesn't do what want to do.
First See the code:
Load Button:
private void LoadBtn_Click(object sender, EventArgs e)
{
TextReader testTxt = new StreamReader(ItemBaseInfosPath);
string read;
do
{
read = testTxt.ReadLine();
if (read.Contains(IDTxt.Text))
{
ConquerItemBaseInformation CIBI = new ConquerItemBaseInformation();
CIBI.Parse(read);
NameTxt.Text = CIBI.Name;
LevelTxt.Text = Convert.ToString(CIBI.Level);
MaxAttackTxt.Text = Convert.ToString(CIBI.MaxAttack);
MinAttackTxt.Text = Convert.ToString(CIBI.MinAttack);
PhysicalTxt.Text = Convert.ToString(CIBI.PhysicalDefence);
DodgeTxt.Text = Convert.ToString(CIBI.Dodge);
MagicAttackTxt.Text = Convert.ToString(CIBI.MagicAttack);
MagicDefTxt.Text = Convert.ToString(CIBI.MagicDefence);
AttackRangeTxt.Text = Convert.ToString(CIBI.AttackRange);
PriceTxt.Text = Convert.ToString(CIBI.ConquerPointsWorth);
break;
}
else
{
MessageBox.Show("Item Not Found.");
}
} while (read != null);
Save Button:
private void SaveBtn_Click(object sender, EventArgs e)
{
TextReader testTxt = new StreamReader(ItemBaseInfosPath);
string read, read1, read2, read3, read4, read5, read6,
read7, read8, read9, read10;
do
{
read = testTxt.ReadLine();
if (read.Contains(IDTxt.Text))
{
ConquerItemBaseInformation CIBI = new ConquerItemBaseInformation();
CIBI.Parse(read);
CIBI.Name = NameTxt.Text;
CIBI.Level = Convert.ToByte(LevelTxt.Text);
CIBI.MaxAttack = Convert.ToByte(MaxAttackTxt.Text);
MessageBox.Show(read);
break;
}
} while (read != null);
}
Load Button is working Great! Without problems. The problems in Save Button.
I got now the line, Example:" 111003##IronHelmet##21##0##15##0##0##0##0##0##0##0##150##0##0##0##3##0##0##0##0##3899##3899##0##0##0##0##0##0##0##0##0##1##1000##0##0##0##0##0##0##0##0##0##0##0##0##0##0##0##0##0##0##0##Warrior'sHelmet##None##5##0##0##0##2020##500##"
111003 is the ID, IronHelmet is the Name, 15 is the level.
It loaded. I want to save it. (Note for each of these have it's TextBox.
It's ItemEditor program, so I want when I edit anything in TextBox and Press "Save button"
It replace each of the edited things and save the text file again!:)
(Note: String.Replace("", ""); This code if I use it and the textbox that should edit, if it's value (Text) is 0 then it will change All Values of 0 in the Line! = Fail )
I hope you understand me!
Related
I got two comboxBox with SelectedIndexChanged event enabled.
In the comboBox2 i want to change the SelectedValue of comboBox1, and that works, but the SelectedIndexChanged of comboBox1 is always triggered even i explicit disabled that.
And the code in selectedIndexChange of the ComboBox1 overwrite what I do in the ComboBox2, that the problem.
I've tried hundreds ways to avoid that but anything works, the event always occurs.
Bellow is my code of ComboBox1:
private void cmbBeneficiario_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cb = (ComboBox)sender;
if (!cb.Focused)
{
return;
}
systemChange = true;
if (cnpjChange)
{
if (!string.IsNullOrWhiteSpace(cmbBeneficiario.Text) &&
!string.IsNullOrWhiteSpace(cmbBeneficiario.Text))
{
var beneficiarioApoliceBeneficiario =
averbacaoController.GetApoliceBeneficiario(cmbBeneficiario.Text);
var apolices = beneficiarioApoliceBeneficiario.Select(x => x.numero_apolice).ToList();
cmbApolice.DataSource = apolices;
cmbApolice.DisplayMember = "numero_apolice";
cmbApolice.Invalidate();
Refresh();
cmbApolice_SelectedIndexChanged(this, e);
var listBene = beneficiariosList;
var filteredList = listBene.Where(x => x.nome_beneficiario == cmbBeneficiario.Text).ToList();
cbbCNPJBeneAverb.DisplayMember = "cnpj_beneficiario";
cbbCNPJBeneAverb.DataSource = filteredList;
}
CarregaBeneficiarioPerfil();
systemChange = false;
}
}
The comboBox2 code (note that I disabled the event of combobox1):
private void cbbCNPJBeneAverb_SelectedIndexChanged(object sender, EventArgs e)
{
cnpjChange = true;
ComboBox cb = (ComboBox)sender;
if (!cb.Focused)
{
return;
}
Console.WriteLine($#"Old ID {cmbBeneficiario.SelectedValue}");
var beneficiario = averbacaoController.GetBeneficarioByCNPJ(cbbCNPJBeneAverb.Text, cmbBeneficiario.Text);
cmbBeneficiario.SelectedIndexChanged -= new EventHandler(cmbBeneficiario_SelectedIndexChanged);
if (cbbCNPJBeneAverb.SelectedIndex > -1)
{
cmbBeneficiario.SelectedValue = beneficiario.id_beneficiario;
CarregaBeneficiarioPerfil();
}
Console.WriteLine($#"New ID {cmbBeneficiario.SelectedValue}");
Console.WriteLine($#"Tinha que ser o ID {beneficiario.id_beneficiario}");
cmbBeneficiario.SelectedIndexChanged += new EventHandler(cmbBeneficiario_SelectedIndexChanged);
cnpjChange = false;
}
Printscreen of my debug:
As my comments above, you can use a class-scope variable to do check:
Add a temporary class-scope variable:
private bool cb1EventIgnore = false;
Set it to ture/false in cbbCNPJBeneAverb_SelectedIndexChanged:
if (cbbCNPJBeneAverb.SelectedIndex > -1)
{
cb1EventIgnore = true;
cmbBeneficiario.SelectedValue = beneficiario.id_beneficiario;
CarregaBeneficiarioPerfil();
cb1EventIgnore = false;
}
Check the value cb1EventIgnore in cmbBeneficiario_SelectedIndexChanged at the beginning:
private void cmbBeneficiario_SelectedIndexChanged(object sender, EventArgs e)
{
if(cb1EventIgnore) return;
//your codes here
}
After a lot of attempts, bellow are the piece of code that solved my question:
cmbBeneficiario.Enabled = false;
Simple like this, i dont know why c# was not able to not trigger the event even I explicit told him to.
I am working on a Windows application where I get an input from a TextBox and add it to the DataGridView when user clicks on a Button (Add).
My problem is that when I add the text for the first time, it works fine and its added to the grid.
When I add new text, it's not added to the DataGridView. Once the Form is closed and reopened with the same object then I am able to see it.
Code:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (Data == null)
Data = new List<Inputs>();
if (!string.IsNullOrWhiteSpace(txtInput.Text))
{
Data.Insert(Data.Count, new Inputs()
{
Name = txtInput.Text,
Value = string.Empty
});
}
else
{
MessageBox.Show("Please enter parameter value", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
txtInput.Text = "";
gridViewInputs.DataSource = Data;
}
I am not sure what is causing the record not to be added to grid on second add button click.
You could set the DataGridView.DataSource to null before setting a new one.
This would cause the DataGridView to refresh its content with the new data in the source List<Inputs>:
the underlying DataGridViewDataConnection is reset only when the DataSource reference is different from the current or is set to null.
Note that when you reset the DataSource, the RowsRemoved event is raised multiple times (once for each row removed).
I suggest to change the List to a BindingList, because any change to the List will be reflected automatically and because it will allow to remove rows from the DataGridView if/when required: using a List<T> as DataSource will not allow to remove a row.
BindingList<Inputs> InputData = new BindingList<Inputs>();
You can always set the AllowUserToDeleteRows and AllowUserToAddRows properties to false if you don't want your Users to tamper with the grid content.
For example:
public class Inputs
{
public string Name { get; set; }
public string Value { get; set; }
}
internal BindingList<Inputs> InputData = new BindingList<Inputs>();
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = InputData;
}
private void btnAddInput_Click(object sender, EventArgs e)
{
string textValue = txtInput.Text.Trim();
if (!string.IsNullOrEmpty(textValue))
{
InputData.Add(new Inputs() {
Name = textValue,
Value = "[Whatever this is]"
});
txtInput.Text = "";
}
else
{
MessageBox.Show("Not a valid value");
}
}
If you want to keep using a List<T>, add the code required to reset the DataGridView.DataSource:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textValue))
{
//(...)
dataGridView1.DataSource = null;
dataGridView1.DataSource = InputData;
txtInput.Text = "";
}
//(...)
Server 1 Server2 Server Config Screen
I am trying to make a video game server manager and I have run into an issue. I want the user to be able to have as many servers as they would like. However I cannot figure out through google searching and just regular messing around how to store the information that the user selects to become associated with the Server they create in the list. Basically when you make Server1 it takes the info you selected from the boxes on the config screen and uses them on the server selection page. But, when you make Server2, the configuration overwrites Server1's configuration. I know my code isn't even setup to be able to do this but I would appreciate a push in the right direction as to which type of code I should use.
Tl:dr I want config options to be associated with ServerX in the server list and each server should have unique settings.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string difSelect;
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if(srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
//Text being displayed to the left of the server listbox
mapLabel1.Text = mapSelect;
difLabel1.Text = difSelect;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string[] lines = { mapSelect, difSelect };
System.IO.File.WriteAllLines(#"C:\Users\mlynch\Desktop\Test\Test.txt", lines);
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
newPanel.Visible = false;
}
}
You mentioned in a recent comment that you had tried saving to a .txt file but it overwrote it anytime you tried to make an additional one. If you wanted to continue with your .txt approach, you could simply set a global integer variable and append it to each file you save.
//Variables
string srvName;
string mapSelect;
string difSelect;
int serverNumber = 0;
...
serverNumber++;
string filepath = Path.Combine(#"C:\Users\mlynch\Desktop\Test\Test", serverNumber.ToString(), ".txt");
System.IO.File.WriteAllLines(filepath, lines);
I think below source code will give you some idea about the direction. Let us start with some initializations:
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
mapBox1.Items.Add("Germany");
mapBox1.Items.Add("Russia");
difBox1.Items.Add("Easy");
difBox1.Items.Add("Difficult");
}
This is the event handler of the "Create Server" button. It takes server parameters from the screen and writes to a file named as the server.
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string path = #"C:\Test\" + srvName + ".txt";
StreamWriter sw = new StreamWriter(path);
sw.WriteLine(mapSelect);
sw.WriteLine(difSelect);
sw.Flush();
sw.Close();
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
//newPanel.Visible = false;
}
And finally list box event handler is below. Method reads the server parameters from file and displays on the screen.
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
string path = #"C:\Test\" + srvList.SelectedItem + ".txt";
StreamReader sr = new StreamReader(path);
//Text being displayed to the left of the server listbox
mapLabel1.Text = sr.ReadLine(); // mapSelect;
difLabel1.Text = sr.ReadLine(); // difSelect;
}
Please feel free to ask any questions you have.
I ended up figuring out the issue. Basically I ended up deciding on a write to a txt file and then read from it to display the contents of the file in the server select menu. I also added a delete button so you can delete the servers that you created. it does not have full functionality yet but it is there. So here it what I ended up with and it works perfectly. Thank you all for trying to help.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string mapFile;
string difSelect;
string difFile;
int maxPlayers;
string plrSelect;
string plrFile;
string finalFile;
string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string fileName = "config.txt";
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
//Read Server Selection
string srvSelect = srvList.GetItemText(srvList.SelectedItem);
string srvOut = System.IO.Path.Combine(basepath, srvSelect, fileName);
mapFile = File.ReadLines(srvOut).Skip(1).Take(1).First();
difFile = File.ReadLines(srvOut).Skip(2).Take(1).First();
plrFile = File.ReadLines(srvOut).Skip(3).Take(1).First();
//Display Server Selection
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
mapLabel1.Text = mapFile;
difLabel1.Text = difFile;
plrLabel1.Text = plrFile;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Set Server Name
srvName = namBox1.Text;
string finalpath = System.IO.Path.Combine(basepath, srvName);
//Check if server name is taken
if (System.IO.Directory.Exists(finalpath))
{
MessageBox.Show("A Server by this name already exists");
}
else
{
//Add Server to the Server List
srvList.Items.Add(srvName);
//Server Configuration
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
maxPlayers = maxBar1.Value * 2;
plrSelect = "" + maxPlayers;
//Clear New Server Form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Create the Server File
Directory.CreateDirectory(finalpath);
finalFile = System.IO.Path.Combine(finalpath, fileName);
File.Create(finalFile).Close();
//Write to config file
string[] lines = { srvName, mapSelect, difSelect, plrSelect };
System.IO.File.WriteAllLines(#finalFile, lines);
//Return to srvList
newPanel.Visible = false;
}
}
}
I have a windows form that reads strings from a file and shows them all in a textbox when I press a button.
private void buttonTxt_Click(object sender, EventArgs e)
{
string[] Test = File.ReadAllLines("C:\\testfile.txt");
for (int i = 0; i < testfile.Length; i++)
{
TextBox.Text += testfile[i];
}
}
I'd like to make two radio buttons. So that first button lets my program work the way I described (by default) AND second radio button makes it work vice versa -- so that I could write in a textbox myself and when I press a button it writes a new line to the same file. Is there a way to do it?
Simply add an if statement in this event handler and implement both sending and receiving the data. Done. Sample in principle:
private const string FilePath = #"C:\testfile.txt";
private void buttonTxt_Click(object sender, EventArgs e)
{
if (radioReadMode.Checked) // check which radio button is selected
{ // read mode
string[] Test = File.ReadAllLines(FilePath);
for (int i = 0; i < testfile.Length; i++)
TextBox.Text += testfile[i];
}
else
{ // write mode
File.WriteAllText(FilePath, TextBox.Text);
}
}
I believe this is what you might be looking for. If radio button 1 is checked then if the file exists it will read that file and put it into a textbox in the form. If you switch to radio button 2. You can type in the text box and then when you press the button it will append it to the file.
public partial class Form1 : Form
{
System.IO.StreamReader sr;
System.IO.StreamWriter sw;
public Form1()
{
InitializeComponent();
radioButton1.Checked = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sr = new System.IO.StreamReader("C:\\testfile.txt");
while (!sr.EndOfStream)
{
textBox1.Text += sr.ReadLine() + "\r\n";
}
}
finally
{
sr.Close();
sr.Dispose();
}
}
}
if (radioButton2.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sw = new System.IO.StreamWriter("C:\\testfile.txt", true);
string result = textBox1.Text;
string[] lststr = result.Split(new Char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in lststr)
{
sw.WriteLine(s);
}
}
finally
{
sw.Flush();
sw.Close();
sw.Dispose();
}
}
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = true;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = false;
}
}
Yes, there's a way. Just add another button to your form and inside read the text from the text box this way:
var textBoxContent = TextBox.Text;
and save it to your file this way
File.WriteAllText("C:\\testfile.txt", textBoxContent);
Note: I recommend getting the path to your file into a variable
This is similar to older posts on this site but I keep getting an error message. I want to create a button in C # WPF that opens a dialogbox and saves a text file to be read at a later date. This code works for windows 32, but crashes on windows 64. How can I change this code to get it to work on both systems? I am a beginner at programming.
Microsoft.Win32.SaveFileDialog saveFile = new Microsoft.Win32.SaveFileDialog(); //throws error message here
private void savebutton_Click(object sender, RoutedEventArgs e)
{
saveFile.FileName = Class1.stringjobnum;
saveFile.Filter = "CCurtain (*.cur)|*.cur";
saveFile.FilterIndex = 2;
saveFile.InitialDirectory = "T:\\Tank Baffle Curtain Calculator\\SavedTanks";
saveFile.OverwritePrompt = true;
bool? result = saveFile.ShowDialog();
if (result.HasValue && result.Value)
{
clsSaveFile.s_FilePath = saveFile.FileName;
int iDotLoc = clsSaveFile.s_FilePath.LastIndexOf('.');
string strExtTest = clsSaveFile.s_FilePath.Substring(iDotLoc);
if (strExtTest != ".cur")
clsSaveFile.s_FilePath += ".cur";
FileInfo sourceFile = new FileInfo(clsSaveFile.s_FilePath);
clsSaveFile.saveFile();
}
}
You're setting an invalid FilterIndex, that might have something to do with it.
There is no 2nd filter in the filter string as written:
"CCurtain (*.cur)|*.cur"
Try setting the FilterIndex to 1 or adding another filter to the string.
You should try adding a catch around the statement to get a better idea as to what is going on.
try
{
code here
}
catch (Exception ex)
{
ex.message contains the info
}
Also, check for null:
bool? result = saveFile.ShowDialog();
if (result != null && (result.HasValue && result.Value))
{
// code
}
I would create the dialogbox IN the event. And you don't have two different filters.
private void savebutton_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.SaveFileDialog saveFile = new Microsoft.Win32.SaveFileDialog();
saveFile.FileName = Class1.stringjobnum;
saveFile.Filter = "CCurtain|*.cur";;
saveFile.FilterIndex = 1;
saveFile.InitialDirectory = "T:\\Tank Baffle Curtain Calculator\\SavedTanks";
saveFile.OverwritePrompt = true;
// Show open file dialog box
Nullable<bool> result = saveFile.ShowDialog();
// Process open file dialog box results
if (result == true)
{
string filename = saveFile.FileName;
// are you sure you need to check the extension.
// if so extension is a a fileinfo property
}