Search code examples
c#auto-generate

auto generate id to textbox and datagridview


I have a problem with my code; when I run my program it produces the following error: "Input string was not in a correct format".

Here is my code:

public String generateID()
{
    String newID = "";           
    String lastID =dataGridView1.Rows[dataGridView1.RowCount1].Cells[0].Value.ToString();                
    newID = lastID.Substring(1);
    int temp = Int32.Parse(newID) + 1;
    newID = "E" + temp.ToString("00");
    return newID;
}


private void btnInsert_Click(object sender, EventArgs e)
{            
    textBox1.Text = generateID();                       
}

Solution

  • This is because newID doesn't contain a string representation of an integer. Is the cell empty? You should ensure the cell will always contain a valid value. Alternatively, use Int32.TryParse to gracefully handle an error.