I am currently working on a project on a shopping cart. I already done the cart but somehow I cannot count the cart and it keep shows 0. I already check that the session for the user is grabbed.
This is the method I used:
//check cart count
public int getCartCount(string Username)
{
MySql.Data.MySqlClient.MySqlConnection msqlConnection = null;
msqlConnection = new MySql.Data.MySqlClient.MySqlConnection("server=localhost;User Id=root;password=rootPassw0rd;Persist Security Info=False;database=infosec;Integrated Security=False");
MySql.Data.MySqlClient.MySqlCommand msqlCommand = new MySql.Data.MySqlClient.MySqlCommand();
//define the connection used by the command object
msqlCommand.Connection = msqlConnection;
msqlCommand.CommandText = "SELECT COUNT(*) FROM shoppingcart WHERE Item_Id = #Username ";
msqlCommand.Parameters.AddWithValue("#Username", _Username);
msqlConnection.Open();
string nofRow = "";
MySql.Data.MySqlClient.MySqlDataReader msqlReader = msqlCommand.ExecuteReader();
if (msqlReader.Read())
{
nofRow = msqlReader["COUNT(*)"].ToString();
}
msqlConnection.Close();
msqlConnection.Close();
msqlReader.Dispose();
int cart = Convert.ToInt32(nofRow);
return cart;
This is the code behind for the .axps page:
//cart increase if there items added.
if (Session["customer_Username"] == null)
{
cartCount.InnerText = "Cart (0)";
}
else
{
cartBLL cBLL = new cartBLL();
string a = Session["customer_Username"].ToString();
int count = cBLL.getCartCount(a);
cartCount.InnerText = "Cart (" + count + ")";
}
Hope you all can help me find the problems.
Thanks in advanced.
Change this line :
nofRow = msqlReader["COUNT(*)"].ToString();
To
nofRow = msqlReader[0].ToString();
Perhaps, it helps you.
Well, maybe MySqlDataReader can have a problem with reading of "COUNT(*)" column (I have not tried yet).
Another point, when you read "COUNT(*)" column with msqlReader["COUNT(*)"], your result can be null and Convert.ToInt32(null) generates 0. (But this is very unlikely)
But more important, using MySqlDataReader is not a good choice in your case. Since you using COUNT(*) to get row counts, ExecuteScalar is a better choice which returns first column of first row in your query.
msqlCommand.CommandText = "SELECT COUNT(*) FROM shoppingcart WHERE Item_Id = #Username ";
msqlCommand.Parameters.AddWithValue("#Username", _Username);
int cart = (int)msqlCommand.ExecuteScalar();
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection msqlConnection = new MySqlConnection(conString))
using(MySqlCommand msqlCommand = myCon.CreateCommand())
{
//
}
Few things:
Verify that string a = Session["customer_Username"].ToString(); does return the username.
Change nofRow = msqlReader["COUNT(*)"].ToString(); to nofRow = msqlReader[0].ToString();. Your query has the count aggregate function in it.
Verify that SELECT COUNT(*) FROM shoppingcart WHERE Item_Id = #Username does pull in value. #Username needs to be replaced by the value that you have from the session.
Looks like you have a typo in this line msqlCommand.Parameters.AddWithValue("#Username", _Username);. _Username should be Username.
Related
i am creating a simple inventory system using c#. sales product table data added success.but sales table data added twice i don't know why. what i tried so far i attached below. i attached the sales table below record added twice
sales table
id subtoal pay bal
27 900.00 1000.00 100.00
28 900.00 1000.00 100.00
string bal = txtBal.Text;
string sub = txtSub.Text;
string pay = textBox1.Text;
sql = "insert into sales(subtoal,pay,bal) values(#subtoal,#pay,#bal); select ##identity;";
con.Open();
cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#subtoal", sub);
cmd.Parameters.AddWithValue("#pay", pay);
cmd.Parameters.AddWithValue("#bal", bal);
int lastinsertID = int.Parse(cmd.ExecuteScalar().ToString());
cmd.ExecuteNonQuery();
string proddname;
int price;
int qty;
int tot;
for (int row = 0; row < dataGridView1.Rows.Count; row++)
{
proddname = dataGridView1.Rows[row].Cells[0].Value.ToString();
price = int.Parse(dataGridView1.Rows[row].Cells[1].Value.ToString());
qty = int.Parse(dataGridView1.Rows[row].Cells[2].Value.ToString());
int total = int.Parse(dataGridView1.Rows[row].Cells[3].Value.ToString());
sql1 = "insert into sales_product(sales_id,prodname,price,qty,total) values(#sales_id,#prodname,#price,#qty,#total)";
cmd1 = new SqlCommand(sql1, con);
cmd1.Parameters.AddWithValue("#sales_id", lastinsertID);
cmd1.Parameters.AddWithValue("#prodname", proddname);
cmd1.Parameters.AddWithValue("#price", price);
cmd1.Parameters.AddWithValue("#qty", qty);
cmd1.Parameters.AddWithValue("#total", total);
cmd1.ExecuteNonQuery();
}
MessageBox.Show("Record Addddedddd");
con.Close();
As per Larnu's commment you were executing the query twice. In this case you should only use the ExecuteScalar() version to retrieve the last inserted id for later use
I also wanted to point out that the design intent is to initialize the parameters collection once, then re use it many times, executing each time. You should also put using statements to make your commands, more like this, and you should probably get into the habit of using SCOPE_IDENTITY() rather than ##identity:
using(var con = new SqlConnection(...)){
con.Open();
string bal = txtBal.Text;
string sub = txtSub.Text;
string pay = textBox1.Text;
sql = "insert into sales(subtoal,pay,bal) values(#subtoal,#pay,#bal); select scope_identity();";
int lastinsertId = 0;
using(var cmd = new SqlCommand(sql, con){
cmd.Parameters.AddWithValue("#subtoal", sub);
cmd.Parameters.AddWithValue("#pay", pay);
cmd.Parameters.AddWithValue("#bal", bal);
lastinsertID = (int)cmd.ExecuteScalar();
}
string proddname = "";
int price = 0;
int qty = 0;
int tot = 0;
sql1 = "insert into sales_product(sales_id,prodname,price,qty,total) values(#sales_id,#prodname,#price,#qty,#total)";
using(var cmd1 = new SqlCommand(sql1, con)){
cmd1.Parameters.AddWithValue("#sales_id", lastinsertID);
cmd1.Parameters.AddWithValue("#prodname", proddname);
cmd1.Parameters.AddWithValue("#price", price);
cmd1.Parameters.AddWithValue("#qty", qty);
cmd1.Parameters.AddWithValue("#total", total);
for (int row = 0; row < dataGridView1.Rows.Count; row++)
{
proddname = dataGridView1.Rows[row].Cells[0].Value.ToString();
price = int.Parse(dataGridView1.Rows[row].Cells[1].Value.ToString());
qty = int.Parse(dataGridView1.Rows[row].Cells[2].Value.ToString());
int total = int.Parse(dataGridView1.Rows[row].Cells[3].Value.ToString());
cmd1 = new SqlCommand(sql1, con);
cmd1.Parameters["#sales_id"].Value = lastinsertID;
cmd1.Parameters["#prodname"].Value = proddname;
cmd1.Parameters["#price"].Value = price;
cmd1.Parameters["#qty"].Value = qty;
cmd1.Parameters["#total"].Value = total;
cmd1.ExecuteNonQuery();
}
} //end using sqlcommand
}//end using sqlconnection - it will close as a result
MessageBox.Show("Record Addddedddd");
And then I also wanted to point out that your life could get a lot easier if you use Dapper. With dapper the code would look more like:
using(var connection = new SqlConnection(...))
sql = "insert into sales(subtoal,pay,bal) values(#subtoal,#pay,#bal); select scope_identity();";
var lastInsertId = connection.Query<int>(sql, new {
subtoal = txtSub.Text,
pay = textBox1.Text,
bal = txtBal.Text
}
).Single();
foreach(...)
}
It does all the parameter jiggling for you, runs the query, manages the connection ,returns a type casted int etc
Also if your datagridview is based on a DataTable (and even better a strongly typed datatable) you can use it in your foreach. Here's what a strongly typed table would look like:
using(...){
foreach(var ro in SalesProductTable){
sql = "insert into sales_product(sales_id,prodname,price,qty,total) values(#sales_id,#prodname,#price,#qty,#total)";
dapperConnection.Execute(sql, new { ro.sales_id, ro.prodname, ro.price, ro.qty, ro.total });
}
Yep, that's it; just 4 lines of code, and it's easier if your #param names match your column names in your strongly typed table.
I think you might even just be able to get Dapper to do the looping too, by passing the datatable in, so long as the rows have properties that are the same as the parameters in the query:
using(...){
sql = "insert into sales_product(sales_id,prodname,price,qty,total) values(#sales_id,#prodname,#price,#qty,#total)";
dapperConnection.Execute(sql, salesProductTable);
}
take a look - http://dapper-tutorial.net
I want to know how to add a foreign key into my website through the payment section which is I created a list Seminar for user to choose first including a schedule. After that, user can click register and redirect page into payment details form which is contains credit card or cash. after user make an payment and click confirm button then the database should be increase by one include the primary key of an id (auto generate).
My problem is why I am still getting an id which is -1 not even +1 (I checked, the database has not updated in SQL Server) because of an id is -1.
Here is my code regarding for the payment section
if (tbxName.Text != null && tbxCC.Text != null && ddlCCType.Text != null && tbxExpDate.Text != null)
{
ShoppingCart sc = (ShoppingCart)Session["cart"];
sc.Name = tbxName.Text;
if (rdbCash.Checked == true)
{
sc.OptionPay = rdbCash.Text;
}
else
{
sc.OptionPay = rdbCC.Text;
}
sc.CreditCard = tbxCC.Text;
sc.CreditCardType = ddlCCType.Text;
sc.SecurityCode = tbxCode.Text;
sc.CCExpiryDate = tbxExpDate.Text;
//sc.Registration.RegId = sc.Id;
int id = ShoppingCartDBMgr.purchaseSeminar(sc);
lblOutput.Text = "Confirm. order id is " + id;
//display output for payment successfully
//lblOutput.Text = "Payment Successfully!";
//make it null for amount, date and session of cart after transaction are being successful
lblAmount.Text = null;
lblDate.Text = null;
Session["cart"] = null;
My payment database manager code:
public static int purchaseSeminar(ShoppingCart sc)
{
int id = -1;
SqlConnection con = new SqlConnection(conStr);
try
{
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandText = "insert into Payment (payment_id, payment_name, payment_ccNo, payment_ccType, payment_ccCode, payment_expDate, payment_price, payment_optionPay, payment_date, reg_id) values (#payment_id, #payment_name, #payment_ccNo, #payment_ccType, #payment_ccCode, #payment_expDate, #payment_price, #payment_optionPay, #payment_date, #reg_id)";
command.Parameters.AddWithValue("#payment_id", sc.Id);
command.Parameters.AddWithValue("#payment_ccNo", sc.CreditCard);
command.Parameters.AddWithValue("#payment_ccType", sc.CreditCardType);
command.Parameters.AddWithValue("#payment_ccCode", sc.SecurityCode);
command.Parameters.AddWithValue("#payment_expDate", sc.CCExpiryDate);
command.Parameters.AddWithValue("#payment_price", sc.TotalAmount);
command.Parameters.AddWithValue("#payment_optionPay", sc.OptionPay);
command.Parameters.AddWithValue("#reg_id", sc.Registration.RegId);
DateTime da = DateTime.Now;
command.Parameters.AddWithValue("#payment_date", da);
con.Open();
command.CommandText = "SET IDENTITY_INSERT Payment ON";
if (command.ExecuteNonQuery() > 0)
{
command.CommandText = "Select ##identity";
id = Convert.ToInt32(command.ExecuteScalar());
}
return id;
}
finally
{
con.Close();
}
}
This is not a good way of doing it however for your answer
you should add
This should be on your first line
command.CommandText = "SET IDENTITY_INSERT Payment On";
command.CommandText = "insert into Payment (payment_id, payment_name, payment_ccNo, payment_ccType, payment_ccCode, payment_expDate, payment_price, payment_optionPay, payment_date, reg_id) values (#payment_id, #payment_name, #payment_ccNo, #payment_ccType, #payment_ccCode, #payment_expDate, #payment_price, #payment_optionPay, #payment_date, #reg_id)";
command.Parameters.AddWithValue("#payment_id", sc.Id);
command.Parameters.AddWithValue("#payment_ccNo", sc.CreditCard);
command.Parameters.AddWithValue("#payment_ccType", sc.CreditCardType);
command.Parameters.AddWithValue("#payment_ccCode", sc.SecurityCode);
command.Parameters.AddWithValue("#payment_expDate", sc.CCExpiryDate);
command.Parameters.AddWithValue("#payment_price", sc.TotalAmount);
command.Parameters.AddWithValue("#payment_optionPay", sc.OptionPay);
command.Parameters.AddWithValue("#reg_id", sc.Registration.RegId);
And this should be your last line
command.CommandText = "SET IDENTITY_INSERT Payment OFF";
I don't see where sc.Id is being assigned a value unlike the others(eg: sc.Name). Then inserting that(sc.Id) into the database will insert a null value. So when you query it from the database, converting it to an int32 value, returns '-1'.
That's what I think might be causing the problem along with the structure of your code.
Since your id is auto-generated, exclude the 'payment_ID' from your insert command. Example:
command.CommandText = "insert into Payment (payment_name, payment_ccNo,
payment_ccType, payment_ccCode, payment_expDate, payment_price,
payment_optionPay, payment_date, reg_id)
values (#payment_name, #payment_ccNo, #payment_ccType, #payment_ccCode,
#payment_expDate, #payment_price, #payment_optionPay,
#payment_date, #reg_id)";
command.Parameters.AddWithValue("#payment_ccNo", sc.CreditCard);
command.Parameters.AddWithValue("#payment_ccType", sc.CreditCardType);
command.Parameters.AddWithValue("#payment_ccType", sc.CreditCardType);
command.Parameters.AddWithValue("#payment_ccCode", sc.SecurityCode);
command.Parameters.AddWithValue("#payment_expDate", sc.CCExpiryDate);
command.Parameters.AddWithValue("#payment_price", sc.TotalAmount);
command.Parameters.AddWithValue("#payment_optionPay", sc.OptionPay);
command.Parameters.AddWithValue("#reg_id", sc.Registration.RegId);
As an identity column, 'payment_ID' doesn't expect a value so exclude it from your insert statement. That way, you won't need to turn IDENTITY INSERT on. So you'll remove those statements too from your code.
I'm using this code to select the maxID from a database table and each time I want to add a new record, the autogenerated ID is not the last one +1.
public formularAddCompanie()
{
InitializeComponent();
try
{
string cs = "Data Source=CODRINMA\\CODRINMA;Initial Catalog=TrafficManager;Integrated Security=True";
string select = "SELECT max(IDCompanie) FROM Companii";
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd2 = new SqlCommand(select, con);
SqlDataReader sda = cmd2.ExecuteReader();
DataTable idmax = new DataTable("idmax");
idmax.Load(sda);
if (idmax.Rows[0][0].ToString().Trim() == "") { txtID.Text = "1"; }
else { txtID.Text = (int.Parse(idmax.Rows[0][0] .ToString() + 1).ToString()); }
}
}
catch (Exception er) { MessageBox.Show(er.Message); }
}
The table from where the selection is made, looks like this:
IDCompany Name Address City RegNo
1 A Street NY 123
Each time I want to add a new record, the autogenerated ID is like this: 11, 111, 1111. It takes the last ID and add another 1 next to it. What am I missing?
Interestingly, note that
string a = "The meaning of life is " + 42;
converts 42 to a string, creating the result
a == "The meaning of life is 42"
Look at this code:
(int.Parse(idmax.Rows[0][0] .ToString() + 1).ToString()); }
You are converting idmax.Rows[0][0] to a string and adding +1 to the end of the string rather than to an integer value. Try
(int.Parse(idmax.Rows[0][0].ToString()) + 1).ToString(); }
Note that idmax.Rows[0][0] should already have an integer in it (as pointed out in the comments). If that's the case, you can simplify to
(idmax.Rows[0][0] + 1).ToString(); }
idmax.Rows[0][0].ToString() + 1 produces string, not int.
You can try
txtID.Text = (Convert.ToInt32(idmax.Rows[0][0]) + 1).ToString();
I just add this because it seems that none cares about the weakness of the code posted by the poster.
First the MAX function is not reliable if you want to find the next autoincrement value that will be assigned to an ID column. Concurrency could wreak havoc with any schema that use MAX. Just suppose that another user has already retrieved the MAX for its own INSERT operation, then depending on the relative speed of the two computers you or the other user will insert a duplicate value for the IDCompany field.
The only correct way to do this common task is to use the IDENTITY property for the column IDCompany and when you need to insert a new record you should write something like this
try
{
string insert = "INSERT INTO Companii (Name,Address,City,RegNo)
VALUES(#name,#address,#city,#regno);
SELECT SCOPE_IDENTITY()";
using (SqlConnection con = new SqlConnection(cs))
using (SqlCommand cmd = new SqlCommand(insert, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = txtBoxCity.Text;
.... and on for the other parameters ....
int companyID = Convert.ToInt32(cmd.ExecuteScalar());
... work with the just added company if required
}
}
catch (Exception er)
{ MessageBox.Show(er.Message); }
SCOPE_IDENTITY will return the last identity value inserted into an identity column in the same scope and in this context scope means the connection used by your command.
In any case, if the MAX approach is still required then the code could be simplified a lot using a modified query and SqlCommand.ExecuteScalar instead of building an SqlDataReader, filling a datatable, trying to parse the result with ifs
string getMax = #"select COALESCE(MAX(IDCompany), 0) + 1 AS maxPlusOne
from Companii"
using(SqlConnection cnn = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(getMax, cnn))
{
cnn.Open();
int nextCompanyID = Convert.ToInt32(cmd.ExecuteScalar());
}
The COALESCE function checks the result of the MAX function and if it is NULL returns the second parameter (here 0), then just increment by 1 to get the next MAX directly from the database. ExecuteScalar will do the call returning just the maxPlusOne alias field
try this snippet:
Convert Your String into Int. String with + operator will con-cat and with int it will add numbers.
if (idmax.Rows[0][0].ToString().Trim() == "") { txtID.Text = "1"; }
else {
txtID.Text = Convert.ToString(Convert.ToInt32(idmax.Rows[0][0] .ToString())+1); }
Try This one, my id format is USR001.The code will generate auto id based on the last id inside the database. If the last id in the database is USR001, the the code will generate USR002 and put the id to the textbox
con.Open();
string sqlQuery = "SELECT TOP 1 kode_user from USERADM order by kode_user desc";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string input = dr["kode_user"].ToString();
string angka = input.Substring(input.Length - Math.Min(3, input.Length));
int number = Convert.ToInt32(angka);
number += 1;
string str = number.ToString("D3");
txtKodeUser.Text = "USR" + str;
}
con.Close();
I have a method like this
private string AccountCreation()
{
string accountId="";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
StringBuilder sql = new StringBuilder();
sql.AppendLine("SELECT ACCOUNT_ID,CUSTOMER_ID FROM T_ACCOUNT order by ACCOUNT_ID desc");
sql.AppendLine("SET IDENTITY_INSERT T_ACCOUNT ON");
sql.AppendLine("INSERT INTO T_ACCOUNT (ACCOUNT_ID,CUSTOMER_ID)");
sql.AppendLine("SELECT ACCOUNT_ID + 1, CUSTOMER_ID +1 FROM T_ACCOUNT Where ACCOUNT_ID = (select max(ACCOUNT_ID) from T_ACCOUNT)");
sql.AppendLine("SET IDENTITY_INSERT T_ACCOUNT OFF");
accountId = Convert.ToString(sql.AppendLine("SELECT top 1 ACCOUNT_ID FROM T_ACCOUNT order by ACCOUNT_ID desc"));
string strUpdateQuery = sql.ToString();
ExecuteQuery(strUpdateQuery, command);
}
return accountId;
}
Now accountId is holding the query but not the value returned after execution of the query. I want the value in that string. Can anyone help me?
For getting value from the query. you need ExecuteScalar method.
object oRetVal = command.ExecuteScalar();
string accountId = string.Empty;
if(oRetVal != null)
{
accountId = oRetVal.ToString();
}
However, it is recommend to use store procedure.
I assume you are looking for the "TOP 1 Account_ID" from the query. What you have done there will not work (or give you what you want). You will need to either send in a output parameter to put the accountID in, or run fetch the data using datareader or dataset.
You'll have to bind the output of your ExecuteQuery to an object.
check if this returns any result and populates the accID.
var accID = ExecuteQuery(strUpdateQuery, command)
public string ExecuteQuery(string query,SqlCommand cmd)
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
object i=cmd.ExecuteScalar();
return i.ToString();
}
After this just assign this to the accounted
accountId = ExecuteQuery(strUpdateQuery, command);
I have asp.net site which contains 13 textboxes where a user can enter in certain information to search through a database. A gridview populates the data. The data is only for viewing purposes.
My issue is, every row is always returned. If a user types data into only one field, then only the rows containing that data should be returned. Instead, every row is returned no matter what and I can't seem to figure out what is wrong with my SQL Statement.
Here is the entire code:
SqlConnection mySqlConnection = new SqlConnection(strings.settings.connectionString);
SqlCommand mycommand = new SqlCommand("SELECT SOPID, CONTACT, SHIPTONAME, KNOWN_EMAIL, ADDR1, ADDR2, CITY, STATE, ZIPCODE, PHONE1, CUSTPO, CID, AID, SEATS FROM dbo.LOOKUP_TEST_TBL WHERE CONTACT = #CONTACT OR SHIPTONAME = #SHIPTONAME OR KNOWN_EMAIL = #KNOWN_EMAIL OR ADDR1 = #ADDR1 OR ADDR2 = #ADDR2 OR CITY = #CITY OR STATE = #STATE OR ZIPCODE = #ZIPCODE OR PHONE1 = #PHONE1 OR CUSTPO = #CUSTPO OR CID = #CID OR AID = #AID OR SEATS = #SEATS", mySqlConnection);
//AccessCommand.Parameters.AddWithValue("#ORDERID", SqlDbType.Char).Value = txtOrderID.Text.ToUpper();
mycommand.Parameters.AddWithValue("#CONTACT", SqlDbType.Char).Value = txtContact.Text.ToUpper();
mycommand.Parameters.AddWithValue("#SHIPTONAME", SqlDbType.Char).Value = txtShipToName.Text.ToUpper();
mycommand.Parameters.AddWithValue("#KNOWN_EMAIL", SqlDbType.Char).Value = txtEmail.Text.ToUpper();
mycommand.Parameters.AddWithValue("#ADDR1", SqlDbType.Char).Value = txtAddress1.Text.ToUpper();
mycommand.Parameters.AddWithValue("#ADDR2", SqlDbType.Char).Value = txtAddress2.Text.ToUpper();
mycommand.Parameters.AddWithValue("#CITY", SqlDbType.Char).Value = txtCity.Text.ToUpper();
mycommand.Parameters.AddWithValue("#STATE", SqlDbType.Char).Value = txtState.Text.ToUpper();
mycommand.Parameters.AddWithValue("#ZIPCODE", SqlDbType.Char).Value = txtZip.Text.ToUpper();
mycommand.Parameters.AddWithValue("#PHONE1", SqlDbType.Char).Value = txtPhone.Text.ToUpper();
mycommand.Parameters.AddWithValue("#CUSTPO", SqlDbType.Char).Value = txtCustomerPO.Text.ToUpper();
mycommand.Parameters.AddWithValue("#CID", SqlDbType.Char).Value = txtCustomerID.Text.ToUpper();
mycommand.Parameters.AddWithValue("#AID", SqlDbType.Char).Value = txtAddressID.Text.ToUpper();
mycommand.Parameters.AddWithValue("#SEATS", SqlDbType.Char).Value = txtSeats.Text.ToUpper();
mySqlConnection.Open();
SqlDataReader reader = mycommand.ExecuteReader();
if (reader.HasRows == false)
{
throw new Exception();
}
GridView1.DataSource = reader;
GridView1.DataBind();
}
Any tips or advice or a point in the right direction would be fantastic! Thanks everyone!
your query shoul look like
SELECT *
FROM dbo.LOOKUP_TEST_TBL
WHERE (CONTACT = #CONTACT and CONTACT is not null) or
(SHIPTONAME = #SHIPTONAME and SHIPTONAME is not null).....
just exclude the nullable records
The problem is almost certainly the query -- it will return any rows that have empty columns in any of those fields, which the user didn't provide.
I would try constructing the query using only the columns that the user has specified.
Get the non-empty parameters:
Dictionary<string, string> values = new Dictionary<string,string> {
{ "#CONTACT", txtContact.Text.ToUpper() },
{ "#ADDR1", txtAddress1.Text.ToUpper() },
// etc
};
var enteredParams = values.Where(kvp => !string.IsNullOrEmpty(kvp.Value));
And construct the query:
string sql = string.Format("SELECT ... WHERE {0}",
string.Join(" OR ",
enteredParams.Select(kvp =>
kvp.Key.TrimStart(new char[] { '#' }) + " = " + kvp.Key
)
);
And finally construct the parameters:
foreach (var kvp in enteredParams)
{
mycommand.Parameters.AddWithValue(kvp.Key, kvp.Value);
}
(Unchecked for exact syntax, but I think you get the idea.)
You OR everything in your WHERE clause together, so if even ONE of the things matches it'll be included in the results. Did you maybe mean to AND them together instead?