c# selecting all record with specific data on datatable - c#

I'm planning to select all rows in my datatable that has 'Dog' in column 2 without using keyword "WHERE" on my query. My guess is to try using DataRow and foreach but I'm not sure where to start. I filled my datatable with records coming from my database and this is what I've done so far.
using(MySqlConnection con = new MySqlConnection(constring))
{
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT * FROM table1",con);
DataTable dt = new DataTable();
adp.Fill(dt);
adp.Dispose();
}
This is what my datatable looks like:
Column1 Column2 Column3
1 Dog Labrador
2 Dog Chowchow
3 Cat Persian
4 Cat Stubby
5 Dog German Shepherd

You can filter records when populating table using data adapter by modifying select query:
SELECT * FROM table1 WHERE Column2='Dog'
and second approach if you need to filter later then use this approach - Creating a DataTable From a Query (LINQ to DataSet):
List<DataRow> result = dt.AsEnumerable().Where(row=> row.Field<string>("Column2") = "Dog").ToList();
You can filter records by using DataView and use the RowFilter Property as below:
// Create a DataView
DataView dv = new DataView(dt);
// Filter by an expression.
dv.RowFilter = "Column2 = 'Dog'";
DataTable newTable = view.ToTable();
References:
Creating a DataTable from a DataView

You are looking for a SQL WHERE clause. Always use SqlParameter or similar to insert variables into a query (prevents potential SQL injection attacks if parameter value is user provided).
string genusInput = "Dog"; // might be provided by user input later on
DataTable result = new DataTable();
using (MySqlConnection con = new MySqlConnection(constring)) {
const string query = "SELECT * FROM table1 WHERE Column2 = #genus";
var adp = new MySqlDataAdapter(query, con);
adp.SelectCommand.Parameters.AddWithValue("#genus", genusInput);
adp.Fill(result);
adp.Dispose();
}

Use where to distinguish:
using(MySqlConnection con = new MySqlConnection(constring))
{
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT * FROM table1,con);
DataTable dt = new DataTable();
adp.Fill(dt);
IEnumerable<DataRow> query = adp.Where(x => x.Column2 == 'dog').ToList();
DataTable filteredRows = query.CopyToDataTable<DataRow>();
adp.Dispose();
}

using(MySqlConnection con = new MySqlConnection(constring))
{
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT * FROM table1",con);
DataTable dt = new DataTable();
adp.Fill(dt);
adp.Dispose();
DataRow[] dr=dt.select(“Column2=‘Dog’”);
}
https://msdn.microsoft.com/en-us/library/det4aw50(v=vs.110).aspx

Create where statement in your query as below sample
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT * FROM table1 WHERE Column2='Dog'",con);

Related

Output data from DataTables within DataSet

I currently accessing a database using multiple queries and storing the results from the queries into DatatTables. I decided since I'm using multiple DataTables to store them inside a DataSet.
I can see that data is inside the DataTables when I print them out. However when I try to access them from the DataSet to print out the data, I get nothing back; it is empty.
string querytest1 = "SELECT * FROM test1";
string querytest2 = "SELECT * FROM test2";
string querytest3 = "SELECT * FROM test3";
using(OleDbConnection connection = new OleDbConnection(connectionString)){
OleDbCommand commandtest1 = new OleDbCommand(querytest1 , connection);
OleDbCommand commandtest2 = new OleDbCommand(querytest2 , connection);
OleDbCommand commandtest3 = new OleDbCommand(querytest3 , connection);
connection.Open();
DataSet dataSet = new DataSet();
OleDbDataAdapter dataAdaptertest1 = new OleDbDataAdapter(commandResults);
OleDbDataAdapter dataAdaptertest2 = new OleDbDataAdapter(commandResults);
OleDbDataAdapter dataAdaptertest3 = new OleDbDataAdapter(commandProjects);
DataTable dataTabletest1 = new DataTable();
DataTable dataTabletest2 = new DataTable();
DataTable dataTabletest3 = new DataTable();
dataAdaptertest1.Fill(dataTabletest1 );
dataAdaptertest2.Fill(dataTabletest2 );
dataAdaptertest3.Fill(dataTabletest3 );
dataTabletest1 = dataSet.Tables.Add("test1 ");
dataTabletest2 = dataSet.Tables.Add("test2 ");
dataTabletest3 = dataSet.Tables.Add("test3 ");
Console.WriteLine("DataSet has {0} DataTables \n", dataSet.Tables.Count);
foreach (DataTable objDt in dataSet.Tables)
Console.WriteLine("{0}", objDt.TableName);
return dataSet;
Expected behaviour: is to be able to access a DataTable from the DataSet and print out the data.
Example: Print out the contents in Test1
The code is redundant. I just don't know a better way to do this.
You don't need three adapters to fill a DataSet with the results from three commands.
You can simply write:
string query1 = "SELECT * FROM test1";
string query2 = "SELECT * FROM test2";
string query3 = "SELECT * FROM test3";
DataSet dataSet = new DataSet();
using(OleDbConnection connection = new OleDbConnection(connectionString)){
connection.Open();
OleDbCommand cmd = new OleDbCommand(q1, connection);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds, "Test1");
cmd.CommandText = q2;
da = new OleDbDataAdapter(cmd);
da.Fill(ds, "Test2");
cmd.CommandText = q3;
da = new OleDbDataAdapter(cmd);
da.Fill(ds, "Test3");
}
Console.WriteLine("DataSet has {0} DataTables \n", ds.Tables.Count);
foreach (DataTable objDt in ds.Tables)
Console.WriteLine("{0}", objDt.TableName);
The trick is filling the same DataSet three times instead of three different DataTables and giving at each fill a different name for each table created.
But, don't you see that dataSet.Tables.Add() call actually creates new DataTable instance, and trying to set its TableName property to "test1 " (btw. take care, space is not allowed in TableName).
That newly created instance(s) are set to properties dataTabletest1...3 - so, you lose access to the original ones, initially populated with data from the database.
You should do something like this:
DataTable dataTabletest1 = dataSet.Tables.Add("Test1");
DataTable dataTabletest2 = dataSet.Tables.Add("Test2");
DataTable dataTabletest3 = dataSet.Tables.Add("Test3");
dataAdaptertest1.Fill(dataTabletest1);
dataAdaptertest2.Fill(dataTabletest2);
dataAdaptertest3.Fill(dataTabletest3);
Please, check: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/adding-a-datatable-to-a-dataset

