Search code examples
c#sqlsql-serverdatagridview

AutoFill SQL Server from Datagridview c#


I have datagridview that connects to a database in SQL Server.

In the database, I have 2 columns NumCrimCase and Prosecutor where I need to fill Prosecutor

NumCrimCase Prosecutor
51-4462 км 23 уффуа
51-4540 км 23
51-4609 км 23
51-4462 км 23
51-4462 км 23
51-4462 км 23
51-4462 км 23
51-4540 км 23
51-4609 км 23
51-4462 км 23
51-4462 км 23
51-4462 км 23

You can see in NumCrimCase I have the same data and in Prosecutor I have empty rows.

For example:

filled row

NumCrimCase Prosecutor
51-4462 км 23 уффуа

and another unfilled row

NumCrimCase Prosecutor
51-4462 км 23

when NumCrimCase contains the same data.

I need to fill all same NumCrimCase into Prosecutor for all the same rows, and my form has a button that should do that.

I don't have idea how I can do it.

I tried sorting my columns by NumCrimCase, and fill rows latest values. That doesn't work.


Solution

  • You want to fill the Prosecutor column for rows with the same data in the NumCrimCase column, correct? You can solve this using an SQL query. For example, to update the Prosecutor column with the same value for all rows with the same NumCrimCase, you can use the following query:

    UPDATE table_name
    SET Prosecutor = (SELECT TOP 1 Prosecutor FROM table_name AS t2 WHERE t2.NumCrimCase = table_name.NumCrimCase)
    

    This query retrieves the Prosecutor value from any row with the same NumCrimCase for each row and updates all rows with that value. Of course, you should replace "table_name" with the name of your table. You can then connect this query to a button in your application to execute it when needed.