【发布时间】:2011-10-09 14:03:39
【问题描述】:
我有这个代码:
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:
这是我重写某些部分后的全新代码,但我仍然遇到同样的问题
【问题讨论】:
-
你到底是哪一行超出了数组的边界?如果您通过 Visual Studio 运行程序,它将在问题点中断。
标签: c# datagridview rows