【问题标题】:C# DataGridView columns 1 compare with columns 1 like this imageC# DataGridView 第 1 列与第 1 列比较,如下图
【发布时间】:2016-06-25 06:57:56
【问题描述】:

我想做一个比较:

if(already employee id == last cell employee)
{
    MessagBox.show(Your Value is duplicated)
}

As shown in image

【问题讨论】:

  • 你试过了吗?
  • 请用文字说明你的问题。

标签: c# winforms c#-4.0 datagridview ado.net


【解决方案1】:

这一点为您指明了正确的方向:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    // Data of inserted value
    var rowIndex = e.RowIndex;
    var colIndex = e.ColumnIndex;
    var insertedValue = (dataGridView1[colIndex, rowIndex].Value ?? "").ToString();

    foreach(DataGridViewRow row in dataGridView1.Rows)
    {
        // If current cell == insertedValue but not the same row
        if((row.Cells["ColumnID"].Value ?? "").ToString() == insertedValue && row.Index != rowIndex)
        {
            MessageBox.Show("Your Value is duplicated");
        }
    }
}

Linq 也是可能的:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    var insertedValue = (dataGridView1[e.ColumnIndex, e.RowIndex].Value ?? "").ToString();

    dataGridView1.Rows.Cast<DataGridViewRow>()
        .Where
        (   
            x => (x.Cells["ColumnID"].Value ?? "").ToString() == insertedValue
            && x.Index != e.RowIndex
        )
        .ToList()
        .ForEach(x => MessageBox.Show("Your Value is duplicated"));
}

请注意,这不会删除插入的值。因此,如果您再次插入相同的值,MessageBox 将提升 2 次。

【讨论】:

  • @NumanKibria 很高兴我能帮上忙。然后考虑将其标记为解决方案(钩在投票按钮下方)。
  • 我们可以让它作为单元格被选中,直到重复的 EmployeeID 从插入的单元格中删除或删除或输入新的不同值
  • @NumanKibria 你可以像dataGridView1[e.ColumnIndex, e.RowIndex].Value = String.Empty;这样清除ID。然后我会将MessageBox 的文本更改为No dublicates allowed. Please insert a unique value!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 2019-03-30
  • 2022-08-15
  • 2016-04-07
相关资源
最近更新 更多