How to edit/update in dynamic table - c#

I have dynamic DataTable says to be DataTable dt=New DataTable(); and column name says to be ID, F_name, L_name.
I had fill a value to this column seems to be
ID | F_name | L_name
1 | mit | jain
2 | raj | patel
3 | anki | patel
4 | alpa | dumadiya
If I want to edit/update column 2 says to be ID=2, F_name that is raj to rajan
what shall I have to do?

You can try like this :
static void Main(string[] args)
{
DataTable dt = GetTable();
DataRow[] dr = dt.Select("ID=2 and F_Name='raj'");
if (dr !=null)
{
foreach (var item in dr)
{
item["F_name"] = "rajan";
}
}
}
static DataTable GetTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("F_name");
dt.Columns.Add("L_name");
dt.Rows.Add("1", "mit", "jain");
dt.Rows.Add("2", "raj", "patel");
dt.Rows.Add("3", "anki", "patel");
dt.Rows.Add("4", "alpa", "dumadiya");
return dt;
}

Related

How to find the count of distinct records in a MS Access database using C#?

I have an MS Access database as below
Filing_Year | Name
------------------------
02/01/2008 | AAA
02/01/2008 | AAA
02/03/2008 | AAA
03/01/2008 | BBB
I need a query in C# which will get me an output as below and display it in a gridview
Filing_Year | file_count
----------------------------
02/01/2008 | 2
02/03/2008 | 1
03/01/2008 | 1
This is the code I tried:
dataGridView1.Columns.Add("Column", "FileCount"); // file count is not an element in database
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=|DataDirectory|\RMS_Database.mdb");
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter("select Filing_Year,count(*) from Checklist_Data group by Filing_Year ", con);
DataTable dt = new DataTable();
sda.Fill(dt);
BindingSource bSource = new BindingSource();
bSource.DataSource = dt;
dataGridView1.DataSource = bSource;
sda.Update(dt);
With this I am seeing only unique filing_year, but not the count.
Thanks in advance. Help is really appreciated.
You need to modify your SQL Query like:
SELECT Filing_Year, COUNT(Name) as file_count
FROM Checklist_Data
GROUP BY Filing_Year, Name

Datatable group and pivot

I have a DT with following structure
unit | value | date
-------------------------
A | 2 | 01-01-2000
B | 3 | 01-01-2000
A | 4 | 02-01-2000
I would like to transform it into following
| A | B
---------------------------
01-01-2000 | 2 | 3
02-01-2000 | 4 |
What would be the fastest way to achieve this?
EDIT:
I have implemented a function for pivot, which gives me the following:
| A | B | A
--------------------------------------
value | 2 | 3 | 4
date |01-01-2000|01-01-2000|02-01-2000
But in this case I am missing grouping by columns.
By 'fastest' I mean possibly shortest code to achieve this (LINQ?). Or perhaps pivot can be achieved simultaneously in the same query?
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("unit", typeof(string));
dt.Columns.Add("value", typeof(int));
dt.Columns.Add("date", typeof(DateTime));
dt.Rows.Add(new object[] { "A",2, DateTime.Parse("01-01-2000")});
dt.Rows.Add(new object[] { "B",3, DateTime.Parse("01-01-2000")});
dt.Rows.Add(new object[] { "A",4, DateTime.Parse("02-01-2000")});
string[] uniqueUnits = dt.AsEnumerable().Select(x => x.Field<string>("unit")).Distinct().ToArray();
DataTable dt1 = new DataTable();
dt1.Columns.Add("date", typeof(DateTime));
foreach (string unit in uniqueUnits)
{
dt1.Columns.Add(unit, typeof(int));
}
var groups = dt.AsEnumerable().GroupBy(x => x.Field<DateTime>("date"));
foreach (var group in groups)
{
DataRow newRow = dt1.Rows.Add();
foreach (DataRow row in group)
{
newRow["date"] = group.Key;
newRow[row.Field<string>("unit")] = row.Field<int>("value");
}
}
}
}
}
It's more lines of code but can be done with only one loop as well:
DataTable dt1 = new DataTable();
dt1.Columns.Add(new DataColumn("unit",typeof(string)));
dt1.Columns.Add(new DataColumn("value",typeof(int)));
dt1.Columns.Add(new DataColumn("date",typeof(DateTime)));
dt1.Rows.Add(new object[] { "A", 2, DateTime.Parse("01-01-2000") });
dt1.Rows.Add(new object[] { "B", 3, DateTime.Parse("01-01-2000") });
dt1.Rows.Add(new object[] { "A", 4, DateTime.Parse("02-01-2000") });
DataTable dt2 = new DataTable();
dt2.Columns.Add(new DataColumn("date", typeof(DateTime)));
dt2.PrimaryKey = new DataColumn[] { dt2.Columns["date"], };
List<string> cols = new List<string>();
List<DateTime> ds = new List<DateTime>();
foreach (DataRow dr1 in dt1.Rows)
{
string unit = dr1["unit"].ToString();
if (!cols.Contains(unit))
{
dt2.Columns.Add(new DataColumn(unit, typeof(int)));
cols.Add(unit);
}
DateTime pkDate = (DateTime)dr1["date"];
if (!ds.Contains(pkDate))
{
ds.Add(pkDate);
DataRow dr = dt2.NewRow();
dr["date"] = dr1["date"];
dr[unit] = dr1["value"];
dt2.Rows.Add(dr);
}
else
{
dt2.Rows.Find(pkDate)[unit] = dr1["value"];
}
}

How to filter the DataGridView using ComboBox

