【问题标题】:Is there an answer in int n = dataGridView1.Rows.Add();int n = dataGridView1.Rows.Add(); 中有答案吗?
【发布时间】:2019-10-16 07:27:21
【问题描述】:

我正在为一个新项目工作,我的问题是 2 个月前我停止了编程工作,所以我又遇到了这个问题。

private void LoadData()
{
    con.dataGet("Select * from [User]");
    DataTable dt = new DataTable();
    con.sda.Fill(dt);
    foreach(DataRow row in dt.Rows)
    {
        int n = dataGridView1.Rows.Add(); //Errors here
        dataGridView1.Rows[n].Cells["dgSno"].Value = n +1; //Not part of my database
        dataGridView1.Rows[n].Cells["dgName"].Value = row["Name"].ToString();
        dataGridView1.Rows[n].Cells["dgDob"].Value = Convert.ToDateTime(row["Dob"].ToString()).ToString("ddd/mm/yy");
        dataGridView1.Rows[n].Cells["dgEmail"].Value = row["Email"].ToString();
        dataGridView1.Rows[n].Cells["dgUserName"].Value = row["UserName"].ToString();
        dataGridView1.Rows[n].Cells["dgRole"].Value = row["Role"].ToString();
        dataGridView1.Rows[n].Cells["dgAddress"].Value = row["Address"].ToString();
    }
}

错误:An unhandled exception of type 'System.InvalidOperationException' occured in System.Windows.Forms.dll

【问题讨论】:

标签: c# sql-server row


【解决方案1】:

您应该直接使用NewRowDataTable 进行操作,初始化它,然后使用Add 它:

var row = dt.NewRow();
// init row
dt.Rows.Add(row);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多