简体   繁体   中英

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

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?

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.

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

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 .

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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