0
Try making the changes I've highlighted:
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string key = string.Empty; / need to reset key to empty each time
try
{
if (tab == null) //If Hashtable not yet loaded
{
tab = new Hashtable();//now refers to Field.
lines = File.ReadAllLines(path);
//The above Statement refers to Fields.
foreach (string line in lines)
{
// This statement refers to field so use if block to search for containing any equality = sign.
if (line.Contains("="))
{
string[] items = line.Split('=');
tab.Add(items[0], int.Parse(items[1]));
}
}
}
if (tab.ContainsKey(comboBox2.SelectedItem.ToString()))
{
key = comboBox2.SelectedItem.ToString();
textBox1.Text = tab[key].ToString();
}
else
{
MessageBox.Show("Invalid Key or Command Selected....\nPlease Select A Valid Device & Operation");
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(key)||lines==null) return;
int code;
if(!int.TryParse(textBox1.Text,out code))
{
MessageBox.Show("You Entered InValid Code.....\nPlease Enter A Valid Code Correctly.");
textBox1.Focus();
}
string search=key+"=";
int index = -1; // this should be -1
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].StartsWith(search))
{
index=i;
break;
}
}
if(index > -1 && Convert.ToInt32(tab[key])!=code) // this should be index > -1
{
lines[index]=search+code.ToString();
File.WriteAllLines(path, lines);// you should be writing the file, not reading it
tab[key]=code;
MessageBox.Show("The Revised Code has been Changed Successfully");
}
}