c# combine two results from two different database providers

I need to check if something in one table (table 1) was added and if so I need to take some values from this table and insert it in the second table (table 2).
The problem is that the Table 1 is .DBF Provider=VFPOLEDB.1 connected by OleDbConnection and the second Table 2 is MSSQL table connected by SqlConnection.
I want to make something like this:
SELECT column1 FROM Table1 WHERE column1 NOT IN (SELECT column2 FROM Table2)
Is it possible to do this? I can load both tables to the datagridview by doing:
public static DataTable GetDataTableDBF(string strFileName)
{
OleDbConnection conFOX = new OleDbConnection("Provider=VFPOLEDB.1;Data Source=" + Path.GetFullPath(strFileName).Replace(Path.GetFileName(strFileName), "") + ";Exclusive=No");
conFOX.Open();
string strQuery = "SELECT * FROM [" + Path.GetFileName(strFileName) + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(strQuery, conFOX);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds.Tables[0];
}
for OleDbConnection and doing:
public static DataTable GetDataTableSQL(string TableName)
{
SqlConnection conSQL = new SqlConnection(connection);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
conSQL.Open();
string strQuery = "SELECT * FROM " + TableName;
da.SelectCommand = new SqlCommand(strQuery, conSQL);
da.Fill(ds);
return ds.Tables[0];
}
for SqlConnection. Mayby I can do 2 datasets or something like temporary tables from this query? so it will be something like this? :
SELECT dataset1.column1 FROM dataset1 WHERE dataset1.column1 NOT IN (SELECT dataset2.column2 FROM dataset2)
Since both datatables are from different sources you need to fetch both datatables into memory and then use linq to dataset. something like this
var datatable1 = GetDataTableDBF("filename");
var datatable2 = GetDataTableSQL("tablename");
var query = from c in dataset1.AsEnumerable()
where !(from o in dataset2.AsEnumerable()
select o.Field<int>("column2")).Contains(c.Field<int>("column1"))
select c;
var filteredDataTable1 = query.CopyToDataTable();
var resultDataTable = filteredDataTable1.DefaultView.ToTable(false, "column1"); //create new table with only 1 column
dataGridView1.DataSource = resultDataTable;

How to display all Database data in Grid View using Data Table?

