Hi I am using DataTable and DevaultView.RowFilter to display a DataGridView.
I have a column with date (dd/mm/yyyy).
String filter = String.Format(#"account_name LIKE '{0}*' AND type_name='{2}' AND Convert( transaction_date, System.DateTime ) < '{1}' OR is_edited ='true' ", this.accountName, this.dateTimePickerTransactionFrom.Value.ToString(), this.radioButtonDebit.Checked ? "Debit" : "Credit");
transactionsAll.DefaultView.RowFilter = filter;
DefaultView_ListChanged();
It ends up in an error:
String was not recognized as a valid DateTime.
Thanks Guys,
I solved the problem.
I changed the DB Query from
SELECT transactions.transaction_id, transactions.transaction_amound, CONVERT(char(10), transactions.transaction_date, 103) AS transaction_date,
transaction_type.type_name, transaction_type.description, accounts.account_name, accounts.user_id
FROM transactions INNER JOIN
transaction_type ON transactions.type_id = transaction_type.type_id INNER JOIN
accounts ON transactions.account_id = accounts.account_id
WHERE (accounts.user_id = #UserId)
To
SELECT transactions.transaction_id, transactions.transaction_amound, transactions.transaction_date, transaction_type.type_name,
transaction_type.description, accounts.account_name, accounts.user_id
FROM transactions INNER JOIN
transaction_type ON transactions.type_id = transaction_type.type_id INNER JOIN
accounts ON transactions.account_id = accounts.account_id
WHERE (accounts.user_id = #UserId)
and
private void ConstraintChanged()
{
String filter = String.Format(#"account_name LIKE '{0}*' AND type_name='{2}' " +
#"AND Convert( transaction_date, System.DateTime ) > '{1}' OR is_edited ='true' ",
this.accountName,
this.dateTimePickerTransactionFrom.Value,
this.radioButtonDebit.Checked ? "Debit" : "Credit");
transactionsAll.DefaultView.RowFilter = filter;
DefaultView_ListChanged();
}
Related
I tried this code in C# winforms but its not working like MSSQL ,
when i select data and using string_agg in SQL its working , but in C# forms its not working and
show the data on multiple lines
This is the code :
private void BtnSearch_Click(object sender, EventArgs e)
{
if (chkCash.Checked == false && chkCovid.Checked == false)
{
btnCash.Enabled = false;
BtnPrint.Enabled = true;
string sql = #" SELECT distinct a.patient_no as 'File No' ,
a.Patient_name as 'Patient Name' ,
b.order_id as 'Order Id' ,
c.custid as 'Clinic No',
c.custname as 'Clinic Name' ,
e.TestId as 'Test Id',
string_agg(e.testname, ',') as 'Test',
b.order_date as 'Order Date',
b.lab_no as 'Lab No'
FROM patients a , lab_orders b ,customers c , order_details d , labtests e
where a.patient_no = b.patient_no
and b.custid = c.custid
and b.order_id = d.order_id
and d.testid = e.testid
and c.CustId > 1
and d.TESTID <> 6438
and cast(b.order_date as time) between '01:00:00' and '23:50:50' ";
string condition = "";
string orderby = "";
orderby += " ORDER BY c.custid";
string groupby = "";
groupby += " group by a.patient_no,a.Patient_name , b.order_id , c.custid , c.custname , b.order_date , b.lab_no, e.TestId ";
DateTime fromDate;
DateTime toDate;
if (!DateTime.TryParse(dtFromDate.Value.ToString(), out fromDate))
{
System.Windows.Forms.MessageBox.Show("Invalid From Date");
}
else if (!DateTime.TryParse(dtToDate.Value.ToString(), out toDate))
{
System.Windows.Forms.MessageBox.Show("Invalid to Date");
}
else
{
condition += " and cast(b.order_date as date) between '" + fromDate + "' and '" + toDate + "'";
}
DataTable dt = data.fireDatatable(string.Format(sql + condition + groupby + orderby));
OrdersDataGridView.DataSource = dt;
OrdersDataGridView.Refresh();
}
Can I use it in winforms ?
Example :
in SQL SERVER when I run the SELECT the output for
orders and tests like this :
Test order_id
CBC,TSH,LDL 100
In C# when run the above code the output for order multiple lines and not one row for each order in case multiple tests ordered in one order :
Test order_id
CBC 100
TSH 100
LDL 100
Are you sure you want to group by test id ? That would cause each test to not be in the list. Is this the same group by you had in the other system.
Hey i am getting a error telling me "Column 'RowNumber' does not belong to table Table1". the navigation works fine when i comment out the currentRecord line but i am no longer getting the value of current selected record. BandMember is the table managing the many to many relationship of band and member.
Here my method:
private void LoadBandMembers()
{
string sqlMemberID = $"SELECT * FROM BandMember WHERE BandID = {currentBandID} AND MemberID = {currentMemberID}";
string sqlNav =
$#"
SELECT
(SELECT COUNT(*) FROM BandMember) AS NumberOfBandMember,
(SELECT TOP(1) BandID as FirstBandID FROM BandMember
) as FirstBandID,
(
SELECT TOP(1) MemberID as FirstMemberID FROM BandMember
) as FirstMemberID,
q.PreviousBandID,
q.PreviousMemberID,
q.NextBandID,
q.NextMemberID,
(
SELECT TOP(1) BandID as LastBandID FROM BandMember ORDER BY BandID Desc
) as LastBandID,
(
SELECT TOP(1) MemberID as LastMemberID FROM BandMember ORDER BY BandID Desc
) as LastMemberID
FROM
(
SELECT BandID, MemberID,
LEAD(BandID) OVER(ORDER BY BandID) AS NextBandID,
LEAD(MemberID) OVER(ORDER BY BandID) AS NextMemberID,
LAG(BandID) OVER(ORDER BY BandID) AS PreviousBandID,
LAG(MemberID) OVER(ORDER BY BandID) AS PreviousMemberID,
ROW_NUMBER() OVER(ORDER BY BandID) AS 'RowNumber'
FROM BandMember
) AS q
WHERE q.BandID = {currentBandID} AND q.MemberID = {currentMemberID}
ORDER BY q.BandID, q.MemberID
";
sqlNav = DataAccess.SQLCleaner(sqlNav);
string[] sqlStatements = new string[] { sqlMemberID, sqlNav };
DataSet ds = new DataSet();
ds = DataAccess.GetData(sqlStatements);
if (ds.Tables[0].Rows.Count == 1)
{
DataRow selectedBandMember = ds.Tables[0].Rows[0];
int bandID = Convert.ToInt32(selectedBandMember["BandID"]);
int memberID = Convert.ToInt32(selectedBandMember["memberID"]);
cmbBand.SelectedValue = selectedBandMember["BandID"];
cmbMember.SelectedValue = selectedBandMember["MemberID"];
numberOfBandMember = Convert.ToInt32(ds.Tables[1].Rows[0]["NumberOfBandMember"]);
firstBandID = Convert.ToInt32(ds.Tables[1].Rows[0]["FirstBandID"]);
firstMemberID = Convert.ToInt32(ds.Tables[1].Rows[0]["FirstMemberID"]);
previousBandID = ds.Tables[1].Rows[0]["PreviousBandID"] != DBNull.Value ? Convert.ToInt32(ds.Tables["Table1"].Rows[0]["PreviousBandID"]) : (int?)null;
previousMemberID = ds.Tables[1].Rows[0]["PreviousMemberID"] != DBNull.Value ? Convert.ToInt32(ds.Tables["Table1"].Rows[0]["PreviousMemberID"]) : (int?)null; ;
nextBandID = ds.Tables[1].Rows[0]["NextBandID"] != DBNull.Value ? Convert.ToInt32(ds.Tables["Table1"].Rows[0]["NextBandID"]) : (int?)null;
nextMemberID = ds.Tables[1].Rows[0]["NextMemberID"] != DBNull.Value ? Convert.ToInt32(ds.Tables["Table1"].Rows[0]["NextMemberID"]) : (int?)null; ;
lastBandID = Convert.ToInt32(ds.Tables[1].Rows[0]["LastBandID"]);
lastMemberID = Convert.ToInt32(ds.Tables[1].Rows[0]["LastMemberID"]);
currentRecord = Convert.ToInt32(ds.Tables[1].Rows[0]["RowNumber"]);
DisplayToolStrip();
}
else
{
MessageBox.Show("The band member no longer exists");
LoadFirstBandMembers();
}
}
I'm semi-new from C# and i've never store objects from mysql query. I've declared 2 Datetimes variables:
DateTime date_min
DateTime date_max
I'd like to store max(date) and min(date) from below query
string query1 = "SELECT MIN(order_status.BEGIN_DATE) AS 'BEGIN DATE', MAX(order_status.END_DATE) AS 'END DATE' FROM project1.order_status INNER JOIN project1.orders ON orders.ID_ORDER = order_status.ID_ORDER WHERE orders.NUMBER_ORDER = 'TEST';";
like: max(date) = MAX(order_status.END_DATE)
min(date) = MIN(order_status.BEGIN_DATE)
which i want use in this loop:
for (DateTime date = date_min; date <= date_max; date = date.AddDays(1))
{
string query2 = "SELECT COUNT(leave.ID_PRACOWNIKA) AS 'NUMBER OF WORKERS ON LEAVE' FROM project1.leave WHERE DATE(leave.BEGIN_DATE) <= '"+date+"' AND DATE(leave.END_DATE) >= '"+date+"';";
string query3 = "SELECT TIME_FORMAT(SEC_TO_TIME(SUM(TIME_TO_SEC(order_status.END_DATE) - TIME_TO_SEC(order_status.BEGIN_DATE))), '%H:%i:%s') AS 'TIME OF ALL ORDERS IN DAY' FROM project1.order_status INNER JOIN project1.orders ON orders.ID_ORDER = order_status.ID_ORDER WHERE (DATE(order_status.BEGIN_DATE) = '"+date+"' AND DATE(order_status.END_DATE) = '"+date+"');";
string query4 = "SELECT TIME_FORMAT(SEC_TO_TIME(SUM(TIME_TO_SEC(order_status.END_DATE) - TIME_TO_SEC(order_status.BEGIN_DATE))), '%H:%i:%s') AS 'TIME OF ORDER IN DAY' FROM project1.order_status INNER JOIN project1.orders ON orders.ID_ORDER = order_status.ID_ORDER WHERE (DATE(order_status.BEGIN_DATE) = '"+date+"' AND DATE(order_status.END_DATE) = '"+date+"') AND orders.NUMBER_ORDER = 'TEST';";
}
Can someone please show what should kind of code line should I write? maybe cmd.Parameters is enough? THX for any help.
there is my code:
public partial class GenerateChartsOfOrders : Form
{
DateTime date_min;
DateTime date_max;
public GenerateChartsOfOrders()
{
InitializeComponent();
}
public void loaddata2()
{
string query1 = "SELECT MIN(order_status.BEGIN_DATE) AS 'BEGIN DATE', MAX(order_status.END_DATE) AS 'END DATE' FROM project1.order_status INNER JOIN project1.orders ON orders.ID_ORDER = order_status.ID_ORDER WHERE orders.NUMBER_ORDER = 'TEST';";
for (DateTime date = date_min; date <= date_max; date = date.AddDays(1))
{
string query2 = "SELECT COUNT(leave.ID_PRACOWNIKA) AS 'NUMBER OF WORKERS ON LEAVE' FROM project1.leave WHERE DATE(leave.BEGIN_DATE) <= '"+date+"' AND DATE(leave.END_DATE) >= '"+date+"';";
string query3 = "SELECT TIME_FORMAT(SEC_TO_TIME(SUM(TIME_TO_SEC(order_status.END_DATE) - TIME_TO_SEC(order_status.BEGIN_DATE))), '%H:%i:%s') AS 'TIME OF ALL ORDERS IN DAY' FROM project1.order_status INNER JOIN project1.orders ON orders.ID_ORDER = order_status.ID_ORDER WHERE (DATE(order_status.BEGIN_DATE) = '"+date+"' AND DATE(order_status.END_DATE) = '"+date+"');";
string query4 = "SELECT TIME_FORMAT(SEC_TO_TIME(SUM(TIME_TO_SEC(order_status.END_DATE) - TIME_TO_SEC(order_status.BEGIN_DATE))), '%H:%i:%s') AS 'TIME OF ORDER IN DAY' FROM project1.order_status INNER JOIN project1.orders ON orders.ID_ORDER = order_status.ID_ORDER WHERE (DATE(order_status.BEGIN_DATE) = '"+date+"' AND DATE(order_status.END_DATE) = '"+date+"') AND orders.NUMBER_ORDER = 'TEST';";
}
}
}
You can use ExecuteReader to retrieve the value as below,
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using(var command = new MySqlCommand(query1, con))
{
using(var reader = command.ExecuteReader())
{
while (reader.Read())
{
date_min = Convert.ToDateTime(reader[0]);
date_max = Convert.ToDateTime(reader[1]);
}
}
}
}
Hope it helps.
So, I'm trying to build a code generator that will extract indexes from a database and make a class that will filter based on an index.
Below code works in SQL-server and yields 2 records. But my SqlDataReader yields zero records.
Provided example for 1 table with index.
Hoping someone can help me out here.
Code in SQL server:
create table Agent(
ID bigint constraint PK_Agent primary key identity(1,1),
LastName nvarchar(50) not null,
FirstName nvarchar(50) not null,
index IN_Agent_Name nonclustered (LastName, FirstName)
)
select t.object_id,
s.name as schemaname,
t.name as tablename,
i.index_id,
i.name as indexname,
index_column_id,
c.name as columnname
from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on i.object_id = t.object_id
inner join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id = i.index_id
inner join sys.columns c on c.object_id = t.object_id and ic.column_id = c.column_id
where i.index_id > 0
and i.type in (1, 2)
and i.is_primary_key = 0
and i.is_unique_constraint = 0
and i.is_disabled = 0
and i.is_hypothetical = 0
and ic.key_ordinal > 0
and t.name like 'Agent'
and i.name like 'IN_Agent_Name'
Code in VS:
public static TableIndex GetIndex(string indexName, string tableName)
{
TableIndex index = null;
using (var conn = new SqlConnection("Server=localhost;Database=VenturaERD;User Id=VenturaDBUser;Password = Ventura;"))
{
conn.Open();
var cmd = new SqlCommand("select t.object_id, s.name as schemaname, t.name as tablename, i.index_id, i.name as indexname, index_column_id, c.name as columnname from sys.tables t inner join sys.schemas s on t.schema_id = s.schema_id inner join sys.indexes i on i.object_id = t.object_id inner join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id = i.index_id inner join sys.columns c on c.object_id = t.object_id and ic.column_id = c.column_id where i.index_id > 0 and i.type in (1, 2) and i.is_primary_key = 0 and i.is_unique_constraint = 0 and i.is_disabled = 0 and i.is_hypothetical = 0 and ic.key_ordinal > 0 and t.name like '" + tableName + "' and i.name like '" + indexName + "'")
{
Connection = conn
};
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
index = new TableIndex()
{
TableId = reader.GetInt32(reader.GetOrdinal("object_id")),
TableName = reader.GetString(reader.GetOrdinal("tablename")),
IndexId = reader.GetInt32(reader.GetOrdinal("index_id")),
IndexName = reader.GetString(reader.GetOrdinal("indexname")),
Columns = new List()
{
new IndexColumn()
{
ColumnName = reader.GetString(reader.GetOrdinal("columnname")),
Order=reader.GetInt32(reader.GetOrdinal("index_column_id"))
}
}
};
while (reader.Read())
{
index.Columns.Add(new IndexColumn()
{
ColumnName = reader.GetString(reader.GetOrdinal("columnname")),
Order = reader.GetInt32(reader.GetOrdinal("index_column_id"))
});
}
}
reader.Close();
}
}
return index;
}
Please check the users rights, I believe with only the public rights the user will not get any data.
Make sure the user you are connecting to with SQL management studio and the user in the connection string are the same.
The user (in my tests at least) needs at least the db_datareader role.
I am data binding of gridview by code behind :
protected void PumpGridBind()
{
string name = Request.QueryString[1].ToString();
string query = "select q1.ID , q1.Scenario, q1.Type, q1.StationName ,q1.minH,
q1.maxH ,q1.Station_Id, q1.Min_OL, q1.Max_OL, q2.Daily_Abstraction as Action
from
(select SD.id,SD.Scenario,PR.Type,PR.StationName,max(if(PARAM = 'minH', Value, '
-999.00'))
as 'minH',max(if(PARAM = 'maxH', Value, ' -999.00'))
as 'maxH',psd.Station_Id,psd.Min_OL,psd.Max_OL from sgwebdb.param_reference as PR
Inner
join
sgwebdb.scenario_data as SD ON PR.Param_Id = SD.Param_Id INNER JOIN
sgwebdb.qualicision_detail as Q ON SD.SCENARIO = Q.Alternative INNER JOIN
sgwebdb.pump_station_detail as psd ON psd.Station_Id = PR.Station_Id where PR.Type
= 'Pump' and Q.Alternative = '" + name + "' GROUP BY PR.Id) q1 JOIN (SELECT
t1.Daily_Abstraction ,t1.Station_id FROM sgwebdb.pump_station_data t1 INNER JOIN
(SELECT
Station_id, MAX(lastupdate) as lastupdate FROM sgwebdb.pump_station_data GROUP BY
Station_id ) t2 ON t1.Station_id = t2.Station_id AND t1.lastupdate = t2.lastupdate)
q2 on
q1.Station_Id=q2.Station_Id";
this.GridView2.DataSource = PSI.DataAccess.Database.DatabaseManager.GetConnection
().GetData(query);
GridView2.DataBind();
}
Here gridview's column minH is coming as a string.
Can we convert string to Double before binding with gridview?
you can use
string query = "select q1.ID , q1.Scenario, q1.Type, q1.StationName ,**CAST(q1.minH as DECIMAL(9,2)) q1.minH**