I have a issue with my code in C#. I have set up a couple of DataTables with a primary key assigned to each of them. what I want to do is to retrieve a single row from a single column.
Lets say I have this code:
DataColumn Pcolumn = new DataColumn();
DataColumn[] key = new DataColumn[1];
Pcolumn.DataType = System.Type.GetType("System.Double");
Pcolumn.ColumnName = "length";
key[0] = Pcolumn;
table6F.Columns.Add(Pcolumn);
table6F.Columns.Add("Area", typeof(double));
table6F.Columns.Add("load", typeof(double));
table6F.Columns.Add("weigth", typeof(double));
table6F.PrimaryKey = key;
table.Rows.Add(6.0, 14.0, 17.8 , 11.0 );
table.Rows.Add(7.0, 16.2 , 20.7 , 16.0 );
And I want to retrieve the the "load" for the second row (20.7), I would like to search for 7.0, primary key column, in the Table. I dummy tested to do like this, just to test:
Object oV;
double load;
//Get an Table object given the specific row number, this dummy i always set to 0.
// Given Column
oV = table.Rows[0]["load"];
load = Convert.ToDouble(oV.ToString());
Is there a similar way to extract using the Primary key?
You can retrieve a row from a DataTable based on its primary key using the DataRowCollection.Find method. In your case it would be:
DataRow matchingRow = table.Rows.Find(7.0D);
double value = (double)matchingRow["load"];
You can use Find method to find a row using primary Key
DataRow row = dataTable.Rows.Find("your key");
if(null != row)
{
string value = row["ColumnName"];
}
Related
I'm trying to see if a row of a DataTable contains a value, but it says "System.Data.MissingPrimaryKeyException: 'Table doesn't have a primary key.'" I'm not sure why a key would be necessary to find a value in a row and need some guidance on how to correctly loo through the rows to find a value.
I labeled the if statement that throws the exception with comments.
DataTable OutputDV = new DataTable();
DataView ScrumTeams = ISBL.GetScrumTeams();
//this dataview returns this: [CountDate, ScrumTeam, DefectCount]
DataView allDefects = ISBL.GetDefects(dtstartdate, dtenddate);
//Adding the columns for the datview
DataColumn ScrumTeamName = new DataColumn("ScrumTeam", typeof(string));
ScrumTeamName.ReadOnly = true;
OutputDV.Columns.Add(ScrumTeamName);
//first create columns of all dates
foreach (DataRow x in allDefects.ToTable().Rows)
{
//if there isnt a column by name of x then add one
if (!OutputDV.Columns.Contains(x["CountDate"].ToString()))
{
OutputDV.Columns.Add(x["CountDate"].ToString());
}
//CODE BELOW CAUSES EXCEPTION:
//System.Data.MissingPrimaryKeyException: 'Table doesn't have a primary key.'
if (!OutputDV.Rows.Contains(x["ScrumTeam"].ToString()) || OutputDV.Rows.Count == 0)
{
OutputDV.Rows.Add(x["ScrumTeam"].ToString());
}
}
i have been using the disconnected model for my project. The issue is that i have used the data adapter .Fill command to fill my data table and it has been filled successfully but after filling the data table i cannot use the datatable.Find method to search data on the base of its primary key. Isn't data adapter suppose to assign everything including primary key after the fill command?
//DataRow r = dt.Rows.Find(BO.RoomNo);
This, gives error when debugged says no primary key exists
Thus,i have to use a foreach loop instead
foreach (DataRow r in dt.Rows)
{
if (BO.RoomNo == (int)r[1])
{
temp.RoomNo = (int)r[1];
temp.Category = (string)r[2];
temp.Price = (float)r[3];
temp.Status = (string)r[4];
}
}
You've to set PrimaryKey property of DataTable as mentioned below,
//ID is primary key
dt.PrimaryKey = new DataColumn[] { dt.Columns["ID"]};
i have 2 DataTables with Data (dtm and dtl).
I must find out if exist a DataRow from DataTable1 in Datatable2.
I have a combined primray key of 3 columns.
I know that i can get the DataTable primarykey like this.
DataColumn[] pkcol;
pkcol = dtm.PrimaryKey;
Is it possible to use the Find method like this?
if (dtl.Rows.Find(dtm[pkcol]) == null)
{
}
I must realize an DataTable Sync Method.
So i go foreach Datarow in dtm.Rows and Foreach Datarow in dtl.Rows.
It would be great if i can go ahead over the table and search for if exist the datarows primary key value in the table.
Any ideas?
Please help.
Thanks
According to MSDN DataRowCollection.Findalready is looking for rows with the given values in the PKs. So you don't even need to get the PKs, but simply an array of values, that matches the PKs in number and type:
// Create an array for the key values to find.
object[]findTheseVals = new object[3];
// Set the values of the keys to find.
findTheseVals[0] = "John";
findTheseVals[1] = "Smith";
findTheseVals[2] = "5 Main St.";
DataRow foundRow = table.Rows.Find(findTheseVals);
You would set the values to null to find your row.
I've a datatable, with column A, B, C. I've set column A's "is identity" property to true, but I can't add any row to the table now.
The code I'm trying is this:
dsA.dtA row = dsA.dtA.NewdtARow();
row.B = 1;
row.C = 2;
dsA.dtA.Rows.Add(row);
I'm getting NoNullAllowedException, but I don't understand why. Column A is PK as well. If I tried to set row.A = 5 (or any similiar) I'll get an error when I try to update the datatable saying "cannot insert explicit value for identity column in table when identity_insert is set to off"
How can I solve this issue? It's frustrating.
Do this way. Reference link
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.AutoIncrement = true;
column.AutoIncrementSeed = 1;
column.AutoIncrementStep = 1;
// Add the column to a new DataTable.
DataTable table = new DataTable("table");
table.Columns.Add(column);
DataRow oRow = table.NewRow();
table.Rows.Add(oRow);
Open the designer of the dataset xsd file and set the AutoIncrement, AutoIncrementSeed and AutoIncrementStep property of the column A in datatable for an existing column.
Try one of the these two:
Set field values:
row.A = null;
row.B = 1;
row.C = 3;
Add row to DataTable:
dtA.Rows.Add(null,1,2);
They are both the same just try any of them and it should get you going. Also remember that whenever you want to make a column auto-increment in DataTable then you have to insert null into it.
The way that I do it is
public void AppendtodtA(int num1, doubledouble1, string string1)
{
object[] RowArray = new object[] {null,(int)num1, (double) doubledouble1, (string) string1}
DataRow CurrentRow = dtA.NewRow();
CurrentRow.ItemArray = RowArray;
dtA.Rows.Add(CurrentRow);
}
use ItemArray property and leave a null in the place of the autoincremented column
AppendtodtA(MyNumber,MyDouble,MyString);
Then just call the method with your variables.
So i had to make a running balance column based on an existing data table.
I have the formulas and everything.
I would just like to know if it is possible to make another column in that data table and generically add data to it based on the result of the formula,
currently I loop through the table row by row and equate the last column, can I put the result in that same row?
Thanks everyone
DataColumn newColumn = new DataColumn("ColumnName", typeof(System.String)); // I considered the column datatype as string, u can give as u want
newColumn.DefaultValue = "Your Value";
dataTable.Columns.Add(newColumn);
We can add a new column with default value as above..
If you want add some other value means, go for for-loop or foreach..
foreach (DataRow DR in dataTable.Rows)
{
DR["ColumnName"] = "Your Value";
}
Yes, you can add a new column to the data table any time, and once added, can always set the value of the RunningBalance cell (column + row) to the value you calculated.
DataColumn runningBalanceColumn = myDataTable.Columns.Add("RunningBalance", typeof(Int64));
runningBalanceColumn[0] = RUNNING_BALANCE_FOR_FIRST_ROW;
// and so on
Also refer [MSDN][1]
// Create total column.
DataColumn totalColumn = new DataColumn();
totalColumn.DataType = System.Type.GetType("System.Decimal");
totalColumn.ColumnName = "total";
totalColumn.Expression = "Price+ Quantity";
// Add columns to DataTable.
...
table.Columns.Add(totalColumn);