I need help on filtering my DataGridView using ComboBox
Here's my display code
cm = new SqlCommand();
cn = new SqlConnection(lgn.connections);
cn.Open();
cm.Connection = cn;
query = "Select * from Trails";
cm.CommandText = query;
SqlDataAdapter dar = new SqlDataAdapter(cm);
DataTable dt = new DataTable();
dar.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Columns[0].Width = 0;
dataGridView1.Columns[1].Width = 130;
dataGridView1.Columns[2].Width = 100;
dataGridView1.Columns[3].Width = 360;
dataGridView1.Columns[4].Width = 130;
this.dataGridView1.Columns[0].Visible = false;
RAW DATA:
ID | TRANSACTYPE | DESCRIPTION | AUTHORIZED BY
-----------------------------------------------
1 | LOGIN | blah blah | BOB
2 | LOGOUT | blah blah | BOB
3 | LOGIN | blah blah | TIM
4 | LOGOUT | blah blah | KURT
I have ComboBox named cboFilter and if I changed the index to LOGIN the data that will show on the dataGridView1 is only LOGINs.
Try this:
DataTable dt = new DataTable();
private void cboFilter_SelectedIndexChanged(object sender, EventArgs e)
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("TRANSACTYPE LIKE '%{0}%'", cboFilter.SelectedItem.ToString());
dataGridView1.DataSource = dv;
}
If you need DataGridView data source always to be a DataTable as in my case.
DataTable dt = (DataTable)dgv.DataSource;
dgv.DataSource = dt.Select("IsActive = 1").CopyToDataTable();

How to compare two DataTable with different number of columns?

If I want to compare two datatables and get the difference in new datatable but I want to keep an uncompared column.
example:
first Datatable
Name | Number
---- |-------
Jude | 12
Mark | 14
Bin | 15
second Datatable
Name
------
Jude
Robin
Kamil
the Datatable must have:
Name | Number
-------|----------
Mark | 14
Bin | 15
I have this method which can compare the two datatables and get the difference, but how can I get the number.
public static DataTable CompareTables(DataTable first, DataTable second)
{
first.TableName = "FirstTable";
second.TableName = "SecondTable";
//Create Empty Table
DataTable table = new DataTable("Difference");
try
{
//Must use a Dataset to make use of a DataRelation object
using (DataSet ds = new DataSet())
{
//Add tables
ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });
//Get Columns for DataRelation
DataColumn[] firstcolumns = new DataColumn[1];
firstcolumns[0] = ds.Tables[0].Columns[0];
DataColumn[] secondcolumns = new DataColumn[1];
secondcolumns[0] = ds.Tables[1].Columns[0];
//Create DataRelation
DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);
ds.Relations.Add(r);
//Create columns for return table
for (int i = 0; i < first.Columns.Count; i++)
{
table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);
}
//If First Row not in Second, Add to return table.
table.BeginLoadData();
foreach (DataRow parentrow in ds.Tables[0].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r);
if (childrows == null || childrows.Length == 0)
table.LoadDataRow(parentrow.ItemArray, true);
}
table.EndLoadData();
}
}
catch (Exception ex)
{
}
return table;
}
Let the database handle these things:
SELECT name, number from table1 where name not in (select name from table2);
public static DataTable CompareTables(DataTable first, DataTable second)
{
second.PrimaryKey = new DataColumn[] {second.Columns["Name"]};
DataTable difference = second.Clone();
foreach (DataRow row in first.Rows) {
if (second.Rows.Find(row["Name"]) == null)
{
difference.ImportRow(row);
}
}
return difference;
}
#user3527065 your code will throw an argument exception as the no. of columns has to be same .
DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);
I your case firstcolumns has 2 columns whereas second columns has 1 column so it would throw an argument exception.

Separating the column values of DataTable using LINQ

Consider i have a DataTable dt retrieved from oracle database in the following format
Eno | EHobbies | Esal
-------------------------------------------------
1 | Cricket,Tennis,Carroms | 500
2 | Cricket,Volley | 1000
//Datatable for above table
DataTable dt = new DataTable("EmployeeTable");
dt.Columns.Add("Eno", typeof(int));
dt.Columns.Add("EHobbies", typeof(string));
dt.Columns.Add("Esal", typeof(int));
dt.Rows.Add(1, "Cricket,Tennis,Carroms",500 );
dt.Rows.Add(2, "Cricket,Volley",1000);
I need to change this into the following format using linq on the DataTable dt .Need to separate the product column with the help of comma by keeping the other columns same.
Eno | EHobbies | Esal
-------------------------------------
1 | Cricket | 500
1 | Tennis | 500
1 | Carroms | 500
2 | Cricket | 1000
2 | Volleyball | 1000
The following would work:
var newRows = dt.AsEnumerable()
.SelectMany(r => r.Field<string>("EHobbies")
.Split(',')
.Select(x => new { No = r.Field<int>("Eno"),
Hobbies = x,
Sal = r.Field<int>("Esal") }
)
);
DataTable result = new DataTable("EmployeeTable");
result.Columns.Add("Eno", typeof(int));
result.Columns.Add("EHobbies", typeof(string));
result.Columns.Add("Esal", typeof(int));
foreach(var newRow in newRows)
result.Rows.Add(newRow.No, newRow.Hobbies, newRow.Sal);
This also helps:
DataTable newDt = new DataTable();
newDt.Columns.Add("Eno", typeof(int));
newDt.Columns.Add("EHobbies", typeof(string));
newDt.Columns.Add("Esal", typeof(int));
dt.AsEnumerable().ToList()
.ForEach(row => row["EHobbies"].ToString().Split(',').ToList()
.ForEach(item => newDt.Rows.Add(row["Eno"], item, row["Esal"])));

Categories

Resources