Manipulating ADO.NET datatable rows and columns - c#

I have a datatable with columns a,b,c,d,e.
When column b is null, I want to set its value to the value of column a and then set all the other columns for that particular row to an empty string.

Try this:
System.Data.DataRow r = dt.Rows[0];
if ( r["b"] == System.DbNull.Value ) //DbNull assumes the nulls are coming from DB. If they are set to null via your code then you can use good old null instead.
{
r["b"] = r["a"];
r["c"] = "";
r["d"] = "";
}

Related

How to check if any or all of gridview column values exists in a Datatable

I have a Datatable that consists of more than 1000 record and a gridview that contains multiple records.I want to check if values present in grid view column for ex:- "AID" exists in datatable's AID column values. If any value of the gridview AID exists in Datatable AID i want to set a bool flag to true if no value exists in Datatable then to false.I want to check all values at a time, not one by one using for loop etc.I have tried the folowing code
List<string> lstInvdiscItem = (from row in dtinv.AsEnumerable()
select Convert.ToString(row["AID"])).ToList();
foreach (DataGridViewRow row in GrdItDetail.Rows)
{
string invdiscitem = row.Cells["AID"].Value.ToString();
int result = dtinv.Rows.IndexOf(dtinv.AsEnumerable().Where(g => g.Field<String>(0) == invdiscitem).FirstOrDefault());
if (result >= 0)
{
DiscFlag = true;
}
}
But above code checks one value at a time.My requirement is to check all values at a time just as we do using "IN" clause in sqlserver.
How can I achieve this task using c#.Any ideas? Any suggestions?

How to remove null datarow from datatable except Autoincrement column

I have a datatable with one autoincrement column. And I want to remove the row which contain null or white space values in all columns except autoincrement column.
var dr = TempRowToSelectionDT.Rows.Cast<DataRow>().Where(row => !row.ItemArray.All(field => field is System.DBNull || string.Compare((field as string).Trim(), string.Empty) == 0)).ToArray();
TempRowToSelectionDT is my datatable. I cannot remove the null rows in that datatable. Because I cannot filter column in itemarray and autoincrement column always has values. So I want to remove the rows in that datatable which contains null values in all cells except autoincrement column
Try this.
Dim dtSociete As New DataTable
dtSociete.Columns.Add("EmpID")
dtSociete.Columns.Add("EmpFName")
dtSociete.Columns.Add("EmpLName")
dtSociete.Rows.Add("1", "Faraz", "Ahmed")
dtSociete.Rows.Add("2", "Saad", "Aslam")
dtSociete.Rows.Add("3", "", "")
dtSociete.Rows.Add("4", "", "")
dtSociete = dtSociete.AsEnumerable().Where(Function(r) r.Field(Of String)("EmpName") <> "" And r.Field(Of String)("Descrip") <> "").CopyToDataTable()

get index of DataTable column with name

I have some code which sets the value of cells in a DataRow by column name i.e.
row["ColumnName"] = someValue;
I want to also set the value for this row in the column immediately to the right of the one found above. Clearly if I was getting the cell by index rather than by column name this would be easy. So is there a way of getting the column index from the column name thus allowing me to do:
row[index + 1] = someOtherValue;
i.e. do I need create some kind of dictionary of column index and column names when the table is initially created, or can I get the index from the column name later on without doing this?
You can use DataColumn.Ordinal to get the index of the column in the DataTable. So if you need the next column as mentioned use Column.Ordinal + 1:
row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;
Warning:
This code returns the next column, so the one after ColumnName, as requested in the question.
Try this:
int index = row.Table.Columns["ColumnName"].Ordinal;
You can simply use DataColumnCollection.IndexOf
So that you can get the index of the required column by name then use it with your row:
row[dt.Columns.IndexOf("ColumnName")] = columnValue;
I wrote an extension method of DataRow which gets me the object via the column name.
public static object Column(this DataRow source, string columnName)
{
var c = source.Table.Columns[columnName];
if (c != null)
{
return source.ItemArray[c.Ordinal];
}
throw new ObjectNotFoundException(string.Format("The column '{0}' was not found in this table", columnName));
}
And its called like this:
DataTable data = LoadDataTable();
foreach (DataRow row in data.Rows)
{
var obj = row.Column("YourColumnName");
Console.WriteLine(obj);
}

