Get final result from data table - c#

I am creating a datatable with 3 columns as below and pushing the values into it from a while loop. Once the while loop is completed. I want to extract the validation values which are True or False and apply a condition to that, which will be like if all the values are "True" then I should get an output "True" if anyone of them is "False" I should get "False" value as output.
DataTable table = new DataTable(); table.Columns.Add("Id", typeof(int));
table.Columns.Add("Number", typeof(string));
table.Columns.Add("Validation", typeof(string));
For getting values of column Validation I am using the code below, but not sure how to apply the above condition and get final value.
DataView dv = new DataView(table);
DataTable dt = dv.ToTable(true, "Validation");

You can use the below code to iterate the datatable and check the value of each row.
foreach (DataRow dtRow in dtTable.Rows)
{
// On all tables' columns
foreach(DataColumn dc in dtTable.Columns)
{
var field1 = dtRow[dc].ToString();
}
}

This is what I used and the above issue was resolved. Added the reference for System.Data.DataSetExtensions.
string validationstr = "False";
bool Contains = table.AsEnumerable().Any(row => validationstr == row.Field<string>("Validation"));
if (Contains == true)
{
}
else
{
}

Related

Trying to get second row from DataTable

I'm trying to retrieve the second row from a DataTable but this is not returning a value. What could be the problem as the DropDown populates just fine.
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
DropDown.DataSource = dt;
DropDown.DataTextField = "FirstName";
DropDown.DataValueField = "FirstName";
DropDown.DataBind();
con.Close();
var secondRow = dt.Rows[2].ToString(); // This should return the second row in my datatable.
}
DataTable.Rows[int] will give you the DataRow object. If you do dt.Rows[2].ToString(), you are going to get the string representation of the object type.
The index starts at 0. Hence for 2nd row, you will query dt.Rows[1]. Further, You can extract the value of a column in the row and for that, you have to mention the column index or name like - dt.Rows[1][0] or dt.Rows[1]["col1"]
You can also loop through all the columns in the row like below:
foreach (DataColumn col in dt.Columns)
{
var columnValue = dt.Rows[1][col];
}

How to display specific row of data based on a column value

From this code I am trying to only display data rows that contain the fields "DBY" in the Station_From_Code column and "MAT" in the Station_To_Column. This will then be printed onto a HTML page. These fields are definitely in the datatable but when I run this cod the table is empty. I am not used to working with data tables in C# so apologies for the poor coding.
dynamic schedluedContent = JsonConvert.DeserializeObject(scheduledJson);
JArray items2 = new JArray();
foreach (JObject stops in schedluedContent.stops)
{
DataTable dt = new DataTable();
DataRow dr;
dr = dt.NewRow();
dr["From_Station_Code"] = stops["station_code"];
dr["To_Station_Code"] = stops["station_code"];
dt.Rows.Add(dr);
DataRow[] result = dt.Select("From_Station_Code = 'DBY' AND To_Station_Code = 'MAT'");
dt.Rows.Add(result);
GridViewTrainTimes.DataSource = dt;
GridViewTrainTimes.DataBind();
}
It's a long time I have not seen this style of code for working with database tables! EntityFramework comes to change and surely ease the way of working with database and prevent different risks of using SQL commands inside the code.
If you use EF, your code will become something like bellow:
var rows = myDBContext.MyTable.Where(x=>x.From_Station_Code == "DBY" && x.To_Station_Code == "MAT");
GridViewTrainTimes.DataSource = rows;
You can use find match rows and add in new datatable, that contains only your match rows data then you can bind this dt to gridview.
DataTable dt = new Datatable(); // Lets this datatable have data;
Datatable dt2 = new Datatable(); // Copy all matching rows
foreach (DataRow dr in dt.Rows)
{
if (dr["From_Station_Code"].ToString() == "DBY" && dr["To_Station_Code"].ToString() == "MAT")
{
dt2.Rows.Add(dr);
}
}
GridViewTrainTimes.DataSource = dt;
GridViewTrainTimes.DataBind();

