I have looking for the solution but still found nothing
Here is my code:
private void Form1_Load(object sender, EventArgs e)
{
RichTextBox rtb = new RichTextBox();
rtb.Text = File.ReadAllText(#"C:\Users\Admin\Desktop\myfile\customers.txt");
int i = 0;
foreach (string line in rtb.Lines)
{
if (line == "--")
{
ListViewItem item = new ListViewItem();
item.Text = rtb.Lines[i + 1];
item.SubItems.Add(rtb.Lines[i + 2]);
item.SubItems.Add(rtb.Lines[i + 3]);
item.SubItems.Add(rtb.Lines[i + 4]);
listView1.Items.Add(item);
}
i += 1;
}
}
private void button1_Click(object sender, EventArgs e)
{
Form2 pop = new Form2();
pop.ShowDialog();
string name = pop.name;
int age = int.Parse(pop.Age);
string dob = pop.DateOfBirth;
string addr = pop.Address;
StreamWriter write = new StreamWriter(#"C:\Users\Admin\Desktop\myfile\customers.txt",true);
write.Write("--\n");
write.Write("{0}\n",name);
write.Write("{0}\n",dob);
write.Write("{0}\n",age);
write.Write("{0}\n",addr);
write.Close();
}
The question is how do I reload the list view after I write the data into the text file?
Extract the logic out of Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
RefreshListView();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 pop = new Form2();
pop.ShowDialog();
string name = pop.name;
int age = int.Parse(pop.Age);
string dob = pop.DateOfBirth;
string addr = pop.Address;
StreamWriter write = new StreamWriter(#"C:\Users\Admin\Desktop\myfile\customers.txt",true);
write.Write("--\n");
write.Write("{0}\n",name);
write.Write("{0}\n",dob);
write.Write("{0}\n",age);
write.Write("{0}\n",addr);
write.Close();
RefreshListView();
}
private void RefreshListView()
{
listView1.Items.Clear();
RichTextBox rtb = new RichTextBox();
rtb.Text = File.ReadAllText(#"C:\Users\Admin\Desktop\myfile\customers.txt");
int i = 0;
foreach (string line in rtb.Lines)
{
if (line == "--")
{
ListViewItem item = new ListViewItem();
item.Text = rtb.Lines[i + 1];
item.SubItems.Add(rtb.Lines[i + 2]);
item.SubItems.Add(rtb.Lines[i + 3]);
item.SubItems.Add(rtb.Lines[i + 4]);
listView1.Items.Add(item);
}
i += 1;
}
}
Related
it's my first post here. I'm learning C# (visual studio) at the moment and we have been building a program through given tasks. The last task is to create an "undo" button. This is the code so far:
namespace GestBar_v1._0
{
public partial class Form1 : Form
{
string[] bebidas = { "Café", "Ice Tea", "Água", "Aguardente" };
double[] precoBebidas = { 0.8, 1.5, 1.0, 1.0 };
string[] alimentacao = { "Bolos", "Sandes Mistas", "Torrada", "Salgados" };
double[] precoAlimentacao = { 1.0, 1.5, 1.5, 1.0 };
double soma = 0;
double fecho = 0;
void resetTxt()
{
txtPreco.BackColor = Color.White;
txtPreco.ForeColor = Color.Black;
txtPreco.Font = new Font("Microsoft Sans Serif", 11, FontStyle.Regular);
label2.Text = "Preço Final";
}
private void Processo(string[] items, double[] prices, int itemIndex)
{
if (listaProduto.Items.Contains(items[itemIndex]))
{
int index = listaProduto.Items.IndexOf(items[itemIndex]);
double count = double.Parse(listaUnidade.Items[index].ToString());
listaPreco.Items[index] = Math.Round(prices[itemIndex] * (count + 1), 2);
listaUnidade.Items[index] = count + 1;
soma += prices[itemIndex];
}
else
{
listaProduto.Items.Add(items[itemIndex]);
listaPreco.Items.Add(prices[itemIndex]);
listaUnidade.Items.Add(1);
soma += prices[itemIndex];
}
txtPreco.Text = soma.ToString();
}
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
resetTxt();
btn11.Visible = true;
btn12.Visible = true;
btn13.Visible = true;
btn14.Visible = true;
btn11.Text = bebidas[0] + "\n" + precoBebidas[0] + "€";
btn12.Text = bebidas[1] + "\n" + precoBebidas[1] + "€";
btn13.Text = bebidas[2] + "\n" + precoBebidas[2] + "€";
btn14.Text = bebidas[3] + "\n" + precoBebidas[3] + "€";
btn21.Visible = false;
btn22.Visible = false;
btn23.Visible = false;
btn24.Visible = false;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnAliment_Click(object sender, EventArgs e)
{
resetTxt();
btn21.Visible = true;
btn22.Visible = true;
btn23.Visible = true;
btn24.Visible = true;
btn21.Text = alimentacao[0] + "\n" + precoAlimentacao[0] + "€";
btn22.Text = alimentacao[1] + "\n" + precoAlimentacao[1] + "€";
btn23.Text = alimentacao[2] + "\n" + precoAlimentacao[2] + "€";
btn24.Text = alimentacao[3] + "\n" + precoAlimentacao[3] + "€";
btn11.Visible = false;
btn12.Visible = false;
btn13.Visible = false;
btn14.Visible = false;
}
private void btnTodosP_Click(object sender, EventArgs e)
{
resetTxt();
btn11.Visible = true;
btn12.Visible = true;
btn13.Visible = true;
btn14.Visible = true;
btn21.Visible = true;
btn22.Visible = true;
btn23.Visible = true;
btn24.Visible = true;
btn11.Text = bebidas[0] + "\n" + precoBebidas[0] + "€";
btn12.Text = bebidas[1] + "\n" + precoBebidas[1] + "€";
btn13.Text = bebidas[2] + "\n" + precoBebidas[2] + "€";
btn14.Text = bebidas[3] + "\n" + precoBebidas[3] + "€";
btn21.Text = alimentacao[0] + "\n" + precoAlimentacao[0] + "€";
btn22.Text = alimentacao[1] + "\n" + precoAlimentacao[1] + "€";
btn23.Text = alimentacao[2] + "\n" + precoAlimentacao[2] + "€";
btn24.Text = alimentacao[3] + "\n" + precoAlimentacao[3] + "€";
}
private void btn11_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 0);
}
private void btn12_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 1);
}
private void btn13_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 2);
}
private void btn14_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 3);
}
private void btn21_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 0);
}
private void btn22_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 1);
}
private void btn23_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 2);
}
private void btn24_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 3);
}
private void btnNovo_Click(object sender, EventArgs e)
{
resetTxt();
fecho += Convert.ToDouble(txtPreco.Text);
listaProduto.Items.Clear();
listaPreco.Items.Clear();
listaUnidade.Items.Clear();
txtPreco.Clear();
soma = 0;
}
private void btnRetirarSelec_Click(object sender, EventArgs e)
{
if (listaProduto.SelectedIndex >= 0)
{
int index = listaProduto.SelectedIndex;
double count = double.Parse(listaUnidade.Items[index].ToString());
soma -= count * precoBebidas[index];
listaUnidade.Items.RemoveAt(index);
listaPreco.Items.RemoveAt(index);
listaProduto.Items.RemoveAt(index);
txtPreco.Text = soma.ToString();
}
}
private void btnReduzQnt_Click(object sender, EventArgs e)
{
int index = -1;
if (listaProduto.SelectedIndex >= 0)
{
index = listaProduto.SelectedIndex;
}
else if (listaPreco.SelectedIndex >= 0)
{
index = listaPreco.SelectedIndex;
}
else if (listaUnidade.SelectedIndex >= 0)
{
index = listaUnidade.SelectedIndex;
}
if (index >= 0)
{
double count = double.Parse(listaUnidade.Items[index].ToString());
if (count > 1)
{
soma -= precoBebidas[index];
soma -= precoAlimentacao[index];
listaUnidade.Items[index] = count - 1;
listaPreco.Items[index] = Math.Round(precoBebidas[index] * (count - 1), 2);
listaPreco.Items[index] = Math.Round(precoAlimentacao[index] * (count - 1), 2);
txtPreco.Text = soma.ToString();
}
else
{
listaUnidade.Items.RemoveAt(index);
listaPreco.Items.RemoveAt(index);
listaProduto.Items.RemoveAt(index);
txtPreco.Text = soma.ToString();
}
}
}
private void btnFechoC_Click(object sender, EventArgs e)
{
txtPreco.Text = fecho.ToString();
txtPreco.BackColor = Color.Green;
txtPreco.ForeColor = Color.White;
txtPreco.Font = new Font("Microsoft Sans Serif", 11, FontStyle.Bold);
label2.Text = "Saldo Final";
MessageBox.Show("A caixa foi Encerrada.");
fecho = 0;
}
private void btnReturn_Click(object sender, EventArgs e)
{
}
}
}
I'm sorry about some of the Portuguese elements in the code. Can anyone help out on how to do this? I'm completly lost on this one.
I thought of creating an array and making every button click start by saving the "status quo" to the erray and having it update the listboxes through a button. But I couldn't implement it. The fixed numbers on arrays seems to be the factor.
When you say fixed numbers on arrays, do you mean that it is a hindrance that they can only be of pre-defined sizes?
If that's the case, then use a List. First import the necessary library then create the list, both as shown below:
using System.Collections.Generic;
List<type> myList = new List<type>();
You can add as many items to a list without pre-defining its size.
To append items to the list use:
myList.Append(someData);
To then access the last action made by the user (which you have already appended to the list), use:
type lastAction = myList[-1];
Hello I'm trying to click a button to remove and item but I keep getting an
'IndexOutOfRange' Exception.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
clientNum = clientList.Items.Count;
for (int i = 0; i < clientNum; i++)
{
nameSeletion[i] = clientList.Items[i].ToString();
}
if (dateSeletion[clientList.SelectedIndex] != null)
{
dateCalender.SelectionStart = todayDate[clientList.SelectedIndex];
Check();
}
else
{
nameLbl.Text = nameSeletion[clientList.SelectedIndex];
dateText.Text = "";
}
}
The if (dateSeletion[clientList.SelectedIndex] != null) is where I'm having the error.
The button code is
private void button1_Click(object sender, EventArgs e)
{
clientList.Items.Remove(clientList.Items[clientList.SelectedIndex]);
}
the dateSelection is defined in the save button and Initialization
private void SaveBtn_Click(object sender, EventArgs e)
{
//save the list array for names
for (int i = 0; i < clientNum; i++)
{
nameSeletion[i] = clientList.Items[i].ToString();
}
dateSeletion[clientList.SelectedIndex] = dateCalender.SelectionStart.Date.ToShortDateString() +
" " + clientTime.Value.ToShortTimeString();
todayDate[clientList.SelectedIndex] = dateCalender.SelectionStart;
dateCalender.BoldedDates = todayDate;
Check();
}
public ClientForm()
{
InitializeComponent();
clientNum = clientList.Items.Count;
todayDate = new DateTime[clientNum];
dateSeletion = new string[clientNum];
nameSeletion = new string[clientNum];
clientTime.CustomFormat = "hh:mm tt";
//initialize the list array for names
for (int i = 0; i < clientNum; i++)
{
nameSeletion[i] = clientList.Items[i].ToString();
}
}
Try this
clientList.RemoveAt(clientList.SelectedIndex);
I'm sorry that the title is confusing but I did not know how to ask this question; if someone can help with a better title I would appreciate it.
I am building a database of players and their match performance. The matches are displayed using a tab control, inside the matches are fields that are stored in a panel. The amount of matches goes up to 5, therefore each field is an array of size 5 to represent different values for different matches. I have ran into the problem of trying to save the amount of tabs (matches) there are for that unique player.
Because the amount of tabs carries over to the next player shown, I tried to iterate through all the matches and all the fields for that player, determine which matches contain empty fields and respectively delete that tab (match). So if player 1 has 3 matches with values in fields, but player 2 only has 2 matches that contain values in fields, the 3rd match (tab) will be deleted as the fields have no values.
to better explain, this is the GUI:
Picture
My attempt at iterating through the field of each match looks like this:
int[] csNumberTF = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
int i = 0;
while (i < 5)
{
if (csNumberTF[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
i++;
}
However I am presented with the error: Cannot implicitly convert type 'int' to 'int[]'
I would really appriciate if someone could help me out here, I understand that the code is long but It is organised and titled so that should help.
Full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
namespace Assignment1_Template2
{
public partial class Form1 : Form
{
// =======================DATA STRUCTURE ===========================
[Serializable]
private struct Player
{ //CONSTRUCTOR
public Player(int noOfMatches)
{
uniquePlayerId = new int[noOfMatches];
playerIgName = "";
contactStreet = "";
contactTown = "";
contactPostcode = "";
contactEmail = "";
contactTelephone = "";
imagePath = "";
matchesCount = 0;
csNumber = new int[noOfMatches];
killsNumber = new int[noOfMatches];
deathsNumber = new int[noOfMatches];
assistsNumber = new int[noOfMatches];
minutesNumber = new int[noOfMatches];
for (int i = 0; i < noOfMatches; ++i)
{
uniquePlayerId[i] = 0;
csNumber[i] = 0;
killsNumber[i] = 0;
deathsNumber[i] = 0;
assistsNumber[i] = 0;
minutesNumber[i] = 0;
}
}
//DATA TYPES
public int[] uniquePlayerId;
public int[] csNumber;
public int[] killsNumber;
public int[] deathsNumber;
public int[] assistsNumber;
public int[] minutesNumber;
public int matchesCount;
public string playerIgName;
public string contactStreet;
public string contactTown;
public string contactPostcode;
public string contactEmail;
public string contactTelephone;
public string imagePath;
}
//GLOBAL VARIABLES
public ArrayList GameDB;
public ArrayList playerMatch;
private int currentEntryShown = 0;
private int numberOfEntries = 0;
private string filename = "W:\\test.dat";
public string prevImage = "";
// =========================================================================
// ====================== STARTING POINT ===================================
// =========================================================================
public Form1()
{
InitializeComponent();
GameDB = new ArrayList();
LoadData();
ShowData();
UpdatePrevNextBtnStatus();
}
// =========================================================================
// ========================= BUTTON ACTION HANDLERS ========================
// =========================================================================
private void showPreviousBtn_Click(object sender, EventArgs e)
{
--currentEntryShown;
ShowData();
UpdatePrevNextBtnStatus();
}
private void showNextBtn_Click(object sender, EventArgs e)
{
++currentEntryShown;
if (currentEntryShown < GameDB.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void addNewPlayerBtn_Click(object sender, EventArgs e)
{
++numberOfEntries;
currentEntryShown = numberOfEntries - 1;
Player aNewStruct = new Player(5);
GameDB.Add(aNewStruct);
ShowData();
addNewPlayerBtn.Enabled = true;
UpdatePrevNextBtnStatus();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
SaveData();
addNewPlayerBtn.Enabled = true;
UpdatePrevNextBtnStatus();
}
private void deletePlayerBtn_Click(object sender, EventArgs e)
{
numberOfEntries--;
GameDB.RemoveAt(currentEntryShown);
SaveData();
currentEntryShown--;
if (currentEntryShown <= GameDB.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.Title = "Select an image file";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.imagePath = openFileDialog1.FileName;
GameDB[currentEntryShown] = aNewStruct;
playerPictureBox.ImageLocation = openFileDialog1.FileName;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private void searchBtn_Click(object sender, EventArgs e)
{
string toFind;
string source;
toFind = searchInput.Text;
toFind = toFind.ToLower();
for (int i = 0; i < GameDB.Count; ++i)
{
source = ((Player)GameDB[i]).playerIgName + ((Player)GameDB[i]).contactStreet;
source = source.ToLower();
if (source.Contains(toFind))
{
currentEntryShown = i;
ShowData();
UpdatePrevNextBtnStatus();
break;
}
if (i == (GameDB.Count - 1))
{
MessageBox.Show(toFind + " not found");
}
}
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveData();
UpdatePrevNextBtnStatus();
}
private void addNewMatchBtn_Click(object sender, EventArgs e)
{
TabPage newTP = new TabPage();
if (tabMatches.TabCount <= 4)
{
tabMatches.TabPages.Add(newTP);
int TabPageNumber = tabMatches.SelectedIndex + 1;
tabMatches.TabPages[TabPageNumber].Text = "Match " + (TabPageNumber + 1);
tabMatches.SelectTab(TabPageNumber);
deleteMatchBtn.Enabled = true;
panel1.Parent = tabMatches.SelectedTab;
}
ShowData();
}
private void deleteMatchBtn_Click(object sender, EventArgs e)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
int lastTabNumber = tabMatches.TabCount - 1;
tabMatches.SelectTab(lastTabNumber);
if (tabMatches.SelectedIndex < 1) deleteMatchBtn.Enabled = false;
}
// =========================================================================
// ================ HANDLE DATA CHANGES BY USER ============================
// =========================================================================
private void playerIdBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.uniquePlayerId[0] = Convert.ToInt32(playerIdBox.Text);
GameDB[currentEntryShown] = aNewStruct;
}
private void playerIgNameBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.playerIgName = playerIgNameBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactStreetBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactStreet = contactStreetBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactTownBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactTown = contactTownBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactPostcodeBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactPostcode = contactPostcodeBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactEmailBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactEmail = contactEmailBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactTelephoneBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactTelephone = contactTelephoneBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
//Match data
private void tabMatches_SelectedIndexChanged(object sender, EventArgs e)
{
panel1.Parent = tabMatches.SelectedTab;
ShowData();
}
private void numCS_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.csNumber[tabMatches.SelectedIndex] = (int)numCS.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numKills_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.killsNumber[tabMatches.SelectedIndex] = (int)numKills.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numDeaths_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.deathsNumber[tabMatches.SelectedIndex] = (int)numDeaths.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numAssists_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.assistsNumber[tabMatches.SelectedIndex] = (int)numAssists.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numMinutes_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.minutesNumber[tabMatches.SelectedIndex] = (int)numMinutes.Value;
GameDB[currentEntryShown] = aNewStruct;
}
// =========================================================================
// ================= HELPER METHODS FOR DISPLAYING DATA ====================
// =========================================================================
private void ShowData()
{
playerIdBox.Text = ((Player)GameDB[currentEntryShown]).uniquePlayerId[0].ToString();
playerIgNameBox.Text = ((Player)GameDB[currentEntryShown]).playerIgName;
contactStreetBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactStreet;
contactTownBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactTown;
contactPostcodeBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactPostcode;
contactEmailBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactEmail;
contactTelephoneBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactTelephone;
playerPictureBox.ImageLocation = ((Player)GameDB[currentEntryShown]).imagePath;
numCS.Value = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
numKills.Value = ((Player)GameDB[currentEntryShown]).killsNumber[tabMatches.SelectedIndex];
numDeaths.Value = ((Player)GameDB[currentEntryShown]).deathsNumber[tabMatches.SelectedIndex];
numAssists.Value = ((Player)GameDB[currentEntryShown]).assistsNumber[tabMatches.SelectedIndex];
numMinutes.Value = ((Player)GameDB[currentEntryShown]).killsNumber[tabMatches.SelectedIndex];
int[] csNumberTF = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
int i = 0;
while (i < 5)
{
if (csNumberTF[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
}
i++;
}
}
private void UpdatePrevNextBtnStatus()
{
if (currentEntryShown > 0) showPreviousBtn.Enabled = true;
else showPreviousBtn.Enabled = false;
if (currentEntryShown < (numberOfEntries - 1)) showNextBtn.Enabled = true;
else showNextBtn.Enabled = false;
label1.Text = "Player ID";
label3.Text = (currentEntryShown + 1) + " / " + numberOfEntries;
}
// =========================================================================
// =============== HELPER METHODS FOR LOADING AND SAVING ===================
// =========================================================================
private void SaveData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
try
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, GameDB);
MessageBox.Show("Data saved to " + filename, "FILE SAVE OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Could not serialise to " + filename,
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
fs.Close();
}
catch
{
MessageBox.Show("Could not open " + filename +
" for saving.\nNo access rights to the folder, perhaps?",
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void LoadData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
try
{
BinaryFormatter bf = new BinaryFormatter();
GameDB = (ArrayList)bf.Deserialize(fs);
currentEntryShown = 0;
numberOfEntries = GameDB.Count;
}
catch
{
MessageBox.Show("Could not de-serialise from " + filename +
"\nThis usually happens after you changed the data structure.\nDelete the data file and re-start program\n\nClick 'OK' to close the program",
"FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
fs.Close();
Environment.Exit(1);
}
fs.Close();
}
catch
{
if (MessageBox.Show("Could not open " + filename + " for loading.\nFile might not exist yet.\n(This would be normal at first start)\n\nCreate a default data file?",
"FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
Player aNewStruct = new Player(5);
GameDB.Add(aNewStruct);
numberOfEntries = 1;
currentEntryShown = 0;
}
}
}
// =========================================================================
// ====================== HELPER METHODS FOR SORTING =======================
// =========================================================================
private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
GameDB.Sort(new PlayerNameComparer());
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Player)x).playerIgName.CompareTo(((Player)y).playerIgName);
}
}
// =========================================================================
// ====================== MISC STUFF =======================================
// =========================================================================
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void developerToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("By Szymon Zmudzki: 13042432");
}
}
}
Try change this
int[] csNumberTF = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
int i = 0;
while (i < 5)
{
if (csNumberTF[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
}
i++;
}
To use the csNumber which is int[] in the for loop
int i = 0;
while (i < 5)
{
if (((Player)GameDB[currentEntryShown]).csNumber[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
}
i++;
}
To find out the value of tabMatches.TabCount, add this line when you run the program and see it in the output window: (To answer your question, I would assume the TabCount start with 1. That's the default value of any .Count() call to an array of integer. But this is the best way to know for sure.)
System.Diagnostics.Debug.WriteLine(tabMatches.TabCount);
I am new to C# and was wondering how to get a file by the name the user puts into a text box, then load that data into an array and display each item in the array into separate text boxes to then be edited and saved to that file again
namespace test
{
public partial class Form1 : Form
{
private TextBox[] textBoxes;
private Button[] buttons;
private const string fileName = (getFile.Text);
public Form1()
{
InitializeComponent();
textBoxes = new TextBox[] { textBox1, textBox2, textBox3, textBox4 };
buttons = new Button[] { button1, button2, button3, button4 };
}
private static void ReplaceLineInFile(string path, int lineNumber, string newLine)
{
if (File.Exists(path))
{
string[] lines = File.ReadAllLines(path);
lines[lineNumber] = newLine;
File.WriteAllLines(path, lines);
}
}
private void Form1_Load(object sender, EventArgs e)
{
LoadFile();
}
private void LoadFile()
{
if (!File.Exists(fileName))
{
WriteAllLines();
return;
}
string[] lines = File.ReadAllLines(fileName);
if (lines.Length != textBoxes.Length)
{
// the number of lines in the file doesn't fit so create a new file
WriteAllLines();
return;
}
for (int i = 0; i < lines.Length; i++)
{
textBoxes[i].Text = lines[i];
}
}
private void WriteAllLines()
{
// this will create the file or overwrite an existing one
File.WriteAllLines(fileName, textBoxes.Select(tb => tb.Text));
}
private void button1_Click(object sender, EventArgs e) // save line 1
{
ReplaceLineInFile(fileName, 0, textBox1.Text);
}
private void button2_Click(object sender, EventArgs e) // save line 2
{
ReplaceLineInFile(fileName, 1, textBox2.Text);
}
private void button3_Click_1(object sender, EventArgs e) // save line 3
{
ReplaceLineInFile(fileName, 2, textBox3.Text);
}
private void button4_Click(object sender, EventArgs e) // save line 4
{
ReplaceLineInFile(fileName, 3, textBox4.Text);
}
private void button_Click(object sender, EventArgs e) // save all
{
Button button = sender as Button;
if (button != null)
{
int lineNumber = Array.IndexOf(buttons, button);
if (lineNumber >= 0)
{
ReplaceLineInFile(fileName, lineNumber, textBoxes[lineNumber].Text);
}
}
}
private void button5_Click(object sender, EventArgs e) // get file
{
if (File.Exists(getFile.Text))
{
//shows message if testFile exist
MessageBox.Show("File " + getFile.Text + " Exist ");
}
else
{
//create the file testFile.txt
File.Create(getFile.Text);
MessageBox.Show("File " + getFile.Text + " created ");
}
}
}
}
First place a TableLayoutPanel control onto your form. This will help easily placing the other controls.
Dock this panel where you want, then Edit the columns and set the SizeType for both columns to AutoSize. Set AutoScroll to true. Leave the control with the default name tableLayoutPanel1.
Now change the methods. Remove all buttonX_Click methods and paste this code instead of the existing LoadFile:
private void button1_Click(object sender, EventArgs e)
{
string[] lines = File.ReadAllLines(fileName);
// Clear the existing rows
tableLayoutPanel1.RowStyles.Clear();
for (int i = 0; i < lines.Length; i++)
{
// Add a new row
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
// Create the TextBox
TextBox txt = new TextBox();
// Add any initializations for the text box here
txt.Text = lines[i];
// Create the button
Button btn = new Button();
// Add any initializations for the button here
btn.Text = i.ToString();
// Handle the button's click event
btn.Click += btn_Click;
// This value helps the button know where it is and which TextBox it is associated to
btn.Tag = new object[] { i, txt };
btn.Width = 30;
// Add the controls to the created row
tableLayoutPanel1.Controls.Add(txt, 0, i);
tableLayoutPanel1.Controls.Add(btn, 1, i);
}
}
void btn_Click(object sender, EventArgs e)
{
object[] btnData = (object[]) ((Control) sender).Tag;
// The values are inside the sender's Tag property
ReplaceLineInFile(fileName, (int)btnData[0], ((TextBox)btnData[1]).Text);
}
UPDATE: This is the whole source of the class, corrected:
namespace test
{
public partial class Form1 : Form
{
private string fileName;
public Form1()
{
InitializeComponent();
}
private void ReplaceLineInFile(int lineNumber, string newLine)
{
if (File.Exists(fileName))
{
string[] lines = File.ReadAllLines(fileName);
lines[lineNumber] = newLine;
File.WriteAllLines(fileName, lines);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void LoadFile()
{
string[] lines = File.ReadAllLines(fileName);
// Clear the existing rows
tableLayoutPanel1.RowStyles.Clear();
for (int i = 0; i < lines.Length; i++)
{
// Add a new row
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
// Create the TextBox
TextBox txt = new TextBox();
// Add any initializations for the text box here
txt.Text = lines[i];
// Create the button
Button btn = new Button();
// Add any initializations for the button here
btn.Text = i.ToString();
// Handle the button's click event
btn.Click += btn_Click;
// This value helps the button know where it is and which TextBox it is associated to
btn.Tag = new object[] { i, txt };
btn.Width = 30;
// Add the controls to the created row
tableLayoutPanel1.Controls.Add(txt, 0, i);
tableLayoutPanel1.Controls.Add(btn, 1, i);
}
}
void btn_Click(object sender, EventArgs e)
{
object[] btnData = (object[])((Control)sender).Tag;
// The values are inside the sender's Tag property
ReplaceLineInFile((int)btnData[0], ((TextBox)btnData[1]).Text);
}
private void button_Click(object sender, EventArgs e) // save all
{
List<string> lines = new List<string>();
for (int i = 0; i < tableLayoutPanel1.RowCount; i++)
{
lines.Add(((TextBox)tableLayoutPanel1.Controls[i * 2]).Text);
}
File.WriteAllLines(fileName, lines.ToArray());
}
private void button5_Click(object sender, EventArgs e) // get file
{
fileName = getFile.Text;
if (File.Exists(fileName))
{
//shows message if testFile exist
MessageBox.Show("File " + fileName + " Exist ");
}
else
{
//create the file testFile.txt
File.Create(fileName);
MessageBox.Show("File " + fileName + " created ");
}
LoadFile();
}
}
}
i just made a file editor, it contains a listview and a textbox, i made that when i select and item from the list view it appears in the textbox, the text is japanese, and when i select a japanese text or line, it gives me an error: InvalidArgument: Value '0' is not valid for 'index'
can you guys help me ? this is my code:
private void Form1_Load(object sender, EventArgs e)
{
}
private void menuItem2_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
textBox1.Text = "";
menuItem12.Text = "file type is: ";
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.Filter = "All Files (*.*)|*.*";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
path = ofd.FileName;
BinaryReader br = new BinaryReader(File.OpenRead(path), Encoding.GetEncoding("SHIFT-JIS"));
foreach (char mychar in br.ReadChars(4)) menuItem12.Text += mychar;
if (menuItem12.Text != "file type is: TXTD")
{
MessageBox.Show("This is not a TXTD file...", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
MessageBox.Show("File opened Succesfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
br.BaseStream.Position = 0x8;
int Pntrnum = br.ReadInt16();
menuItem11.Visible = true;
menuItem11.Text = Pntrnum.ToString();
List<int> offsets = new List<int>();
br.BaseStream.Position = 0x10;
for (int i = 0; i < Pntrnum; i++)
{
offsets.Add(br.ReadInt32());
}
Dictionary<int, string> values = new Dictionary<int, string>();
for (int i = 0; i < offsets.Count; i++)
{
int currentOffset = offsets[i];
int nextOffset = (i + 1) < offsets.Count ? offsets[i + 1] : (int)br.BaseStream.Length;
int stringLength = (nextOffset - currentOffset - 1) / 2;
br.BaseStream.Position = currentOffset;
var chars = br.ReadChars(stringLength);
values.Add(currentOffset, new String(chars));
}
foreach (int offset in offsets)
{
listView1.Items.Add(offset.ToString("X")).SubItems.Add(values[offset]);
}
br.Close();
br = null;
}
}
ofd.Dispose();
ofd = null;
}
private void menuItem4_Click(object sender, EventArgs e)
{
this.Close();
}
private void menuItem6_Click(object sender, EventArgs e)
{
BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
int number_pointers = Convert.ToInt32(menuItem11.Text);
Encoding enc = Encoding.GetEncoding("SHIFT-JIS");
bw.BaseStream.Position = 0x10;
int curr_pointer = 4 + number_pointers * 4;
for (int i = 0; i < number_pointers; i++)
{
bw.Write(curr_pointer);
curr_pointer += enc.GetByteCount(listView1.Items[i].SubItems[1].Text) + 1;
}
for (int i = 0; i < number_pointers; i++)
bw.Write(enc.GetBytes(listView1.Items[i].SubItems[1].Text + '\0'));
bw.Flush();
bw.Close();
bw = null;
}
private void menuItem8_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = Application.ExecutablePath;
sfd.Filter = "Text Files (*.txt)|*.txt";
sfd.Title = "Save Text file";
DialogResult result = sfd.ShowDialog();
if (result == DialogResult.Cancel)
return;
StreamWriter wwrite = new StreamWriter(sfd.FileName, false, Encoding.GetEncoding("SHIFT-JIS"));
for (int i = 0; i < listView1.Items.Count; ++i)
{
string Ptrs = listView1.Items[i].SubItems[0].Text;
string Strs = listView1.Items[i].SubItems[1].Text;
wwrite.WriteLine(i.ToString() + " > " + Ptrs + " > " + Strs);
}
wwrite.Close();
}
private void menuItem5_Click(object sender, EventArgs e)
{
MessageBox.Show("TXTD Editor by Omarrrio v0.1 Alpha\n2013 Copyrighted crap and whatever", "About...", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = listView1.SelectedItems[0].SubItems[1].Text;
}
private void button1_Click(object sender, EventArgs e)
{
listView1.SelectedItems[0].SubItems[1].Text = textBox1.Text;
}
private void menuItem12_Click(object sender, EventArgs e)
{
}
}
}
Before accessing the SelectedItems index, you should check if there are any items selected.
private void button1_Click(object sender, EventArgs e)
{
if(listView1.SelectedItems.Count > 0)
textBox1.Text = listView1.SelectedItems[0].SubItems[1].Text;
}
You may also want to perform a check to ensure that SubItems has an index of 1 before using it.