how to check the datatable row column value using ado.net - c#

i want to check the column value of one table. want to check the column value = 1 or not.in the table row column has value of 1 but not entering in the if condition.
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows[0][1].ToString()=="1") // getting false
{
InsertSmsDetails();
}
data
888a1e5 1 voltage level is critical

var list_ids = (from DataRow dr in dt.Rows
where (string)dr["ColumnName"] == "1"
select (string)dr["ColumnName"]).ToList();
foreach (var item in list_ids)
{
InsertSmsDetails();
}

Related

C# simple subtraction from two different database

I have 2 different databases - SQLite and PostgreSQL and i trying to make tiny math on table from this databases.
Both tables contains columns nr_serii and ilosc, SQLite:
And Postgres:
I established a connection to both databases and populate dataset. Maybe i should use different place to store the data?
I need to substraction column ilosc: (sqlite-postgres), but not know how to do that.
For example, for each nr_serii make substraction column ilosc:
nr_serii:222222
ilosc:15-7=8
Finally i want to show output data to datagridview.
When i use messagebox i can see the data in dataset. Here is my part of code:
string cs = #"URI = file:" + Sdatabase;
string csP = conParam;
string sqlP = "select nr_serii, ilosc from stany";
string sql = "select nr_serii, ilosc from przychod";
using var con = new SQLiteConnection(cs);
con.Open();
using var cmd = new SQLiteCommand(sql, con);
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
using var conP = new NpgsqlConnection(csP);
conP.Open();
NpgsqlCommand cmdP = new NpgsqlCommand(sqlP, conP);
NpgsqlDataAdapter DA = new NpgsqlDataAdapter(cmdP);
DataSet dsP = new DataSet();
DA.Fill(dsP);
//----------test-----------
foreach (DataRow row in dsP.Tables[0].Rows)
{
var nr_serii = row["nr_serii"];
var ilosc = row["ilosc"];
MessageBox.Show(nr_serii +","+ ilosc);
}
//--------------------------
For example, you can browse data table from first datasource ds and search for a matching row by value of nr_serii column for each row in the datatable in second datasource dsP, and if found, add a new row with the calculation result to the new third result table.
Then you don't forget to solve the problem of what to do with records that are only in the first ds or only in the second dsP datasource, depending on the value of the nr_serii column.
Program code example:
//prepare result third DataTable
DataTable resultDt = new DataTable();
resultDt.Columns.Add("nr_serii");
resultDt.Columns.Add("ilosc");
//add content to result DataTable
foreach (DataRow row in ds.Tables[0].Rows)
{
var nr_serii = row["nr_serii"];
var ilosc = row["ilosc"];
DataRow drP = null;
foreach (DataRow dataRow in dsP.Tables[0].Rows)
{
if (nr_serii.ToString() == (string)dataRow["nr_serii"])
{
drP = dataRow;
break;
}
}
if (drP != null)
{
var dr = resultDt.NewRow();
dr["nr_serii"] = nr_serii;
dr["ilosc"] = (int)ilosc - (int)drP["ilosc"];
resultDt.Rows.Add(dr);
}
}

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];
}

Compare two data tables and insert into another table based on column name in C#

