Click to See Complete Forum and Search --> : referenceing datarow objects


soandos
September 2nd, 2009, 11:01 PM
generally speaking, if one wants to reference a datarow object datarow[rowindex] will work.
if there a way to reference one by what is in the ID column of a row, or must a for loop be used?
also, is there a way to turn datagridview rows into datarows?

using .net 3.5

rliq
September 3rd, 2009, 12:34 AM
If the DataTable has a Primary Key, then a member function will be generated in the DataTable automatically. Eg, if your Primary Key is called 'TeamId' of type UNIQUEIDENTIFIER, then the member function will be have a signature of:

FindByTeamId(Guid teamId);

This returns a strongly typed DataRow from your DataTable.

Otherwise, it's a loop I'm afraid. Therefore make sure it has a Primary Key!

rliq
September 3rd, 2009, 12:50 AM
The second part of your question....

I think you should be binding a DataTable to the DataGridView, therefore the DataGridRow's in the DataGrid will always match up with the DataRow's in the DataTable and vice versa. If you use the FindBy{PrimaryKey}() member I mentioned before, you should be able to solve any problems that arise....

soandos
September 3rd, 2009, 02:00 AM
im sorry i dont really understand.
i really have two problems:
1) a user selects a row in a datagridview control
2) take that row and change it

currently i use datagridview1.rows.index and pass that as a variable, and then do 2) , but that fails in a number of curcumstances, so i need to both get the primary key of the row selected in the datagridview and then acsess that row later.

could you please write a way of getting the unique ID from the datagridview?

thank you very much

rliq
September 3rd, 2009, 02:02 AM
How are you populating the DataGridView in the first place?

soandos
September 3rd, 2009, 02:11 AM
im using c# express 2008, which autogenerates a select statement that pulls in the data

soandos
September 3rd, 2009, 12:59 PM
Can someone people explain to me how to write data to a row specified by its UniqueKey?
currently I write the data based on rowindex, but that is flawed for many reasons.
any ideas anyone?

monalin
September 3rd, 2009, 01:11 PM
Is this what you want? You can access a column by the column name or the index.

datarow["columnName"]

If you have a datatable and you're trying to find the row where the ID column = 5 you could do this

DataRow[] rows = datatable.Select("id = 5");

soandos
September 3rd, 2009, 01:27 PM
But how would i write to that row?
for example, lets say i have a datarow with ID = 5
can i do something like:
datarow[] rowtoupdate = datatable.select("ID = 5");
rowtoupdate["columnname"] = "string that i want in that column"

or is there a better way?

JonnyPoet
September 6th, 2009, 04:10 PM
datarow[] row = datatable.Select("ID = 5");
row[0].BeginEdit();
row[0]["columnname"] = "string that i want in that column"
row[0].EndEdit();