Incorrext syntax near '=' error in SQL select query - c#

Error Text : Incorrect syntax near '='.
What is the error in my Code?
How I Can Select It right
this code to sure if this found or not
its All my Code Plz Check It
its to check my value and update some it
or insert
ssssssssssssssssssssssssssssssssssssssssssssssssssssssss
//Test For Insert Duplicate Row
int tst = 0;
SqlCommand cmd = new SqlCommand("Select Count(*) From Product Where ProdCode=#CodeVar And ProdName= #NameVar And BuyPrice=#PriceVar",conn);
cmd.Parameters.Add("#CodeVar", SqlDbType.Int).Value = Convert.ToDouble(dataGridView1.Rows[x].Cells[1].Value);
cmd.Parameters.Add("#NameVar", SqlDbType.NVarChar).Value = dataGridView1.Rows[x].Cells[2].Value;
cmd.Parameters.Add("#PriceVar", SqlDbType.Money).Value = Convert.ToDouble(dataGridView1.Rows[x].Cells[4].Value);
cmd.CommandType = CommandType.Text;
conn.Open();
SqlDataReader reader= cmd.ExecuteReader();
if(reader.Read())
{
if (Convert.ToInt16(reader[0]) > 0)
{
tst = 1;
}
}
reader.Close();
conn.Close();
// Test For Same Row But Anthor Code
cmd.CommandText = "Select Count(*) From Product Where ProdName=#PName And BuyPrice=#BPrice And Not ProdCode = #Pcode And ProdCode BETWEEN #SCode And #SCode+2000";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#PName",SqlDbType.NVarChar).Value = dataGridView1.Rows[x].Cells[2].Value ;
cmd.Parameters.Add("#BPrice", SqlDbType.Money).Value = Convert.ToDouble(dataGridView1.Rows[x].Cells[5].Value);
cmd.Parameters.Add("#Pcode",SqlDbType.Int).Value = Convert.ToInt32(dataGridView1.Rows[x].Cells[1].Value);
cmd.Parameters.Add("#SCode", SqlDbType.Decimal).Value = Convert.ToDecimal(label10.Text);
cmd.CommandType = CommandType.Text;
conn.Open();
reader = cmd.ExecuteReader();
if(reader.Read())
{
if(Convert.ToInt16(reader[0])>0)
{
tst = 2;
}
}
reader.Close();
conn.Close();
cmd.CommandText = "Select Count(*) From Product Where ProdCode = #CodeVar1 ";
cmd.Parameters.Add("#CodeVar1", SqlDbType.Int).Value = Convert.ToInt32(dataGridView1.Rows[x].Cells[1].Value);
cmd.CommandType = CommandType.Text;
conn.Open();
reader= cmd.ExecuteReader();
if (reader.Read())
{
if (Convert.ToInt16(reader[0]) > 0 && tst == 0)
{
MessageBox.Show("الأكواد باللون الأحمر خاصة احد الأصناف ..!");
dataGridView1.Rows[x].Cells[1].Style = redcell;
return;
}
}
reader.Close();
conn.Close();

You should try to replace ProdCode Not = #Pcode with ProdCode != #Pcode or ProdCode <> #Pcode or Not ProdCode = #Pcode.
All should be valid in TSQL.

change
and ProdCode Not = #Pcode
to
and not ProdCode = #Pcode

You need to replace the ProdCode Not = #Pcode in your sql command with ProdCode <> #Pcode

Related

Cannot Fetch the Last_inserted_id in a foreach loop inside another foreach mysql C#