I have 5 data in my datatbase, these data I want to display in a gridView using Data Table. But my code displays only the last binded data in GridView? My code is. Please point out the mistake?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
SqlCommand cmd = new SqlCommand("select Date from MusterRoll where EmpCode='"+code+"' and Month='1' and Year='2015'", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
var rows = ds.Tables[0].Rows;
foreach (DataRow row in rows)
{
string date1 = Convert.ToString(row["Date"]);
DateTime date2 = Convert.ToDateTime(date1);
SqlCommand cmd1 = new SqlCommand(" select TOP 1 m.EmpCode,m.NOH,m.OT,m.Late,m.Early,convert(varchar(10),m.Date,103)AS DATE,convert(varchar(10),s1.Shiftname,103)AS Shift From ShiftChange s,ShiftType s1,MusterRoll m WHERE s1.ShiftID=s.NShiftID and '" + date2 + "'>=Fromdate and Todate>='" + date2 + "' and m.Month = '1' and m.date='"+date2+"' and m.EmpCode='Neena' order by Todate desc", conn);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
//var rows1 = ds.Tables[0].Rows;
for (int rowIndex = 0; rowIndex < dt.Rows.Count; rowIndex++)
{
DataRow rpw = dt.Rows[rowIndex];
string EmpCode = rpw.Field<string>("EmpCode");
string NOH = rpw.Field<string>("NOH");
string OT = rpw.Field<string>("OT");
string Latae = rpw.Field<string>("Late");
string Early = rpw.Field<string>("Early");
string date3 =rpw.Field<string>("Date");
string Shift = rpw.Field<string>("Shift");
gvSingleemp.Visible = true;
gvSingleemp.DataSource = dt;
gvSingleemp.DataBind();
}
}
In my shiftChange table there is no Field for date instead of that I have fromDate and ToDate.I want display employee shifft according to MusterRoll table date. So that first I selected MusteRoll date nd checkrd this date exist in between ShiftChange FromDate and ToDate if exist show the Shift
You are databinding the GridView in a loop. You don't need the loop, just bind it to the DataTable:
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
gvSingleemp.DataSource = dt;
gvSingleemp.DataBind();
I still think that you don't need those loops at all. I guess that you want to select all records from EmpDetails where the EmpCode = code and MusterRoll.Month='1' and MusterRoll.Year='2015'. Then you only need one sql query to fill one DataTable which can be used as DataSource for gvSingleemp. Is that correct?
If so, this should work (note that i use the using statement and sql-parameters):
DataTable tblData = new DataTable();
string sql = #"SELECT ed.EmpCode,ed.Name,ed.Age,ed.Date
FROM MusterRoll mr
INNER JOIN EmpDetails ed
ON mr.Date = ed.Date
WHERE mr.EmpCode=#EmpCode AND mr.Month=1 AND mr.Year=2015";
using(var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
using(var sda = new SqlDataAdapter(sql, conn))
{
var codeParam = new SqlParameter("#EmpCode", SqlDbType.VarChar).Value = code; // change type accordingly
sda.SelectCommand.Parameters.Add(codeParam);
sda.Fill(tblData); // no need for conn.Open/Close with SqlDataAdapter.Fill
}
gvSingleemp.Visible = true;
gvSingleemp.DataSource = tblData;
If you don't want to join the tables you can also use EXISTS:
string sql = #"SELECT ed.EmpCode, ed.Name, ed.Age, ed.Date
FROM EmpDetails ed
WHERE EXISTS
(
SELECT 1 FROM MusterRoll mr
WHERE mr.EmpCode = #EmpCode
AND mr.Month = 1 AND mr.Year=2015
AND mr.Date = ed.Date
)";
You dont have to use loop to bind the DT to GridView :
SqlCommand cmd1 = new SqlCommand(" select EmpCode,Name,Date,Age from EmpDetails where CompanyID='1'", conn);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
gvSingleemp.DataSource =dt;
gvSingleemp.DataBind();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
DataTable data = new DataTable();
Da.Fill(data);
gvSingleemp.DataSource = data;
gvSingleemp.DataBind();

Collect data and display the data in a column label

How can I sum a column to the table without dataGridView and i'm using sql command method And my database is in SQL server 2008.
I like this script
using System.Data;
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter("Select Price from PriceList", connection);
sda.Fill(dt);
int sum=Convert.ToInt32(dt.Compute("sum(Price)",""));
Label1.Text=sum.ToString();
You can loop through the DataTable and sum the field you like.
You can try something like this one,
string query = "SELECT Price FROM Bill";
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, DBconn);
DataTable dtSource = new DataTable();
dAdapter.Fill(dtSource);
int colSum =0;
foreach (DataRow dr in dtSource .Rows)
{
colSum += Convert.ToInt32(dr["Price"]);
}
TotalValueLabel.Text = colSum.ToString();
For multiplication, you can try something like this,
string query = "SELECT Qty,Price FROM Bill";
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, DBconn);
DataTable dtSource = new DataTable();
dAdapter.Fill(dtSource);
dtSource.Columns.Add("3rdColumn");
foreach (DataRow dr in dtSource .Rows)
{
dr["3rdColumn"]= Convert.ToInt32(dr["Qty"]) * Convert.ToInt32(dr["Price"]);
}

how to sort in order using Datatable for Gridview

i have a table in GridView
vName iId
Jeeva 323243
raj 4343
Abishek 3434
ramesh 4545
Manoj 7374234
viky 885
I want to show this table in ascending/decending order by using DataTable.
static string strcon = "Data Source=;Initial Catalog=;Integrated Security=True";
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter("select * from one", con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
Try this:
datatable.DefaultView.Sort = "yourcolumnname ASC";
datatable = datatable.DefaultView.ToTable();
Using linq:
var OrderedItems = dt.OrderBy(x=>x.vName).ToList();
GridView1.DataSource = OrderedItems;
Or order by any other column (OrderByDescending can be used too)

Categories