DataGridView唯一单元格值c#

时间:2013-04-24 18:51:14

标签: c# datagridview

我在datagridview中保持单元格的值是唯一的... 让我解释一下:所以,我的数据库表包含2个属性,ownerID(主键)和ownerName ...

假设我的数据库中有3个条目:

    1 A
    2 B
    3 C

当我在datagridview中删除B并更新DB时,我留下了:

    1 A
    3 C

当我尝试添加新的所有者时,让我们说它是D,我希望他的ID为4,因为它是主键,但我得到的是:

    1 A
    3 C
    3 D

所以,我显然需要保持我的ownerID唯一。我正在使用这行代码来完成这项工作,但它正在产生上述结果:

    private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
    {
            dataGridViewOwner.CurrentRow.SetValues(dataGridViewOwner.RowCount);
    }

任何提示?

2 个答案:

答案 0 :(得分:0)

使datagridview中的单元格值保持唯一 您应该在数据库中创建唯一值。 要做到这一点: 1.ownerID应该是数据库中的IDENTITY 您可以在表设计器中设置它 创建表的脚本:

CREATE TABLE [dbo]。[YorTableName] (     [ownerID] [int] IDENTITY(1,1)NOT NULL,

[ownerName] [varchar](50) NULL

)ON [PRIMARY]

  1. 插入声明: 插入YorTableName(ownerName)值(@ownerName) 选择@@ Identity 只插入所有者名称,数据库为ownerID创建唯一值并将其插入行中选择@@ Identity将恢复此唯一值
  2. 3.使用DB

    返回的值更新datagridviewer中的字段ownerID

答案 1 :(得分:0)

private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
    {
            int max=0;
            for(int i=0;i<dataGridViewOwner.Rows.Count;i++)
              if(dataGridViewOwner.Rows[i].Cells[0].Value!=null && dataGridViewOwner.Rows[i].Cells[0].Value!=DBNull.Value )
              {
                  try
                   {
                         int pre= int.Parse(dataGridViewOwner.Rows[i].Cells[0].Value.ToString());
                        if(pre>max)
                              max=pre;
                   }
                  catch
                 {
                   }
              }//if
             max++;
            dataGridViewOwner.CurrentRow.Cells[0].Value=max;//if assume crrent row is target new row
    }