How to Edit a row in the datatable

I have created a data table. It has 3 column Product_id, Product_name and Product_price
Datatable table= new DataTable("Product");
table.Columns.Add("Product_id", typeof(int));
table.Columns.Add("Product_name", typeof(string));
table.Columns.Add("Product_price", typeof(string));
table.Rows.Add(1, "abc", "100");
table.Rows.Add(2, "xyz", "200");
Now I want to find by index, and update that row.
say for e.g.
I want to change value of Product_name column to "cde" that has the Product_id column value : 2.
First you need to find a row with id == 2 then change the name so:
foreach(DataRow dr in table.Rows) // search whole table
{
if(dr["Product_id"] == 2) // if id==2
{
dr["Product_name"] = "cde"; //change the name
//break; break or not depending on you
}
}
You could also try these solutions:
table.Rows[1]["Product_name"] = "cde" // not recommended as it selects 2nd row as I know that it has id 2
Or:
DataRow dr = table.Select("Product_id=2").FirstOrDefault(); // finds all rows with id==2 and selects first or null if haven't found any
if(dr != null)
{
dr["Product_name"] = "cde"; //changes the Product_name
}
You can find that row with
DataRow row = table.Select("Product_id=2").FirstOrDefault();
and update it
row["Product_name"] = "cde";
Try the SetField method:
By passing column object :
table.Rows[rowIndex].SetField(column, value);
By Passing column index :
table.Rows[rowIndex].SetField(0 /*column index*/, value);
By Passing column name as string :
table.Rows[rowIndex].SetField("product_name" /*columnName*/, value);
If your data set is too large first select required rows by Select(). it will stop further looping.
DataRow[] selected = table.Select("Product_id = 2")
Then loop through subset and update
foreach (DataRow row in selected)
{
row["Product_price"] = "<new price>";
}
You can traverse through the DataTable like below and set the value
foreach(DataTable thisTable in dataSet.Tables)
{
foreach(DataRow row in thisTable.Rows)
{
row["Product_name"] = "cde";
}
}
OR
thisTable.Rows[1]["Product_name"] = "cde";
Hope this helps
Try this I am also not 100 % sure
for( int i = 0 ;i< dt.Rows.Count; i++)
{
If(dt.Rows[i].Product_id == 2)
{
dt.Rows[i].Columns["Product_name"].ColumnName = "cde";
}
}
try this,
foreach(DataRow rw in dt.Rows)
{
rw["Obj_Amt"] = h.Decrypt(rw["Obj_Amt"].ToString());
dt.AcceptChanges();
rw.SetModified();
}
use SetModified() method to update data table value.

How to get the list of columns of same datatype from datatable

i am having a datatable in my program, i want to get the list of the columns which has same data type.
i used the following code:
DataTable dt = new DataTable();
dt.Columns.Add("col1", typeof(string));
dt.Columns.Add("col2", typeof(string));
dt.Columns.Add("col3", typeof(int));
dt.Columns.Add("col4", typeof(string));
List<DataColumn> string_type_columns = new List<DataColumn>();
for (int i = 0; i < dt.Columns.Count;i++ )
{
if (dt.Columns[i].DataType.ToString().Equals("System.String"))
{
string_type_columns.Add(dt.Columns[i]);
}
}
string_type_columns will give me the list of the columns which has string datatype.
but in my actual program there can be more than 40 columns in my table so i don't want to loop through each column of datatable.
is there any other (better) way to do this?
If you just want less code I suppose you could use LINQ.
var string_type_columns = dt.Columns.Cast<DataColumn>().Where(c => c.DataType == typeof(String));

Difference Between DataTable.Add.Row(array) and DataTable.ImportRow(row)

