ColdFusion query to C# Winform - c#

I was given a query, originally done in ColdFusion, but I am having difficulties with the translation to a Winform use. I have a textbox that contains a concatenated string of other textboxes to make a case number. The purpose of this is to check for a record that might have been a transfer. In the first query, it is based on column caa443400048 either having something or being NULL. How would I incorporate that into a conditional statement for checking?
<cfquery name="q_transfer" datasource=#DSN#>
SELECT caa443400048
FROM caa44340
WHERE caa44340041 = '#SearchCaseNo#'
</cfquery>
<CFSET TransferCaseNo = "">
<CFSET TransferFlag = 'N'>
<CFIF #q_transfer.caa443400048# NEQ "">
<cfquery name="q_newcaseno" datasource=#DSN# >
SELECT caa44340041
FROM caa44340
WHERE caa443400018 = '#q_transfer.caa443400048#'
</cfquery>
<CFSET TransferFlag = 'Y'>
<CFSET TransferCaseNo = #SearchCaseNo#>
<CFSET SearchCaseNo = #q_newcaseno.caa44340041#>
</cfif>
Here is the C# code I am currently using:
string sql = "select COUNT (caa443400048) FROM caa44340 WHERE caa44340041 = ? ";
OdbcConnection con = new OdbcConnection("Dsn=XXXXX; User ID=XXXXX; Password=XXXXX");
con.Open();
OdbcCommand cmd = new OdbcCommand(sql, con);
cmd.Parameters.AddWithValue("caa44340041", txtCustomCaseNumber.Text);
int count = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
if (count != 0)
{
MessageBox.Show("This is a transfer");
}
else
{
MessageBox.Show("This is not a transfer");
}

I'm not 100%, but maybe this may help:
var TransferFlag = "N";
var SearchCaseNo = "";
var q_transfer = "";
var q_newcaseno = "";
using (var con = new OdbcConnection("Dsn=XXXXX; User ID=XXXXX; Password=XXXXX"))
{
con.Open();
using (var cmd = new OdbcCommand("SELECT caa443400048 FROM caa44340 WHERE caa44340041 = ?", con))
{
cmd.Parameters.AddWithValue("#var", txtCustomCaseNumber.Text);
q_transfer = (string)cmd.ExecuteScalar();
}
if (!string.IsNullOrEmpty(q_transfer))
{
using (var cmd = new OdbcCommand("SELECT caa44340041 FROM caa44340 WHERE caa443400018 = ?", con))
{
cmd.Parameters.AddWithValue("#var", q_transfer);
q_newcaseno = (string)cmd.ExecuteScalar();
}
TransferFlag = "Y";
SearchCaseNo = q_newcaseno;
MessageBox.Show("This is a transfer");
}
else
MessageBox.Show("This is not a transfer");
}

Related

There is no row at position 2

