У меня есть этот код:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13) {
db database = new db();
database.set_connection(Properties.Settings.Default.connection);
DataTable result = database.search(textBox1.Text, "", "");
if (result.Rows.Count == 0)
{
MessageBox.Show("nothing found", "error", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.SelectAll();
textBox1.Focus();
}
else {
if (dataGridView1.Rows.Count == 0)
{
DataGridViewRow row = new DataGridViewRow();
dataGridView1.Rows.Add(row);
row.Cells[0].Value = result.Rows[0]["title"].ToString();
row.Cells[1].Value = result.Rows[0]["code"].ToString();
row.Cells[2].Value = result.Rows[0]["sell"].ToString();
row.Cells[3].Value = "1";
row.Cells[4].Value = "";
decimal total = Convert.ToDecimal(result.Rows[0]["sell"].ToString()) * 1;
row.Cells[5].Value = total;
}
else {
bool found = false;
int position = 0;
foreach (DataGridViewRow ro in dataGridView1.Rows)
{
if (ro.Cells[0].Value.ToString() == result.Rows[0]["title"].ToString())
{
found = true;
position = ro.Index;
break;
}
}
if (found)
{
dataGridView1.Rows[position].Cells[3].Value = Convert.ToInt32(dataGridView1.Rows[position].Cells[3].Value) + 1;
decimal total = Convert.ToDecimal(dataGridView1.Rows[position].Cells[2].Value) * Convert.ToDecimal(dataGridView1.Rows[position].Cells[3].Value);
dataGridView1.Rows[position].Cells[5].Value = total;
}
else {
DataGridViewRow row = new DataGridViewRow();
dataGridView1.Rows.Add(row);
row.Cells[0].Value = result.Rows[0]["title"].ToString();
row.Cells[1].Value = result.Rows[0]["code"].ToString();
row.Cells[2].Value = result.Rows[0]["sell"].ToString();
row.Cells[3].Value = "1";
row.Cells[4].Value = "";
decimal total = Convert.ToDecimal(result.Rows[0]["sell"].ToString()) * 1;
row.Cells[5].Value = total;
}
}
}
}
}
Когда я запускаю свое приложение, я могу добавить первую строку без проблем, но когда я хочу добавить вторую строку, я получаю эту ошибку:
Specified argument was out of the range of valid values.
Parameter name: rowIndex
В чем проблема ??
РЕДАКТИРОВАТЬ:
ошибка происходит в:
+ row.Cells[0].Value 'row.Cells[0].Value' threw an exception of type 'System.ArgumentOutOfRangeException' object {System.ArgumentOutOfRangeException}
РЕДАКТИРОВАТЬ 2:
Этомой полный новый код после переписывания некоторых частей, но у меня все еще остается та же проблема