How to make a unique column in datagridview with c#?

2.9k views Asked by At

how to prevent repeating of rows in datagridview while adding rows?

I need to make a unique column like in sql.

is there any way to do this via properties window or programmaticalLy?

4

There are 4 answers

4
Vanest On BEST ANSWER

You can check the existing unique column value before adding the new one, something like,

    var rows = dataGridView1.Rows.OfType<DataGridViewRow>()
                                 .Where(x => x.Cells["cell1"].Value == "newCellVal1")
                                 .ToArray();
    if (rows == null || rows.Length == 0)
    {
        //New row is unique
        //Logic to add new row
    }
    else
    {
        //Row already exists with "newCellVal1"
        //Update the existing value rows
        rows[0].Cells["cell2"].Value = "newCellVal2"; //Coulmn "cell2" with a new value "newCellVal2"
        rows[0].Cells["cell3"].Value = "newCellVal3"; //Coulmn "cell3" with a new value "newCellVal3"
    }

Here, cellVal is the unique column name in the datagrid and newCellVal is the value of unique column from the new row. Also you can add combination of columns to check for unique values in the Any method.

Hope this helps...

1
Megha On

I wanted to add it as a comment but I dont have the privilege . Just to give you a hint if you are populating your dgv using list or something similar you coud use the "distinct" function and give it a try. If you are reading some text file that you need to write some code to remove the duplicates.

0
Albert Ricia On

to prevent user from adding new row, you can disable it from the properties window and set the allowusertoadd from true into false.

If you have a problem about the duplicate row or data, you have to check your datasources first.

And about making unique column, you can set it either from properties window and programatically.

Adding column from properties window, you can select the column properties and add or edit the column you want,

Programmatically, you can type this syntax : datagridview1.columns.add("Column1");, etc

0
Peter Brennan On

This is not done (directly) in the DataGridView.

You will, most propably, have bound the DataGridView to a DataSource like DataTable via .net data binding (a BindingSource). If not, do so right now by adding a DataSet to your project and create a new DataTable in it.

This (DataTable) gives you an in memory table of data, which can be populated with data in any way you like (loading from database, inserting programmatically).

You can then add constraints to columns of this table as described here.