I'm trying to understand the difference between rows created using the following methods:
newTable.Rows.Add(array);
newTable.ImportRow(row);
I have a WinForms App which uses both these methods to add rows to a DataTable.
Now when I use that DataTable as the DataSource for a DataGridView I can see 'all' of the rows created using both methods.
However, when I use a loop of the type
foreach (DataRow row in newTable.Rows)
{
//...do work
}
The loop only 'sees' the rows created using the ImportRow method. Its as if the rows created using the Rows.Add(array) don't exist, yet clearly they do because I can see them in the DataGridView when I use the DataTable as its DataSource.
EDIT (subsequent to comment by Rahil Jan Muhammad)
Yes - after a lot of playing around I think the Row Adding Methods are nothing to do with it. The issue is in the following code:
foreach (DataGridViewColumn col in dataAllocations.Columns)
{
if (col.Name == "Allocation")
{
col.ReadOnly = false;
}
else
{
col.ReadOnly = true;
}
}
foreach (DataGridViewRow row in dataAllocations.Rows)
{
MessageBox.Show("DataGrid, " + row.Cells["AllocID"].Value.ToString() +
", " + row.Cells["Active"].Value.ToString());
if (row.Cells["Active"].Value == null || (bool)row.Cells["Active"].Value == false)
{
row.ReadOnly = true;
}
else
{
row.ReadOnly = false;
}
}
The first loop makes all Columns except Column "Allocation" read only. The second loop is intended to make even Column "Allocation" read only, if the value in Column "Active" is false. However what is happening is exactly the opposite. Those rows where Active is true are read only and vice versa. So yes, there is something wrong with my 'if' statement. But what?
I found your problem(logig error):
foreach (DataGridViewRow row in dataAllocations.Rows)
{
MessageBox.Show("DataGrid, " + row.Cells["AllocID"].Value.ToString() +
", " + row.Cells["Active"].Value.ToString());
if (row.Cells["Active"].Value == null || (bool)row.Cells["Active"].Value == false)
{
row.Cells["Allocation"].ReadOnly = true;
}
else
{
row.Cells["Allocation"].ReadOnly = false;
}
}
your code sets the all row's column readonly.you want to set readonly Allocation column(my code).
datatable.Rows.Add()
To add new records into a dataset, a new data row must be created and added to the DataRow collection ( Rows) of a DataTable in the dataset
The ImportRow method of DataTable copies a row into a DataTable with all of the properties and data of the row. It actually calls NewRow method on destination DataTable with current table schema and sets DataRowState to Added.
The difference between Rows.Add and ImportRow is that if you call Rows.Add, the row is marked as added (so if you send your table to a data adapter, and insert will be generated). If you use Import row, the row comes in, but it is not in the "inserted" state, and will not generate an insert.
However, I cannot reproduce the behavior that you are describing with AddRow - they show up in my foreach.
Test code below (this is from LINQpad, if you don't have that, you can change the .Dump() call to Console.Write):
var dt = new DataTable();
dt.Columns.Add("C1", typeof(int));
for(int i = 0; i < 10; i++)
{
var row = dt.NewRow();
row[0] = i;
dt.Rows.Add(row);
}
foreach(DataRow row in dt.Rows)
row.Dump();
to add row to datatable use newTable.Rows.Add(array); and to add rows from other tables to another table we use newTable.ImportRow(row);
example :
DataTable dt = GetTable(true);
dataGridView1.DataSource = dt;
DataRow row = dt.NewRow();
row[0] = 101;
row[1] = "101";
row[2] = "101";
row[3] = DateTime.Now;
dt.ImportRow(row);
DataTable dt2 = GetTable(false);
object[] r = { 105, "Habib", "Zare", DateTime.Now };
dt2.Rows.Add(r);
dt2.ImportRow(dt.Rows[1]);
dataGridView2.DataSource = dt2;
the GetTable method :
static DataTable GetTable(bool isAddRows)
{
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
if (isAddRows)
{
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
}
return table;
}

Categories

Resources