I am trying to execute this code in getting an error as
There is no row at position 2"
How can I solve this?
public JsonResult Question()
{
try
{
string [] Question=new string[2];
SqlConnection con = new SqlConnection(connectionString: "Server = (localdb)\\mssqllocaldb; Database = QuestionDb; Trusted_Connection = True; MultipleActiveResultSets = true");
con.Open();
string query = "";
query += #"select Id,Sum(Yes) AS T_Yes,Sum(No) AS T_No,Sum(DontKnow) AS T_DontKnow from dbo.Questions Group By Id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandText = query;
DataTable dt = new DataTable();
SqlDataAdapter cmd1 = new SqlDataAdapter(cmd);
cmd1.Fill(dt);
if (dt.Rows.Count == 0)
{
Question[0] = "0";
Question[1] = "0";
Question[2] = "0";
}
else
{
Question[0] = dt.Rows[0]["T_Yes"].ToString();
Question[1] = dt.Rows[1]["T_No"].ToString();
Question[2] = dt.Rows[2]["T_DontKnow"].ToString();
}
return Json(Question);
The problem is that you are mixing rows and columns. Use:
Question[0] = dt.Rows[0]["T_Yes"].ToString();
Question[1] = dt.Rows[0]["T_No"].ToString();
Question[2] = dt.Rows[0]["T_DontKnow"].ToString();
You must use always dt.Rows[0] (instead of [1] or [2]) to get the properties of the first row.
You're checking only to row count = 0, try this:
Also for comentary answer you need all data for the pie chart so need to recover all records.
Add a reference to System.Data, System.Collections.Generic and System.Linq to your project if this does not compile
List<string[]> listofIdGroups;
List<string[]> listofIdGroups;
listofIdGroups = dt.Rows.OfType<DataRow>()
.Select(dr => new string[3] { dr["T_Yes"].ToString(), dr["T_No"].ToString(), dr["T_DontKnow"].ToString() }).ToList();
you can read the list this way:
foreach (string[] question in listofIdGroups)
{
Console.WriteLine("Yes:" + question[0] + Environment.NewLine + "No: " + question[1] + Environment.NewLine + "DontKnow: " + question[2]);
}
try it here:
https://dotnetfiddle.net/0S1N3c

How to check SqlParameter is true with If

I want to check sqlparameter is true on if statements like this;
string sql1 = "SELECT * FROM users WHERE mail=#mail and passwd is null";
string sql2 = "SELECT * FROM users WHERE mail=#mail and passwd=#password";
SqlParameter prm1 = new SqlParameter("mail", txtMail.Text.Trim());
SqlParameter prm2 = new SqlParameter("password", txtPassword.Text.Trim());
if (sql1 == true)
{
MessageBox.Show("yes");
}
else if (sql2 == true)
{
MessageBox.Show("yes2");
}
{
MessageBox.Show("no");
}
It's rather unclear what you are trying to do, but it looks like you might want code like this:
const string query = #"
SELECT CASE WHEN passwdHash is null THEN 1 ELSE 2 END
FROM users
WHERE mail = #mail and (passwdHash is null OR passwdHash = #passwdHash);
";
using (var conn = new SqlConnection(yourConnString))
using (var comm = new SqlCommand(query, conn))
{
comm.Parameters.Add("#mail", SqlDbType.VarChar, 200).Value = txtMail.Text.Trim();
comm.Parameters.Add("#passwordHash", SqlDbType.Binary, 32) = SaltAndHashPassword(txtPassword.Text.Trim());
conn.Open();
var result = comm.ExecuteScalar() as int?;
conn.Close();
if (result == 1)
{
MessageBox.Show("yes");
}
else if (result == 2)
{
MessageBox.Show("yes2");
}
else
{
MessageBox.Show("no");
}
}
Note the following
using blocks on all Sql objects
Specify parameter types and lengths explicitly
Hash the password and compare that instead
Don't select *, just pass back a single column with a result
Close the connection before blocking with a MessageBox

Is there a way to validate the connection string if the server is closed or down?

I have problem regarding inserting the loop process. So when the connection string determine that the server is down, the inserting process stop looping. My question, is there way to determine whether this connection string is down or not? I have research they answer is to make if condition sqlconn.State == ConnectionState.Open I will show you guys the sample error that I encounter.
string connetionString = null;
MySqlConnection cnn;
connetionString = "server=localhost;database=sample_db_xx;uid=root;pwd=;";
cnn = new MySqlConnection(connetionString);
try
{
var arpp_pro = new List<string>();
cnn.Open();
MySqlCommand command = new MySqlCommand("SELECT store_id,CONCAT(boh,'\\\\sqlexpress') as boh FROM db_cua.stores WHERE " +
"is_active = 1 AND boh != '' ", cnn);
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader[0].ToString());
arpp_pro.Add(reader[1].ToString());
}
}
cnn.Close();
foreach (var arpp_pro_data in arpp_pro)
{
string connetionString_SQL = #"Server=" + arpp_pro_data + " \sqlexpress;Database=Site5;User ID=sa;Password=dospos";
//#"Server=" + arpp_pro_data + ";Database=Site5;User ID=sa;Password=dospos";
var date_minus_one_day = DateTime.Today.AddDays(-1);
var formatted_date_minus_one_day = date_minus_one_day.ToString("yyyy-MM-dd");
var year = DateTime.Now.ToString("yyyy");
var month = DateTime.Now.ToString("MM");
var date = DateTime.Today.AddDays(-1);
var date_formatted = date.ToString("dd");
string get_sos_orders_details = #"SELECT
Convert(nvarchar(50),dbo.SOS_ORDERS.OrderId)+ '-'+ Convert(nvarchar(50),dbo.SOS_ORDERS.TransTime) + Convert(nvarchar(50),dbo.Sales.TransactionId)+ Convert(nvarchar(50),dbo.Sales.TotalDeptName) as result,
dbo.Sales.StoreId,
Convert(nvarchar(50),dbo.SOS_ORDERS.TransTime) as TransTime,
dbo.Transactions.OperatorName as Cashier,
dbo.Sales.TotalDeptName as Transaction_Type,
dbo.Sales.TransactionId,
(dbo.SOS_ORDERS.DTOT + dbo.SOS_ORDERS.ASSM) as Cashier_Time,
(dbo.SOS_ORDERS.KIT) as Preparation_Time,
(dbo.SOS_ORDERS.KIT + dbo.SOS_ORDERS.DTOT + dbo.SOS_ORDERS.ASSM) as Total_Time
FROM dbo.SOS_ORDERS INNER JOIN
dbo.Sales ON dbo.SOS_ORDERS.OrderId = dbo.Sales.StoredOrderIndex INNER JOIN
dbo.Transactions ON dbo.Sales.Sequence = dbo.Transactions.Sequence
where dbo.Sales.businessdate= #date_minus_one_day
OR(DATEPART(yy, dbo.SOS_ORDERS.TransTime) = #year
AND DATEPART(mm, dbo.SOS_ORDERS.TransTime) = #month
AND DATEPART(dd, dbo.SOS_ORDERS.TransTime) = #date_today )
AND(dbo.Sales.TotalDeptName in ('01 SALLE MANGER', '02 EMPORTER')
or dbo.Sales.TotalDeptName in ('01 DINE IN', '02 TAKE OUT'))
GROUP BY dbo.SOS_ORDERS.OrderId, dbo.Sales.StoreId, dbo.SOS_ORDERS.TransTime, dbo.SOS_ORDERS.DTOT, dbo.SOS_ORDERS.LINE, dbo.SOS_ORDERS.WIND, dbo.SOS_ORDERS.SERV, dbo.SOS_ORDERS.HOLD,
dbo.SOS_ORDERS.TOTL, dbo.SOS_ORDERS.ASSM, dbo.SOS_ORDERS.CASH, dbo.SOS_ORDERS.FTOT, dbo.SOS_ORDERS.PAY, dbo.SOS_ORDERS.KIT, dbo.Sales.TransactionId,
dbo.Transactions.OperatorName, dbo.Sales.TotalDeptName order by dbo.SOS_ORDERS.TransTime DESC";
using (SqlConnection sqlconn = new SqlConnection(connetionString_SQL))
{
sqlconn.Open();
if (sqlconn.State == ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand(get_sos_orders_details, sqlconn);
cmd.Parameters.AddWithValue("#date_minus_one_day", formatted_date_minus_one_day);
cmd.Parameters.AddWithValue("#year", year);
cmd.Parameters.AddWithValue("#month", month);
cmd.Parameters.AddWithValue("#date_today", date_formatted);
SqlDataReader rs = cmd.ExecuteReader();
while (rs.Read())
{
// access your record colums by using reader
Console.WriteLine(rs["StoreId"]);
cnn.Open();
MySqlCommand comm = cnn.CreateCommand();
comm.CommandText = #"INSERT INTO master_data.so_v2 (StoreId,TransTime,Cashier,Transaction_Type,TransactionId,Cashier_Time,Preparation_Time)
VALUES(#Storeid, #TransTime, #Cashier, #Transaction_Type, #TransactionId, #Cashier_Time, #Preparation_Time)";
comm.Parameters.AddWithValue("#Storeid", rs["StoreId"]);
comm.Parameters.AddWithValue("#TransTime", rs["TransTime"]);
comm.Parameters.AddWithValue("#Cashier", rs["Cashier"]);
comm.Parameters.AddWithValue("#Transaction_Type", rs["Transaction_Type"]);
comm.Parameters.AddWithValue("#TransactionId", rs["TransactionId"]);
comm.Parameters.AddWithValue("#Cashier_Time", rs["Cashier_Time"]);
comm.Parameters.AddWithValue("#Preparation_Time", rs["Preparation_Time"]);
comm.ExecuteNonQuery();
cnn.Close();
}
}
sqlconn.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Thank you.
I suppose if all you wanted was a way to test and make sure a connection string is valid and that you can connect to the server and to the database, you could use a method like this:
public bool IsConnectionStringValid(string cs)
{
try
{
using (MySqlConnection conn = new MySqlConnection(cs))
{
conn.Open();
return true;
}
}
catch
{
return false;
}
}
Although I have to admit, in all my years of developing in C#, I've never used anything like this. Normally, as people have said in the comments, you already know before runtime that your connection string is valid and working.

Querying data from two databases in C#

I currently have a query where I am getting data from 2 different databases which is getting appended to one list called "accountbuys".
My first table has three data entry(3 accounts which want to buy stocks
The next table with 17 data points(17 stocks to buy)
I am merging these tables and getting output
However,the output I want , should have 17 data points repeated each time for the 3 different accounts, so that the end user can drill down and buy whichever stock he wants
PS: If what I am trying to ask is not clear, please be polite and tell me so. Please try not to be rude, I am still learning and new to StackExchange!
This is my code :`
public List<BuySellModel> GetBuyDataWthAccount()
{
List<BuySellModel> accountbuys = new List<BuySellModel>();
using (SqlConnection connectionreit = new SqlConnection(HubConnection))
using (SqlConnection connection = new SqlConnection(PMConnection))
{
connectionhub.Open();
connection.Open();
SqlCommand command3 = new SqlCommand(#"SELECT distinct(table1.name) as 'Symbol' ,table2.Segment as 'Segment',table2.AllocationAmount as 'AllocationAmount',table2.PX_LAST as 'Price',
table1.CUR_MKT_CAP as 'CMC',table1.FCFY_WITH_CUR_MKT_CAP as 'FCMC',table1.ROIC as 'ROIC', table1.ROICDELTA as 'ROICD' FROM View_REIT_Model_And_Holdings as table1
INNER JOIN [MostRecentlyInModelSelected] as table2
ON table1.name = table2.Ticker
WHERE table1.AllocationAmount != -1 AND
NOT EXISTS (SELECT NULL FROM [ViewPCData] as table3 WHERE table1.name = table3.Symbol AND table2.Segment = table3.SubsectorDescription AND table3.Objective = 'REITS' AND table3.SectorDescription != 'NULL' AND table3.SubsectorDescription != 'NULL')",
connectionreit);
command3.CommandType = CommandType.Text;
SqlCommand command4 = new SqlCommand("SELECT PortfolioAccountNumber, PortfolioDescription, SUM(TotalValue) as 'TotalValue' FROM [ViewPCData] WHERE Objective = 'REITS' GROUP BY PortfolioAccountNumber,PortfolioDescription", connection);
command4.CommandType = CommandType.Text;
var reader = command3.ExecuteReader();
var reader1 = command4.ExecuteReader();
if (reader1.HasRows)
{
while (reader1.Read())
{
BuySellModel accountb = new BuySellModel();
accountb.PortfolioAccount = reader1.GetString(reader1.GetOrdinal("PortfolioAccountNumber"));
accountb.PortfolioDescription = reader1.GetString(reader1.GetOrdinal("PortfolioDescription"));
accountb.AccountAmount = reader1.GetDecimal(reader1.GetOrdinal("TotalValue"));
accountbuys.Add(accountb);
if (reader.HasRows)
{
//foreach(var account in accountbuys)
//{
while (reader.Read())
{
BuySellModel buy = new BuySellModel();
buy.Symbol = reader.GetString(reader.GetOrdinal("Symbol"));
buy.Segment = reader.GetString(reader.GetOrdinal("Segment"));
//if (accountNumber == "soand os")
//{
// 1/3 of totalaccountvalue
buy.AllocationAmount = (reader.GetDouble(reader.GetOrdinal("AllocationAmount")));
//}
buy.Price = reader.GetDouble(reader.GetOrdinal("Price"));
buy.MarketValue = reader.GetDouble(reader.GetOrdinal("CMC"));
buy.FCFY = reader.GetDouble(reader.GetOrdinal("FCMC"));
buy.ROIC = reader.GetDouble(reader.GetOrdinal("ROIC"));
buy.ROICdelta = reader.GetDouble(reader.GetOrdinal("ROICD"));
buy.Buy = true;
//account1 = account.accountnumber;
accountbuys.Add(buy);
}
//} //for loop
}
} // accounts
} //reader1.hasrows
connectionhub.Close();
connection.Close();
}
return accountbuys;
}
EDIT:
Split the tables into two different lists and merged them later. This is working well now. Seems good for scaling too.
public List<BuySellModel> GetBuyDataWthAccount()
{
List<BuySellModel> accountbuys = new List<BuySellModel>();
List<Account> accounts = new List<Account>();
using (SqlConnection connection = new SqlConnection(PMConnection))
{
connection.Open();
SqlCommand command3 = new SqlCommand(#"SELECT distinct(table1.name) as 'Symbol' ,table2.Segment as 'Segment',table2.AllocationAmount as 'AllocationAmount',table2.PX_LAST as 'Price',
table1.CUR_MKT_CAP as 'CMC',table1.FCFY_WITH_CUR_MKT_CAP as 'FCMC',table1.ROIC as 'ROIC', table1.ROICDELTA as 'ROICD' FROM View_Model_And_Holdings as table1
INNER JOIN [MostRecentlyInModelSelected] as table2
ON table1.name = table2.Ticker
WHERE table1.AllocationAmount != -1 AND
NOT EXISTS (SELECT NULL FROM [ViewPCData] as table3 WHERE table1.name = table3.Symbol AND table2.Segment = table3.SubsectorDescription AND table3.Objective = 'STOCKS' AND table3.SectorDescription != 'NULL' AND table3.SubsectorDescription != 'NULL')",
connectionreit);
command3.CommandType = CommandType.Text;
SqlCommand command4 = new SqlCommand("SELECT PortfolioDetail , SUM(TotalValue) as 'TotalValue' FROM [ViewPCData] WHERE Objective = 'STOCKS' GROUP BY PortfolioAccountNumber,PortfolioDescription", connection);
command4.CommandType = CommandType.Text;
var reader = command3.ExecuteReader();
var reader1 = command4.ExecuteReader();
if (reader1.HasRows)
{
while (reader1.Read())
{
Account accountb = new Account();
accountb.PortfolioDetail = reader1.GetString(reader1.GetOrdinal("PortfolioDetail"));
// accountb.PortfolioDescription = reader1.GetString(reader1.GetOrdinal("PortfolioDescription"));
accountb.AccountAmount = reader1.GetDecimal(reader1.GetOrdinal("TotalValue"));
accounts.Add(accountb);
}
}
//List<BuyReits> buys = new List<BuyReits>();
if (reader.HasRows && accounts.Count > 0)
{
while (reader.Read())
{
foreach (var acc in accounts)
{
BuySellModel buy = new BuySellModel();
buy.Symbol = reader.GetString(reader.GetOrdinal("Symbol"));
buy.Segment = reader.GetString(reader.GetOrdinal("Segment"));
buy.AllocationAmount = (reader.GetDouble(reader.GetOrdinal("AllocationAmount")));
buy.Price = reader.GetDouble(reader.GetOrdinal("Price"));
//buy.Quantity = reader.GetInt32((reader.GetOrdinal("AllocationAmount"))/(reader.GetOrdinal("Price")));
buy.MarketValue = reader.GetDouble(reader.GetOrdinal("CMC"));
buy.FCFY = reader.GetDouble(reader.GetOrdinal("FCMC"));
buy.ROIC = reader.GetDouble(reader.GetOrdinal("ROIC"));
buy.ROICdelta = reader.GetDouble(reader.GetOrdinal("ROICD"));
buy.Buy = true;
buy.PortfolioAccount = acc.PortfolioDetail;
buy.AccountAmount = acc.AccountAmount;
accountbuys.Add(buy);
}
}
}
connection.Close();
}
return accountbuys;
}
The following provides the cross join in the C# layer (not saying it is the best possible solution, but it gets you closer to ready):
using (SqlConnection connectionhub = new SqlConnection(HubConnection))
using (SqlConnection connection = new SqlConnection(PMConnection))
{
connectionhub.Open();
connection.Open();
SqlCommand command3 = new SqlCommand(#"
SELECT distinct(table1.name) as 'Symbol',
table2.Segment as 'Segment',
table2.AllocationAmount as 'AllocationAmount',
table2.PX_LAST as 'Price',
table1.CUR_MKT_CAP as 'CMC',
table1.FCFY_WITH_CUR_MKT_CAP as 'FCMC',
table1.ROIC as 'ROIC',
table1.ROICDELTA as 'ROICD'
FROM View_REIT_Model_And_Holdings as table1
INNER JOIN [MostRecentlyInModelSelected] as table2
ON table1.name = table2.Ticker
WHERE table1.AllocationAmount != -1
AND NOT EXISTS (SELECT NULL
FROM [ViewPCData] as table3
WHERE table1.name = table3.Symbol
AND table2.Segment = table3.SubsectorDescription
AND table3.Objective = 'REITS'
AND table3.SectorDescription != 'NULL'
AND table3.SubsectorDescription != 'NULL')",
connectionreit);
command3.CommandType = CommandType.Text;
SqlCommand command4 = new SqlCommand(#"
SELECT PortfolioAccountNumber,
PortfolioDescription,
SUM(TotalValue) as 'TotalValue'
FROM [ViewPCData]
WHERE Objective = 'REITS'
GROUP BY PortfolioAccountNumber, PortfolioDescription", connection);
command4.CommandType = CommandType.Text;
var stocksDS = new DataSet();
var stocksDA = new System.Data.SqlClient.SqlDataAdapter();
stocksDA.SelectCommand = command3
stocksDA.Fill(stocksDS, "stocks");
var acctsDS = new DataSet();
var acctsDA = new System.Data.SqlClient.SqlDataAdapter();
acctsDA.SelectCommand = command4
acctsDA.Fill(acctsDS, "accts");
var stocks = stocksDS.Tables["stocks"].AsEnumerable();
var accts = acctsDS.Tables["accts"].AsEnumerable();
var results = (from stocksDR in stocks
from acctsDR in accts
select new BuySellModel {
PortfolioAccount = acctsDR["PortfolioAccountNumber"],
PortfolioDescription = acctsDR["PortfolioAccountDescription"],
AccountAmount = acctsDR["TotalValue"],
Symbol = stocksDR["Symbol"],
Segment = stocksDR["Segment"],
AllocationAmount = stocksDR["AllocationAmount"],
Price = stocksDR["Price"],
MarketValue = stocksDR["CMC"],
FCFY = stocksDR["FCMC"],
ROIC = stocksDR["ROIC"],
ROICdelta = stocksDR["ROICD"],
Buy = true
});
foreach (BySellModel buy in results) {
accountBuys.Add(buy);
}
connectionhub.Close();
connection.Close();
}
Edit: removed offending parentheses.
Without changing any of your C# code, it may be possible to get what you want by changing the SQL query from an INNER JOIN query to a CROSS JOIN query.
Some caveats regarding this approach though:
If you include a WHERE clause, the query will act as an INNER JOIN.
Cross joins can be significantly slower, as the query is looking to make all possible combinations. With only 51 (3 * 17) combinations available that will not be a significant issue, but if you are looking to scale this to more clients and stocks, it will become increasingly worse performance wise

how to write a single sql query based on combobox selection?

I have a winform in which user input values through a combobox. I am assigning combobox value to search db. If there is no selection then the SQL server query should not use that column to filter.
example -
if (string.IsNullOrEmpty(combobox1.text)) {
.....Select * from country
}
else if (combobox1.selectedindex > -1) {
....Select * from country where city_name = combobox.text
}
Is there a way to write a single query instead of using this multiple 'IF' conditions in case where user selects or doesn't select a value from combobox.
It is important to parameterize as well:
private const string _select = "select * from country";
void DoSomething()
{
string sql = string.Empty;
if (combobox1.SelectedIndex > -1)
{
command.Parameters.AddWithValue("#1", (string)combobox1.SelectedValue);
sql = " where city_name = #1";
}
sql = _select + sql;
command.CommandText = sql;
command.Execute...
}
#un-lucky asked me how would I deal with many conditions - here is one way
var conditions = new List<string>();
if (/* condition 1*/)
{
command.Parameters.AddWithValue("#2", (string)cboN.SelectedItem);
conditions.Add("col1 = #2");
}
if (/* condition 2*/)
{
command.Parameters.AddWithValue("#3", textBoxN.Text);
conditions.Add("col2 = #3");
}
if (conditions.Count > 0)
sql = _select + " where " + string.Join(" AND ", conditions.ToArray());
You can use the shorthand if only if you have two conditions:
string query = string.Format("Select * from country{0}", string.IsNullOrEmpty(combobox1.text) ? "" : " where city_name = " + combobox1.text);
Hope it helps!
I think you have to try something like this with parameterization:
StringBuilder queryBuilder = new StringBuilder("Select * from country Where 1=1 ");
SqlCommand cmdSql = new SqlCommand();
if (combobox1.selectedindex > -1)
{
queryBuilder.Append(" And city_name = #city_name ");
cmdSql.Parameters.Add("#city_name", SqlDbType.VarChar).Value = combobox.text;
}
else if(Condition 2)
{
queryBuilder.Append(" And column2 = #col2 ");
cmdSql.Parameters.Add("#col2", SqlDbType.VarChar).Value = "some Value here;
}
// Build the query like this
cmdSql.CommandText= = queryBuilder.ToString();
cmdSql.Connection = conObject;
// Here you can execute the command
I have a sample, try it
string select = this.combobox1.GetItemText(this.combobox1.SelectedItem); cm1 = new SqlCommand("Select * from country where city_name=#select or #select is null", con);
cm1.Parameters.Add("#select", SqlDbType.NVarChar, 50);
cm1.Parameters["#select"].Value = select;
dap = new SqlDataAdapter(cm1);
ds = new System.Data.DataSet();
dap.Fill(ds, "DATABASE");
//DataGridView1.DataSource = ds.Tables[0]; get data

Categories