I have two data tables Table1 and Table2. I want to compare a value SourceField and insert the row of both table into a new data table.
Table #1 - Mapping table
Key SourceField
------------------
null name
A101 V1
A102 V2
A103 V3
Table #2 - Source table
Name V1 V2 V3
-----------------------
10001 1 2 3
Table #3 - Output table
Name Value Key
--------------------
10001 1 A101
10001 2 A102
10001 3 A103
Regards,
Manish
For DataTable , following solution will work for you.
I tested it. I used the same structure that you mentioned in the question.
DataTable table1 = new DataTable();
table1.Columns.Add("Key");
table1.Columns.Add("SourceField");
table1.Rows.Add("A101", "V1");
table1.Rows.Add("A102", "V2");
table1.Rows.Add("A103", "V3");
DataTable table2 = new DataTable();
table2.Columns.Add("Name");
table2.Columns.Add("V1");
table2.Columns.Add("V2");
table2.Columns.Add("V3");
table2.Rows.Add("10001", 1, 2, 3);
DataTable table3 = new DataTable();
table3.Columns.Add("Name");
table3.Columns.Add("Value");
table3.Columns.Add("Key");
// LOOP FOR COMPARING THE DIFFERENT COLUMNS AND VALUES FROM DIFFERENT DATATABLES
foreach (DataRow drtable1 in table1.Rows)
{
foreach (DataRow drtable2 in table2.Rows)
{
if ( drtable2[Convert.ToString(drtable1["SourceField"])] != null)
{
table3.Rows.Add(drtable2["Name"], drtable2[Convert.ToString(drtable1["SourceField"])], drtable1["Key"]);
}
}
}
Result (snap from Visual Studio)
UPDATE
Need to add one more condition in loop for checking blank value for Key column.
// LOOP FOR COMPARING THE DIFFERENT COLUMNS AND VALUES FROM DIFFERENT DATATABLES
foreach (DataRow drtable1 in table1.Rows)
{
foreach (DataRow drtable2 in table2.Rows)
{
if (drtable2[Convert.ToString(drtable1["SourceField"])] != null && Convert.ToString(drtable1["Key"]).Trim() != string.Empty)
{
table3.Rows.Add(drtable2["Name"], drtable2[Convert.ToString(drtable1["SourceField"])], drtable1["Key"]);
}
}
}
You can create a new DataSet:
DataSet dset = new DataSet();
DataTable datatable3 = new DataTable("OutputTable");
datatable3.Columns.Add(new DataColumn("Name",typeof(string)));
datatable3.Columns.Add(new DataColumn("Value", typeof(int)));
datatable3.Columns.Add(new DataColumn("Key", typeof(string)));
//do a foreach or any other operation here
//you can add a new row to the datatable like that:
drow["Name"] = "10001";
drow["Value"] = 3;
drow["Key"] = "A103";
DataRow drow = datatable3.NewRow();
datatable3.Rows.Add(drow);
//after adding ALL rows, you have to add the datatable to the dataset
dset.Tables.Add(datatable3);
Loop through an existing dataset (I suppose you already have ds1 and ds2 as seperate datatables):
foreach (DataRow row1 in datatable1.Rows)
{
foreach (DataRow row2 in datatable2.Rows)
{
//example comparasion
if (row1["SourceField"] == row2["SourceField")
{
datatable3.Rows.Add(....) //see above examples how to add a row
}
}
}

Delete Row From Data Table

I want to Delete the Multiple records from the DataTable
For example :
in my case PaperId is Repeating several Times.I want to Delete it all Duplicate records.
i have written code but loop is giving error
DataSet ds = new DataSet();
sqlDad.Fill(ds);
DataTable dt1 = new DataTable();
ds.Tables.Add(dt1);
dt1 = ds.Tables[0];
DataTable dt2 = new DataTable();
dt2 = dt1;
List<DataRow> rowsToDelete = new List<DataRow>();
foreach(DataRow dr in ds.Tables[0].Rows)
{
int r = ds.Tables[0].Columns.Count;
string x = dr.ItemArray[0].ToString();
int counter = 0;
foreach (DataRow dr1 in ds.Tables[0].Rows)
{
if (x == dr1.ItemArray[0].ToString())
{
counter++;
}
if (counter > 1)
{
rowsToDelete.Add(dr1);
foreach (DataRow row in rowsToDelete)
{
dt2.Rows.Remove(row);
}
dt2.AcceptChanges();
rowsToDelete.Clear();
}
}
Using the DefaultView of the DataTable and setting the sort order on the column that you don't want repeats to appear. You could loop over the rows and delete all the rows after the first one
// Work on the first table of the DataSet
DataTable dt1 = ds.Tables[0];
// No need to work if we have only 0 or 1 rows
if(dt1.Rows.Count <= 1)
return;
// Setting the sort order on the desidered column
dt1.DefaultView.Sort = dt1.Columns[0].ColumnName;
// Set an initial value ( I choose an empty string but you could set to something not possible here
string x = string.Empty;
// Loop over the row in sorted order
foreach(DataRowView dr in dt1.DefaultView)
{
// If we have a new value, keep it else delete the row
if(x != dr[0].ToString())
x = dr[0].ToString();
else
dr.Row.Delete();
}
// Finale step, remove the deleted rows
dt1.AcceptChanges();
Try This
DataRow[] rows;
rows=dataTable.Select("UserName = 'ABC'"); // UserName is Column Name
foreach(DataRow r in rows)
r.Delete();
If you want to remove the entire row from DataTable ,
try this
DataTable dt = new DataTable(); //User DataTable
DataRow[] rows;
rows = dt.Select("UserName = 'KarthiK'");
foreach (DataRow row in rows)
dt.Rows.Remove(row);

Getting value from a DataSet into a variable

I have the following method which returns dataset. I am using .NET 2.0
DataSet ds = GetAllRecords();
I want to get values from each column for a particular row and bind it to a variable.
How can this be achieved?
currently the method returns all the row from the table and I have to find that particular row based on ID.
However, if that is not possible I can come with
DataSet ds = GetSpecificRecord(id);
But I still need to get values from each column and bind it to variable.
Please advice.
// Create a table
DataTable table = new DataTable("users");
table.Columns.Add(new DataColumn("Id", typeof(int)));
table.Columns.Add(new DataColumn("Name", typeof(string)));
table.Rows.Add(1, "abc");
table.Rows.Add(2, "ddd");
table.Rows.Add(3, "fff");
table.Rows.Add(4, "hhh d");
table.Rows.Add(5, "hkf ds");
// Search for given id e.g here 1
DataRow[] result = table.Select("Id = 1"); // this will return one row for above data
foreach (DataRow row in result)
{
Console.WriteLine("{0}, {1}", row[0], row[1]);
}
This will get you the value from Row 0 obviously you would need to modify for multiple rows returned
long id = ds.Tables[0].Rows[0].Field<long>("ID");
You can do this with LINQ.
DataRow resultRow = ds.Tables["SomeTable"].AsEnumerable().Where(row => row.Field<int>("SomeID") == 1).FirstOrDefault();
For .NET 2.0 and below
If your DataTable has a primary key defined, you can find the row like this:
DataTable table = ds.Tables["SomeTable"];
DataRow row = table.Rows.Find(1);
If there is no primary key, you can assign one like this:
DataTable table = ds.Tables["SomeTable"];
table.PrimaryKey = new DataColumn[] { table.Columns["SomeID"] };
DataRow row = table.Rows.Find(1);
Another option is to use the RowFilter property of the DefaultView, like this:
DataTable table = ds.Tables["SomeTable"];
table.DefaultView.RowFilter = "SomeID == 1"; //not sure if it's == or = here
DataRow row = table.DefaultView[0].Row;
Lastly, you can also use the DataTable.Select() method to find rows.
Have you looked at using a typed dataset? If you're looking for a row based on the primary key of a table it will autogenerate a method for you to get a row by ID and it will be strongly typed so you can get column values by name.
They were quite handy in .Net 2.0 - but LINQ made them fairly obsolete.
Edit: A slightly better reference URL
http://www.c-sharpcorner.com/UploadFile/rupadhyaya/TypedDataSets12032005021013AM/TypedDataSets.aspx
We can get value from dataset by using this easy method:
System.Data.DataSet ds = db.MySelect(
"Fields",
"Table",
"Condition"
);
if (ds != null)
{
if (ds.Tables[0].Rows.Count > 0)
{
object value=Tables[0].Rows[indx]["field name"];
}
}
To fetch values from student table and display it in console window.
class Class1
{
static void Main(string[] args)
{
SqlConnection con=new SqlConnection(<connectionstring>);
SqlCommand cmd = new SqlCommand("select * from Student", con);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet ds=new DataSet();
ad.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
try
{
DataRow r = ds.Tables[0].Rows[i];
Console.WriteLine(r.Field<Int32>(0));
Console.WriteLine(r.Field<String>(1));
Console.WriteLine(r.Field<String>(2));
Console.WriteLine(r.Field<Decimal>(3));
Console.WriteLine(r.Field<Int16>(4));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Console.ReadKey();
}
}
sql Student table Info
Id int
Name varchar(50)
EmailId nvarchar(50)
MobileNo numeric(10,0)
Standard smallint

Categories

Resources