【问题标题】:Table doesn't have a primary key when adding a new row to datatable向数据表添加新行时表没有主键
【发布时间】:2012-07-09 14:29:17
【问题描述】:

我有一个 Windows 形式的数据表,我想在表中添加一个新行。我总是收到错误

表没有主键。

问题是我根本不想要主键。它可能在表中重复了“ID”。 我的代码:

using (DataTable dt = new DataTable())
{
dt.Columns.Add("EntryDE", typeof(string));
dt.Columns.Add("Descr", typeof(string));
dt.Columns.Add("Id", typeof(int));
foreach (DataGridViewRow row in dgv.Rows)
{
    DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
    if (check.Value != null)
    {
        if ((bool)check.Value)
        {
            //this row has a checkBox set to true (tick is added)
            //add this row to dataTable ...
            DataRow myRow = (row.DataBoundItem as DataRowView).Row;
            DataRow dr = dt.NewRow();

            dr["EntryDE"] = myRow["ID"].ToString();        
            dr["Descr"] = myRow["EntryName"];               
            dr["Id"] = Id;    
                    dt.Rows.Add(dr);
        }
    }
}

感谢您的建议。

【问题讨论】:

  • 你的代码中的 dr["Id"] = Id 来自哪里?

标签: c# winforms datatable


【解决方案1】:

错误不是来自 DataTable,因为它有效:

    using (DataTable dt = new DataTable())
    {
        dt.Columns.Add("EntryDE", typeof(string));
        dt.Columns.Add("Descr", typeof(string));
        dt.Columns.Add("Id", typeof(int));

        for (int i = 0; i < 10; i++) 
        {
            DataRow dr = dt.NewRow();

            dr["EntryDE"] = "abc";
            dr["Descr"] = "xyz";
            dr["Id"] = 1;
            dt.Rows.Add(dr);
        }
    }

你还有其他问题。

【讨论】:

    【解决方案2】:

    您可能确实需要一个主键,因为没有它您以后将无法更新或删除行。

    如果 ID 字段将包含重复项,那么您应该添加另一列,将其命名为 primary_key 或任何您喜欢的名称,并将该列用作 PK。

    【讨论】:

      猜你喜欢
      • 2019-03-23
      • 2021-11-06
      • 2020-06-16
      • 2011-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多