the image above shows the output inside mysql Tables.
my problem is it cannot get the value of last_inserted_id value in ORDERTABLE, as it is the reference value in ItemTable itemid.
this is my code in SAVEORDER and SAVEITEM
the description =is where I split the Data into a foreach and save it in item table.
each split should save each data with corresponding orderid, I tried last_inserted_id and not MaxID as i want it to be done by 1-3 user simultaneously without having problem in data integrity.
private void SaveOrder()
{
try
{
foreach (DataGridViewRow row in DGSingleOrders.Rows)
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "INSERT INTO single_order (customerid, category, type, description, code, color, price, status, transaction, attendee) VALUES (#customerid, #category, #type, #description, #code, #color, #price, #status, #transaction, #attendee)";
cmd.CommandType = CommandType.Text;
cmd.Connection = db.con;
db.con.Open();
cmd.Parameters.Add("#customerid", MySqlDbType.VarChar).Value = OrderID;
cmd.Parameters.Add("#category", MySqlDbType.VarChar).Value = row.Cells[0].Value.ToString();
cmd.Parameters.Add("#type", MySqlDbType.VarChar).Value = row.Cells[1].Value.ToString();
cmd.Parameters.Add("#description", MySqlDbType.VarChar).Value = row.Cells[2].Value.ToString();
cmd.Parameters.Add("#code", MySqlDbType.VarChar).Value = row.Cells[3].Value.ToString();
cmd.Parameters.Add("#color", MySqlDbType.VarChar).Value = row.Cells[4].Value.ToString();
cmd.Parameters.Add("#price", MySqlDbType.VarChar).Value = row.Cells[5].Value.ToString();
cmd.Parameters.Add("#status", MySqlDbType.VarChar).Value = SaveAs;
cmd.Parameters.Add("#transaction", MySqlDbType.VarChar).Value = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss tt");
cmd.Parameters.Add("#attendee", MySqlDbType.VarChar).Value = attendee;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
db.con.Close();
}
//Check this first
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "SELECT LAST_INSERT_ID()";
cmd.Connection = db.con;
db.con.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
long id;
while (reader.Read())
{
id = reader.GetInt64(0);
ItemID = id.ToString();
}
db.con.Close();
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message,"ORDER");
db.con.Close();
return;
}
}
private void SaveItem()
{
//Getting Each Data
foreach (DataGridViewRow row in DGSingleOrders.Rows)
{
string item = row.Cells[1].Value.ToString();
string type = row.Cells[0].Value.ToString();
string str = row.Cells[2].Value.ToString();
string code = row.Cells[3].Value.ToString();
string color = row.Cells[4].Value.ToString();
List<string> descr = str.Split('+').ToList<string>();
//Splitting Description
//Adding Split to a DataTable
foreach (var l in descr)
{
OrderRow = l;
try
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "INSERT INTO single_item (orderid, type, item, brand, code, color, eventdate, orderstatus, itemstatus, orderchecker, attendee)VALUES(#orderid, #type, #item, #brand, #code, #color, #eventdate, #orderstatus, #itemstatus, #orderchecker, #attendee)";
cmd.CommandType = CommandType.Text;
cmd.Connection = db.con;
cmd.Parameters.Add("#orderid", MySqlDbType.VarChar).Value = ItemID;
cmd.Parameters.Add("#type", MySqlDbType.VarChar).Value = type;
cmd.Parameters.Add("#item", MySqlDbType.VarChar).Value = OrderRow;
cmd.Parameters.Add("#brand", MySqlDbType.VarChar).Value = "-";
cmd.Parameters.Add("#code", MySqlDbType.VarChar).Value = code;
cmd.Parameters.Add("#color", MySqlDbType.VarChar).Value = color;
cmd.Parameters.Add("#eventdate", MySqlDbType.VarChar).Value = eventDay;
cmd.Parameters.Add("#orderstatus", MySqlDbType.VarChar).Value = SaveAs;
cmd.Parameters.Add("#itemstatus", MySqlDbType.VarChar).Value = "Good";
cmd.Parameters.Add("#orderchecker", MySqlDbType.VarChar).Value = "Not Updated";
cmd.Parameters.Add("#attendee", MySqlDbType.VarChar).Value = atendee;
db.con.Open();
cmd.ExecuteNonQuery();
db.con.Close();
dtItems.Clear();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
db.con.Close();
return;
}
SaveItem();
}
}
I added SaveItem(); Method inside SaveOrder(); ForeachLoop so that it can save together with the ORDER table, and can fetch the data of Last_inserted_id but it still get the first ID, I also tried putting it out the foreach loop, but then I can't get the result of the Order ID, and save data differently.
You can use MySqlCommand.LastInsertedId to get the ID of the row that was just inserted, without a separate query. It's also guaranteed to contain the correct value because it comes directly from MySQL's response to the INSERT statement.
long itemId;
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "INSERT INTO single_order (customerid, ...";
// ...
cmd.ExecuteNonQuery();
itemId = cmd.LastInsertedId;
}
// ...
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "INSERT INTO single_item (orderid, ...";
cmd.Parameters.AddWithValue("#orderid", itemID);
// ...
}
So I figure it out.
Instead of using SELECT LAST_INSERT_ID() which has some documentation that it only returns the first ID that has been insert. Bradley Grainger offer to use MySqlCommand.InsertLastId;
I've modified it to this.
cmd.ExecuteNonQuery();
cmd.Parameters.Add(new MySqlParameter("newId", cmd.LastInsertedId));
ItemID = Convert.ToInt32(cmd.Parameters["#newId"].Value);
MessageBox.Show(ItemID.ToString());
```
now it is working. It can fetch the lastInserted iD in each loop, and the beauty of it is it can be threadsafe and can work along with simultaneous insert.
Also this link help me. https://livshitz.wordpress.com/2011/10/28/returning-last-inserted-id-in-c-using-mysql-db-provider/

play math with sql commands

i'm working on restaurants programming with c#
working on the daily quantity of the material
i do count of the total that they make on the day then count how many they used and how many remaining on that day
my code is
public void ExecuteQuery(string query)
{
foreach (Control txt in this.Controls)
{
if (txt.GetType() == typeof(TextBox))
if (string.IsNullOrEmpty(txt.Text))
txt.Text = "0";
}
SqlCommand com = new SqlCommand(query, connection);
com.Parameters.Add("#shish_add", SqlDbType.Int).Value = shish_add.Text;
com.Parameters.Add("#bani_add", SqlDbType.Int).Value = bani_add.Text;
com.Parameters.Add("#zingr_add", SqlDbType.Int).Value = zingr_add.Text;
com.Parameters.Add("#tabona_add", SqlDbType.Int).Value = tabona_add.Text;
com.Parameters.Add("#fahita_chkn_add", SqlDbType.Int).Value = fahita_chkn_add.Text;
com.Parameters.Add("#borger_add", SqlDbType.Int).Value = borger_add.Text;
com.Parameters.Add("#kabab_add", SqlDbType.Int).Value = kabab_add.Text;
com.Parameters.Add("#shgef_add", SqlDbType.Int).Value = shgef_add.Text;
com.Parameters.Add("#faheta_met_add", SqlDbType.Int).Value = faheta_met_add.Text;
com.Parameters.Add("#kabda_add", SqlDbType.Int).Value = kabda_add.Text;
com.Parameters.Add("#shawo_met_add", SqlDbType.Int).Value = shawo_met_add.Text;
com.Parameters.Add("#shawo_chkn_add", SqlDbType.Int).Value = shawo_chkn_add.Text;
com.Parameters.Add("#chkn_mash_add", SqlDbType.Int).Value = chkn_mash_add.Text;
com.Parameters.Add("#chkn_red_add", SqlDbType.Int).Value = chkn_red_add.Text;
com.Parameters.Add("#patata_add", SqlDbType.Int).Value = patata_add.Text;
com.Parameters.Add("#shish_take", SqlDbType.Int).Value = shish_take.Text;
com.Parameters.Add("#bani_take", SqlDbType.Int).Value = bani_take.Text;
com.Parameters.Add("#zingr_take", SqlDbType.Int).Value = zingr_take.Text;
com.Parameters.Add("#tabona_take", SqlDbType.Int).Value = tabona_take.Text;
com.Parameters.Add("#fahita_chkn_take", SqlDbType.Int).Value = fahita_chkn_take.Text;
com.Parameters.Add("#borger_take", SqlDbType.Int).Value = borger_take.Text;
com.Parameters.Add("#kabab_take", SqlDbType.Int).Value = kabab_take.Text;
com.Parameters.Add("#shgef_take", SqlDbType.Int).Value = shgef_take.Text;
com.Parameters.Add("#faheta_met_take", SqlDbType.Int).Value = faheta_met_take.Text;
com.Parameters.Add("#kabda_take", SqlDbType.Int).Value = kabda_take.Text;
com.Parameters.Add("#shawo_met_take", SqlDbType.Int).Value = shawo_met_take.Text;
com.Parameters.Add("#shawo_chkn_take", SqlDbType.Int).Value = shawo_chkn_take.Text;
com.Parameters.Add("#chkn_mash_take", SqlDbType.Int).Value = chkn_mash_take.Text;
com.Parameters.Add("#chkn_red_take", SqlDbType.Int).Value = chkn_red_take.Text;
com.Parameters.Add("#patata_take", SqlDbType.Int).Value = patata_take.Text;
com.Parameters.Add("#shish_rom", SqlDbType.Int).Value = shish_rom.Text;
com.Parameters.Add("#bani_rom", SqlDbType.Int).Value = bani_rom.Text;
com.Parameters.Add("#zingr_rom", SqlDbType.Int).Value = zingr_rom.Text;
com.Parameters.Add("#tabona_rom", SqlDbType.Int).Value = tabona_rom.Text;
com.Parameters.Add("#fahita_chkn_rom", SqlDbType.Int).Value = fahita_chkn_rom.Text;
com.Parameters.Add("#borger_rom", SqlDbType.Int).Value = borger_rom.Text;
com.Parameters.Add("#kabab_rom", SqlDbType.Int).Value = kabab_rom.Text;
com.Parameters.Add("#shgef_rom", SqlDbType.Int).Value = shgef_rom.Text;
com.Parameters.Add("#faheta_met_rom", SqlDbType.Int).Value = faheta_met_rom.Text;
com.Parameters.Add("#kabda_rom", SqlDbType.Int).Value = kabda_rom.Text;
com.Parameters.Add("#shawo_met_rom", SqlDbType.Int).Value = shawo_met_rom.Text;
com.Parameters.Add("#shawo_chkn_rom", SqlDbType.Int).Value = shawo_chkn_rom.Text;
com.Parameters.Add("#chkn_mash_rom", SqlDbType.Int).Value = chkn_mash_rom.Text;
com.Parameters.Add("#chkn_red_rom", SqlDbType.Int).Value = chkn_red_rom.Text;
com.Parameters.Add("#patata_rom", SqlDbType.Int).Value = patata_rom.Text;
com.Parameters.Add("#dates", SqlDbType.DateTime).Value = dates.Value.Date;
if (connection.State == ConnectionState.Closed)
connection.Open();
com.ExecuteNonQuery();
connection.Close();
foreach (Control txt in this.Controls)
{
if (txt.GetType() == typeof(TextBox))
if (txt.Text == "0")
txt.Text = "";
}
MessageBox.Show("تمت عملية الاضافة بنجاح", "ملاحظة", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
public void doqury(string strn)
{
string sqlQuery = strn;
ExecuteQuery(sqlQuery);
}
private void button1_Click(object sender, EventArgs e)
{
// check for first time entry
SqlCommand cmd = new SqlCommand("select * from megana_cooking ", connection);
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
//mean there values on database
//now need to check is this a new day or not
SqlCommand cmd1 = new SqlCommand("select * from megana_cooking where dates = #dates", connection);
connection.Open();
SqlDataReader reader1 = cmd.ExecuteReader();
if (reader1.HasRows)
{
//no this is the take valus statment
reader.Close();
doqury("UPDATE megana_cooking SET shish_rom =shish_add - #shish_take ,bani_rom =bani_add - #bani_take ,zingr_rom =zingr_add - #zingr_take ,tabona_rom =tabona_add - #tabona_take ,fahita_chkn_rom =fahita_chkn_add - #fahita_chkn_take ,borger_rom =borger_add - #borger_take ,kabab_rom =kabab_add - #kabab_take ,shgef_rom =shgef_add - #shgef_take ,faheta_met_rom =faheta_met_add - #faheta_met_take ,kabda_rom =kabda_add - #kabda_take ,shawo_met_rom =shawo_met_add - #shawo_met_take ,shawo_chkn_rom =shawo_chkn_add - #shawo_chkn_take ,chkn_mash_rom =chkn_mash_add - #chkn_mash_take ,chkn_red_rom =chkn_red_add - #chkn_red_take ,patata_rom =patata_add - #patata_take ,patata_take =#patata_take,chkn_red_take =#chkn_red_take,chkn_mash_take =#chkn_mash_take,shawo_chkn_take =#shawo_chkn_take,shawo_met_take =#shawo_met_take,kabda_take =#kabda_take,faheta_met_take =#faheta_met_take,shgef_take =#shgef_take,kabab_take =#kabab_take,borger_take =#borger_take,fahita_chkn_take =#fahita_chkn_take,tabona_take =#tabona_take,zingr_take =#zingr_take,bani_take =#bani_take,shish_take =#shish_take ,dates =#dates where dates = #dates ");
}
else
{
// yes new day new values and add value to the remain values from last entry
DialogResult result = MessageBox.Show("سيتم ادخال بيانات ليوم جديد " + Environment.NewLine + " سيقوم بأدخال البيانات دون احتساب عملية السحب", "تأكيد", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign);
doqury("INSERT INTO megana_cooking ( shish_add ,bani_add ,zingr_add ,tabona_add ,fahita_chkn_add ,borger_add ,kabab_add ,shgef_add ,faheta_met_add ,kabda_add ,shawo_met_add ,shawo_chkn_add ,chkn_mash_add ,chkn_red_add ,patata_add ,dates ) VALUES ( #shish_add ,#bani_add ,#zingr_add ,#tabona_add ,#fahita_chkn_add ,#borger_add ,#kabab_add ,#shgef_add ,#faheta_met_add ,#kabda_add ,#shawo_met_add ,#shawo_chkn_add ,#chkn_mash_add ,#chkn_red_add ,#patata_add ,#dates )");
//insert new quentity done now need to update the remain value
//new quentity + last remain
here need to find the last date that it have value then update and add the new quantity to it
}
}
else
{
//this is first entry
reader.Close();
DialogResult result = MessageBox.Show("سيتم ادخال البيانات الى المنظومة لاول مره " + Environment.NewLine + " سيقوم بأدخال البيانات دون احتساب عملية السحب", "تأكيد", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign);
doqury("INSERT INTO megana_cooking ( shish_add ,bani_add ,zingr_add ,tabona_add ,fahita_chkn_add ,borger_add ,kabab_add ,shgef_add ,faheta_met_add ,kabda_add ,shawo_met_add ,shawo_chkn_add ,chkn_mash_add ,chkn_red_add ,patata_add ,shish_rom ,bani_rom ,zingr_rom ,tabona_rom ,fahita_chkn_rom ,borger_rom ,kabab_rom ,shgef_rom ,faheta_met_rom ,kabda_rom ,shawo_met_rom ,shawo_chkn_rom ,chkn_mash_rom ,chkn_red_rom ,patata_rom ,dates ) VALUES ( #shish_add ,#bani_add ,#zingr_add ,#tabona_add ,#fahita_chkn_add ,#borger_add ,#kabab_add ,#shgef_add ,#faheta_met_add ,#kabda_add ,#shawo_met_add ,#shawo_chkn_add ,#chkn_mash_add ,#chkn_red_add ,#patata_add ,#shish_add ,#bani_add ,#zingr_add ,#tabona_add ,#fahita_chkn_add ,#borger_add ,#kabab_add ,#shgef_add ,#faheta_met_add ,#kabda_add ,#shawo_met_add ,#shawo_chkn_add ,#chkn_mash_add ,#chkn_red_add ,#patata_add ,#dates )");
}
connection.Close();
}
the question is
i need to find the last date that it have value then update and add the new quantity to it i did mention it in my code
i know i can because when i tried this code on new query on sql management studio it work
SELECT
*
FROM
megana_cooking
ORDER BY
dates
update megana_cooking set shish_rom = shish_rom + '5'
can i make the sql command shorter than this by using sql programmability or server side because i have more than 15 type of the material food
i have weak knowledge about sql
thank you in advance

if (counter == < database value >)

How do I make the value from my database as a int that I can use for my if else function ?
For example: In my database "armnumber = 3", how do I use it in my if else function ?
code
string myConnectionString;
myConnectionString = "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
try
{
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
string sqlStr = "Select armnumber from assign where id=1";
cmd.CommandText = sqlStr;
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
}
#endregion
if (counter == )
{
}
One option would be MySqlDataAdapter like this:
MySqlDataAdapter da = new MySqlDataAdapter {SelectCommand = cmd};
DataSet ds = new DataSet();
int armnumber = da.Fill(ds);
...
if (counter == armnumber)
Also you should always use parameterized queries to avoid SQL Injection:
string sqlStr = "Select armnumber from assign where id=#id";
cmd.Parameters.AddWithValue("#id", 1);
//Or better
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
You should replace this code
connection.Open();
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();
int databaseValue = int.Parse(reader["armnumber"].ToString());
connection.Close();
Few initial notes:
Continue operations after getting exception will not be a good practice, so I prefer the condition if (counter == xx ) inside the try block.
If the value of ID in the where clause is variable then make use of parameterization instead for concatenated queries.
Since you are fetching only a single field make use of ExecuteScalar instead for ExecuteNonQuery
You can make use of using als well for proper managing of connection and command objects.
So the code can be written as :
try
{
string sqlStr = "Select armnumber from assign where id=#id";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.Parameters.AddWithValue("#id", 1);
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlStr;
cmd.Connection = connection;
connection.Open();
var result = cmd.ExecuteScalar();
int armnumber = result != null ? int.Parse(result.ToString()) : 0;
if (counter == armnumber)
{
// code here
}
}
catch (MySqlException ex)
{
}

Autocomplete textbox with two option to search in c# winform

This is my code on my FormLoad-event
SqlDataReader dReader;
SqlConnection conn = new SqlConnection(MyClass.GlobalConn());
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
if (radioName.checked==true)
{
cmd.CommandText = "select RTRIM(Person_name) from MyTable order by Person_name";
}
else
{
cmd.CommandText = "select RTRIM(Person_number) from MyTable order by Person_number";
}
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader[0].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
tPT.AutoCompleteMode = AutoCompleteMode.Suggest;
tPT.AutoCompleteSource = AutoCompleteSource.CustomSource;
tPT.AutoCompleteCustomSource = namesCollection;
conn.Close();
I want two options to populate an autocomplete textbox during typing in textbox:
By name
By number
However it doesn't work. I already tryed this in my TextChanged-event, but with no luck. Can somebody help me?
Rather than using optional AutoCompleteSource update all the data into one source. This wont be any problem, since the person wont have to select the options, rather he will type by deciding his option.
SqlDataReader dReader;
SqlConnection conn = new SqlConnection(MyClass.GlobalConn());
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select RTRIM(Person_name) from MyTable order by Person_name";
dReader = cmd.ExecuteReader();
cmd.CommandText = "select RTRIM(Person_number) from MyTable order by Person_number";
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader[0].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
tPT.AutoCompleteMode = AutoCompleteMode.Suggest;
tPT.AutoCompleteSource = AutoCompleteSource.CustomSource;
tPT.AutoCompleteCustomSource = namesCollection;
conn.Close();
or if you want to use the older option,
namesCollection.RemoveAll();
SqlDataReader dReader;
SqlConnection conn = new SqlConnection(MyClass.GlobalConn());
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
namesCollection.RemoveAll();
if (radioName.checked==true)
{
cmd.CommandText = "select RTRIM(Person_name) from MyTable order by Person_name";
}
else
{
cmd.CommandText = "select RTRIM(Person_number) from MyTable order by Person_number";
}
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader[0].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
tPT.AutoCompleteMode = AutoCompleteMode.Suggest;
tPT.AutoCompleteSource = AutoCompleteSource.CustomSource;
tPT.AutoCompleteCustomSource = namesCollection;
conn.Close();
Notice
namesCollection.RemoveAll();

Read CheckBox Values in ASP.Net from a SQL db?

I have a table of CheckBoxes that are inserted into a SQL db as '1' and '0'. However, I would like to retrieve those values again with a load event, but I'm not able to get them. This is my code:
private void getAuditChecklist()
{
SqlCommand cmd = null;
string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string queryString = #"SELECT Mount, Braker, Access, Conn_Net, Log_Book, Pictures, Floor, Cb_Lenght, Channel FROM AUDITOR_CHECKLIST " +
"WHERE SITE_ID = #SiteID";
using (SqlConnection connection =
new SqlConnection(conn))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
cmd = new SqlCommand(queryString);
cmd.Connection = connection;
cmd.Parameters.Add(new SqlParameter("#SiteID", //the name of the parameter to map
System.Data.SqlDbType.NVarChar, //SqlDbType value
20, //The width of the parameter
"SITE_ID")); //The name of the column source
//Fill the parameter with the value retrieved
//from the text field
cmd.Parameters["#SiteID"].Value = foo.Site_ID;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
CheckBox1.Checked = (reader.GetBoolean(reader.GetOrdinal("Mount")));
CheckBox2.Checked = (reader.GetBoolean(reader.GetOrdinal("Braker")));
CheckBox3.Checked = (reader.GetBoolean(reader.GetOrdinal("Access")));
CheckBox4.Checked = (reader.GetBoolean(reader.GetOrdinal("Conn_Net")));
CheckBox5.Checked = (reader.GetBoolean(reader.GetOrdinal("Log_Book")));
CheckBox6.Checked = (reader.GetBoolean(reader.GetOrdinal("Pictures")));
CheckBox8.Checked = (reader.GetBoolean(reader.GetOrdinal("Floor")));
CheckBox9.Checked = (reader.GetBoolean(reader.GetOrdinal("Cb_lenght")));
CheckBox10.Checked = (reader.GetBoolean(reader.GetOrdinal("Channel")));
}
reader.Close();
}
}
What am I missing to get the checkmark from the sql db? Below is how insert into sql:
private void SaveAuditChecklist()
{
if (auditChecklist != null)
{
SqlCommand cmd = null;
string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string queryString = #"INSERT INTO AUDITOR_CHECKLIST VALUES(" +
"#SiteID, #Mount, #Braker, #Access, #ConnNet, #LogBook, #Pictures, #Floor, #CbLenght, #Channel) ";
using (SqlConnection connection =
new SqlConnection(conn))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
cmd = new SqlCommand(queryString);
cmd.Connection = connection;
cmd.Parameters.Add(new SqlParameter(
"#SiteID", //the name of the parameter to map
System.Data.SqlDbType.NVarChar, //SqlDbType value
20, //The width of the parameter
"Site_ID")); //The name of the column source
//Fill the parameter with the value retrieved
//from the text field
cmd.Parameters["#SiteID"].Value = foo.Site_ID;
cmd.Parameters.Add(new SqlParameter("#Mount", SqlDbType.Bit));
cmd.Parameters["#Mount"].Value = CheckBox1.Checked;
cmd.Parameters.Add(new SqlParameter("#Braker", SqlDbType.Bit));
cmd.Parameters["#Braker"].Value = CheckBox2.Checked;
cmd.Parameters.Add(new SqlParameter("#Access", SqlDbType.Bit));
cmd.Parameters["#Access"].Value = CheckBox3.Checked;
cmd.Parameters.Add(new SqlParameter("#ConnNet", SqlDbType.Bit));
cmd.Parameters["#ConnNet"].Value = CheckBox4.Checked;
cmd.Parameters.Add(new SqlParameter("#LogBook", SqlDbType.Bit));
cmd.Parameters["#LogBook"].Value = CheckBox5.Checked;
cmd.Parameters.Add(new SqlParameter("#Pictures", SqlDbType.Bit));
cmd.Parameters["#Pictures"].Value = CheckBox6.Checked;
cmd.Parameters.Add(new SqlParameter("#Floor", SqlDbType.Bit));
cmd.Parameters["#Floor"].Value = CheckBox8.Checked;
cmd.Parameters.Add(new SqlParameter("#CbLenght", SqlDbType.Bit));
cmd.Parameters["#CbLenght"].Value = CheckBox9.Checked;
cmd.Parameters.Add(new SqlParameter("#Channel", SqlDbType.Bit));
cmd.Parameters["#Channel"].Value = CheckBox10.Checked;
cmd.ExecuteReader();
}
}
}
Booleans are stored as 1 or 0 in Sql Database, but the datareader do the conversion for you. Instead use:
var myBool = reader.GetBoolean(i);
Then just assign the value to the control's value property.
Finally got the reader they way it should work to get the checkmark values. I edited my question with the working code; however, below is what I added or changed for the reader:
while (reader.Read())
{
CheckBox1.Checked = (reader.GetBoolean(reader.GetOrdinal("Mount")));
CheckBox2.Checked = (reader.GetBoolean(reader.GetOrdinal("Braker")));
CheckBox3.Checked = (reader.GetBoolean(reader.GetOrdinal("Access")));
CheckBox4.Checked = (reader.GetBoolean(reader.GetOrdinal("Conn_Net")));
CheckBox5.Checked = (reader.GetBoolean(reader.GetOrdinal("Log_Book")));
CheckBox6.Checked = (reader.GetBoolean(reader.GetOrdinal("Pictures")));
CheckBox8.Checked = (reader.GetBoolean(reader.GetOrdinal("Floor")));
CheckBox9.Checked = (reader.GetBoolean(reader.GetOrdinal("Cb_lenght")));
CheckBox10.Checked = (reader.GetBoolean(reader.GetOrdinal("Channel")));
}

Categories