Loop through each row in a column find a null value and replace in a datatable c#

I am trying to write a linq query or another way that will loop through all the rows in a column within a data table.
The data column header is known in advanced. As it loops I want to be able to check for a null value in each cell and if found put a default value in, in the case below it is [dob].
Below is an example of a dataTable, I want to able to loop through the [dob] column and look for the null value and replace it with a default value say 01/01/1901.
[firstName], [lastname], [dob]
tester, testerSurname, null
tester2, tester2Surname, 25/04/1876
foreach (DataColumn column in table.Columns)
{
if (table.Rows.OfType<DataRow>().Any(r => r.IsNull(column)))
{
}
I have started above but could not find away of getting the value and assigning it to another value but could find the null.
You wouldn't loop through each row in a column, you would just loop through the rows and check that column for each row in the loop:
DataTable dt;
string col = "ColumnIAmCheckingForANullValue";
string def = "My Default Value for NULL";
foreach (DataRow row in dt.Rows) {
if (string.IsNullOrEmpty(row[col].ToString())) {
row[col] = def;
}
}
If you're looking to perform a bulk database update, a Linq query is not the best way to go about it. You're better off writing a SQL query to perform the update - the COALESCE operator will be your friend.
UPDATE tablename
SET dob = COALESCE(dob, '1901/01/01')
If u r using data table then u can also loop through columns in a row
foreach (DataRow dr in table.Rows)
{
foreach (DataColumn clm in table.Columns)
{
if (dr[clm] == DBNull.Value)
{
dr[clm] = GetDefaultValueForColumn[clm.ColumnName];
}
}
}
If checking for DBNull, the code from mikeschuld's answer should work:
DataTable dt;
string col = "ColumnIAmCheckingForANullValue";
string anotherValue = "My Default Value for NULL";
foreach (DataRow row in dt.Rows) {
if (row[col] is DBNull) {
row[col] = anotherValue;
}
}
You can remove NULL from data using query
SELECT ISNULL(col, '') FROM MyTable

datatable select rows

I am using a datatable created by program. In this datatable i want to insert values in some specified columns.
Initially I am inserting primary key values leaving remaining columns null, when I am querying datatable with recently inserted value in Primary column to update same row, I am facing error Missing operand after ID operator
Can any one tell me the exact issue.
I am trying following code:
dt.Rows.Add(1);
int insertedValue = 1;
DataRow[] dr = dt.Select("ID = '" + insertedValue.toString() + "'");
And the table structure after entring primary value is as follows.
ID Volumn1 Volumn2 volumn3
--------------------------------------
1
You can do this more cleanly with LINQ and make this a strongly typed operation.
Something like:
dt.Rows.Add(1);
int insertedValue = 1;
var result =
dt.AsEnumerable().Where( dr => dr.Field<int>( "ID" ) == insertedValue );
Working example:
DataTable dt = new DataTable();
dt.Columns.Add( "ID", typeof( int ) );
dt.Rows.Add( 1 );
var result = dt.AsEnumerable().Where( dr => dr.Field<int>( "ID" ) == 1 );
You can simply format the selection string as shown below:
DataRow[] dr = dt.Select(string.Format("ID ='{0}' ", insertedValue));
Feel free to let me know if this works for you.. Thanks
You do not need ' ' in your filter.
I think this should work:
DataRow[] dr = dt.Select("ID = " + insertedValue.toString());
By the way, reference System.Data.DataSetExtensions
If you are looking for a specific row and your datatable has a primary key you could use the Find method and target the primary key which would return just the row you want rather than an array:
DataRow foundRow = dt.Rows.Find([INSERT SEARCH PARAMETER HERE]);
if(foundRow != null)
{
TO SET A STRING EQUAL TO A FOUND VALUE:
string str = foundRow["COLUMN NAME / INDEX];
OR IF YOU ARE INSERTING A VALUE YOU CAN USE IT LIKE THIS:
foundRow["COLUMN NAME / INDEX"] = NEW VALUE;
}
select column of row
dt.Rows[0].Field<string>("MyColumnName")

Categories

Resources