Collect data and display the data in a column label - c#

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

Related

c# selecting all record with specific data on datatable

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);

Create a row according to empty DataTable Definition

After executing DataAdapter and get an empty DataTable. I need to create a new row according to empty datatable definition. Please help in this point.
SqlConnection con = CreateCon();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand();
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Connection = con; da.SelectCommand.CommandText = "spGET_RackZone";
if (con.State == ConnectionState.Closed)
{
con.Open();
}
DataSet ds = new DataSet();
da.Fill(ds);
if (con.State == ConnectionState.Open){
con.Close();
}
DataTable dt = ds.Tables[0];
Now I want to create a row when datatable is empty.
DataTable table = new DataTable();
if(table.Rows.Count==0)
{
DataRow row = table.NewRow();
table.Rows.Add(row);
}
//if you already know the column of the table
table.Columns.Add("sl.No", typeof(int));
table.Columns.Add("Name", typeof(string));
// Here we add a DataRow.
table.Rows.Add(57, "Amin");

DataTable and ODBC adapter

I need to fill DataTable from ODBC Data adapter. I can see that dataTable is still empty but DataSet (ds) is successfully filled with data though.
OdbcConnection cnn;
cnn = new OdbcConnection(azureConnection);
using (OdbcCommand command = cnn.CreateCommand())
{
command.CommandText = "{call sp_Get_Excel_Data(?,?,?,?,?,?,?,?)}";
command.Parameters.AddWithValue("#StartDate", startDate);
command.Parameters.AddWithValue("#EndDate", endDate);
command.Parameters.AddWithValue("#startTime", startTime);
command.Parameters.AddWithValue("#endTime", endTime);
command.Parameters.AddWithValue("#rptSymbol", tickerSymbol);
command.Parameters.AddWithValue("#reg", RegId);
command.Parameters.AddWithValue("#events", events);
command.Parameters.AddWithValue("#userId", userId);
DataTable dataTable = new DataTable();
cnn.Open();
//DataTable
OdbcDataAdapter adapter = new OdbcDataAdapter(command);
adapter.Fill(dataTable);
//DataSet
DataSet ds = new DataSet();
adapter.Fill(ds);
string[] colNames = new string[dataTable.Columns.Count];
int col = 0;
foreach (DataColumn dc in dataTable.Columns)
colNames[col++] = dc.ColumnName;
}
Can you suggest why I can't see data in DataTable and how to make it work?
Ok, I solved the issue by casting to DataTable:
DataTable dataTable = ds.Tables[0];
You can remove
adapter.Fill(dataTable);
And put after filling ds
dataTable = ds.Tables[0]
Or
dataTable = ds.Tables["name_of_your_table"]

Get Contents of Last Record in DataGridView using C#

I am creating an application in which I am getting some data in my dataGridView1 in my form. I want to access my last row of data in some variables like I want to store columns in variables and use them. I know how to do this in GridView Cell click event but I want to use this in a loop like after every 10 seconds new data comes from database to dataGridView1 and I want last row to be accessed in variables.
Below is the code of how I am loading data in dataGridView
using (var con = new SqlConnection(ConStr))
{
string query = "SELECT * FROM CHECKINOUT";
using (var cmd = new SqlCommand(query, con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
}
Can you not just access the last row of Table 0 in your dataset and then assign all columns to variables
int lastRow = 0;
lastRow = ds.Tables(0).rows.count - 1;
string col1 = ds.Tables(0).Rows(lastRow)(0).tostring.trim;
Using your code you could do:
using (var con = new SqlConnection(ConStr))
{
string query = "SELECT * FROM CHECKINOUT";
using (var cmd = new SqlCommand(query, con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
}
int lastRow = 0;
lastRow = ds.Tables(0).rows.count - 1;
string col1 = ds.Tables(0).Rows(lastRow)(0).tostring.trim;
string col2 = ds.Tables(0).Rows(lastRow)(1).tostring.trim;
string col3 = ds.Tables(0).Rows(lastRow)(2).tostring.trim;

OleDbDataAdapter can't not update the access database

I use OleDbCommand to run the sqlcommand that can update the Access database.
But when I try to use OleDbDataAdapter and DataTable to update the database,
it doesn't work.
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("select * from confirm", conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
DataTable table = new DataTable();
adapter.Fill(table);
DataRow row = table.NewRow();
row["k"] = "november";
row["v"] = "eleven";
// table.AcceptChanges();
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.Update(table);
// table.AcceptChanges();
return table;
}
When I run the code, the database doesn't change.
This DataRow row = table.NewRow(); creates a row with table shema but doesn't add the row to the DataTable. You need to add the row to the table :
table.Rows.Add(row);
complete code
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("select * from confirm", conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
DataTable table = new DataTable();
adapter.Fill(table);
DataRow row = table.NewRow();
row("k") = "november";
row("v") = "eleven";
//**You missed this**
table.Rows.Add(row);
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.Update(table);
// table.AcceptChanges();
return table;
}

Categories