繁体   English   中英

DataGridView唯一单元格值C#

[英]DataGridView unique cell value c#

我在保持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);
    }

有小费吗?

若要使datagridview中的单元格值唯一,则应在数据库中设置唯一值。 为此,请执行以下操作:1.ownerID在数据库中应为IDENTITY。您可以在表设计器或脚本中将其设置为创建表:

创建表[dbo]。[YorTableName]([ownerID] [int] IDENTITY(1,1)NOT NULL,

[ownerName] [varchar](50) NULL

)在[PRIMARY]上

  1. 插入语句:插入YorTableName(ownerName)值(@ownerName)选择@@ Identity,仅插入ownername,数据库为ownerID创建唯一值,并将其插入行中选择@@ Identity检索此唯一值

3.使用从数据库返回的值更新datagridviewer中的字段ownerID

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
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM