ArguementOutOfRangeException 是未处理的错误

本文关键字:错误 未处理 ArguementOutOfRangeException | 更新日期: 2023-09-27 18:34:02

我对编程和 C# 很陌生。 在这里,我有争论超出范围异常。 我想在每次单击按钮时向数据网格视图添加新的数据行。 所以我使用变量"i"逐个增加值,并在使用"0"时更改行值,这意味着

dataGridView2.Rows[0].Cells[0].Value = textBox1.Text.ToString();

第一行代替"i"填充,但当使用"1"时,这意味着

dataGridView2.Rows[1].Cells[0].Value = textBox1.Text.ToString();

例外来了。做这样的事情的正确方法是什么?

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
    public SqlConnection conn;
    public int i = 0;
    private void Form2_Load(object sender, EventArgs e)
    {
        conn = new SqlConnection("Data Source=.''SQLEXPRESS; Integrated Security=sspi; Initial Catalog=student");
        conn.Open();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        string Sqlstr = "insert into student(name, pw)values(@name,@pw)";
        SqlCommand cmd = new SqlCommand(Sqlstr, conn);

        cmd.Parameters.AddWithValue("@name", textBox1.Text);
        cmd.Parameters.AddWithValue("@pw", textBox2.Text);

        if (cmd.ExecuteNonQuery() > 0)
        {
            i++;
            DataGridView dataGridView1 = new DataGridView();
            dataGridView2.Rows[i].Cells[0].Value = textBox1.Text.ToString();
            dataGridView2.Rows[i].Cells[1].Value = textBox2.Text.ToString();
        }
        label1.Text = Convert.ToString(i);
    }
}

}

ArguementOutOfRangeException 是未处理的错误

不必每次单击按钮时都定义新DataGridView,我相信您希望在插入数据库后在现有DataGridView中添加一个新行。你可以做:

if (cmd.ExecuteNonQuery() > 0)
{
    DataGridViewRow row = (DataGridViewRow)dataGridView2.Rows[0].Clone();
    row.Cells[0].Value = textBox1.Text.ToString();
    row.Cells[1].Value = textBox2.Text.ToString();
    dataGridView2.Rows.Add(row);
}

尝试编写新行之前,您必须添加新行。使用 dataGridView2.Rows.Add( something ) ,请查看 Add 方法。