AutoComplete with MS Access database - c#

I want to make my txtSearch textbox in Visual Studio autocomplete.
I have searched around for a long time, for some explanations and tutorials,
but the most are about SQL databases. I have a MS Access database in my application.
I want to make autocomplete suggests from my Titel colon in my database (appData/Film)
First of all, can a textbox do the job, or is a rich textbox necessary to do the job?
I don't expect code from you, but maybe an explanation or a tutorial, you know somewhere?
Thanks. And oops. Important info: My application is based on C#, and coded in Visual Studio.

Try it this way.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;
namespace WinAutoComplete
{
public partial class Form1 : Form
{
AutoCompleteStringCollection ProductList = new
AutoCompleteStringCollection();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//declare connection string
string cnString = #"Data Source=EXCEL-PC\SQLEXPRESS; Initial Catalog=NORTHWND;" +
"Trusted_Connection = True";
/*use following if you use standard security
string cnString = #"Data Source=(local);Initial
Catalog=northwind; Integrated Security=SSPI"; */
//declare Connection, command and other related objects
SqlConnection conGetData = new SqlConnection(cnString);
SqlCommand cmdGetData = new SqlCommand();
SqlDataReader drGetData;
try
{
//open connection
conGetData.Open();
//prepare connection object to get the data through
//reader and populate into dataset
cmdGetData.CommandType = CommandType.Text;
cmdGetData.Connection = conGetData;
cmdGetData.CommandText = "Select ProductName From Products";
//read data from command object
drGetData = cmdGetData.ExecuteReader();
if (drGetData.HasRows == true)
{
while (drGetData.Read())
ProductList.Add(drGetData["ProductName"].ToString());
}
else
MessageBox.Show("No data found in Products tables");
//close reader and connection
drGetData.Close();
conGetData.Close();
//set the default pattern to SuggestAppend
//comboBoxPattern.SelectedIndex = 1;
txtProductID.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtProductID.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtProductID.AutoCompleteCustomSource = ProductList;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
//check if connection is still open then attempt to close it
if (conGetData.State == ConnectionState.Open)
{
conGetData.Close();
}
}
}
private void comboBoxPattern_SelectedIndexChanged(object sender, EventArgs e)
{
//switch (comboBoxPattern.Text)
//{
// case "Suggest":
// txtProductID.AutoCompleteMode = AutoCompleteMode.Suggest;
// break;
// case "Append":
// txtProductID.AutoCompleteMode = AutoCompleteMode.Append;
// break;
// case "SuggestAppend":
// txtProductID.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
// break;
//}
}
}
}
This definitely works, as you can see in the screen shot below.
Also, check this out when you have a chance.
https://www.connectionstrings.com/

Related

Is there a better way to connect my DB to my Form?

I'm trying to connect my DB to my ListView, and I'm trying to find a better way than what's in the book. I looked at a couple forums and a lot of them have the same thing like what's in my code down below.
We didn't have a lot of time to go over databases in class, so a lot of my knowledge with connection strings come from the internet and a small chapter in the book.My Database name is GameStoreLibrary.
using System.Data;
using System.Data.SqlServerCe;
public partial class DisplayGameStoreTable : Form
{
//WHAT THE C# FORUMS SAY TO DO
public SqlCeConnection cn = new SqlCeConnection(#"
Data Source=.;
Initial Catalog=DB GameStoreLibrary;
Integrated Security=True;
MultipleActiveResultSets=True");
private void DisplayGameStoreTable_Load(object sender, EventArgs e)
{
try
{
cn.Open();
}
catch(SqlCeException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
private void NewGameBttn_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM newGames ORDER BY gametitle ASC", cn);
try
{
SqlCeDataAdapter da = new SqlCeDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["gametitle"].ToString());
item.SubItems.Add(dr["releasedate"].ToString());
item.SubItems.Add(dr["console"].ToString());
item.SubItems.Add(dr["company"].ToString());
item.SubItems.Add(dr["gameprice"].ToString());
item.SubItems.Add(dr["quantity"].ToString());
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Small Tip :
Try to use a DBConnect class instead of typing connection string every single time and closing the connection.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace InventoryManagementSystem
{
class DBConnect : IDisposable
{
private static String connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Private\InventoryManagementSystem\InventoryManagementSystem\InventoryDB.mdf;Integrated Security=True";
public SqlConnection con = new SqlConnection(connectionString);
public DBConnect()
{
try
{
con.Open();
Console.WriteLine("Database connected");
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
Console.WriteLine("Database Connection Failed");
throw new Exception();
}
}
public void Dispose()
{
con.Close();
}
}
}
After you have this in your project you just have to create an object whenever you want to access the database.
public void getData(){
using(DBConnect db = new DBConnect()){
String q = "select * from TestTable";
SqlCommand cmd = new SqlCommand(q,db.con);
SqlDatareader r = cmd.ExcecuteReader();
}
}
This will automatically close the connections too.
To add on to Gihan's answer, it's also an accepted practice to create the App.Config file and put the connection string in there so it's not inside your source code. Then it's easier to change without recompiling anything.
Use the ConnectionStrings section of the App.Config and then you can get the connection string using the code:
System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

Set connection string using a combobox 'selected' item using C#

I am self-learning C# using Visual Studio 2012 and stuck on a connection problem. Basically, I want to use a combobox to connect to a database based on the users selection.
For example: When the user selects TEST1 this will select the test1 database and TEST2 will enable test2 database..etc
The code I have pieced together uses a button which displays the results from a SQL script through a messagebox. At the moment I cant get this to work as the message box does not display anything.
I commented out the MainConnection() as that was a test to see if the connection was working.
Appreciate if someone could point me in the right direction.
Please see the C# code below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace TestDB
{
public partial class Form1 : Form
{
class ComboItemExample
{
public string DisplayString { get; set; }
public string ConnectionString { get; set; }
public override string ToString() { return DisplayString; }
}
private string currentConnection = "Data Source= np-2 ;Initial Catalog= TESTDB Integrated Security=true";
public Form1()
{
InitializeComponent();
var firstConnection = new ComboItemExample { DisplayString = "Data Source= np-2 ;Initial Catalog= TESTDB1 Integrated Security=true" };
comboBox1.Items.Add("TEST1");
var secondConnection = new ComboItemExample { DisplayString = "Data Source= np-2 ;Initial Catalog= TESTDB2 Integrated Security=true" };
comboBox1.Items.Add("TEST2");
}
public void MainConnection()
{
//Make connection to np-2 TESTDB
//string str = "Data Source= np-hums12 ;Initial Catalog= TESTDB;"
//+ "Integrated Security=true";
// ReadOrderData(str);
}
public static void ReadOrderData(string currentConnection)
{
// Run SQL script
string queryString = "SELECT *;";
using (SqlConnection connection = new SqlConnection(currentConnection))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
}
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// call read before accessing data.
while (reader.Read())
{
//display script in message box
MessageBox.Show(reader.GetValue(1).ToString());
}
// close when finished reading.
reader.Close();
}
}
private void CloseUI_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void ShowData_Click(object sender, EventArgs e)
{
MainConnection();
}
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex <= 0) return;
var newConnection = ((ComboItemExample)comboBox1.Items[comboBox1.SelectedIndex]).ConnectionString;
// use "newConnection" as connection string.
currentConnection = newConnection;
using (var connection = new SqlConnection(currentConnection))
{
}
}
}
}
It looks like you're just adding the text value to your comboboxes, but not actually tying the connection string to it. You may be inadvertently passing the values "TEST1" and "TEST2" as connection strings. You should be adding the new variables you're creating in your constructor as the new items, not those strings. Use the Add() that takes an Item as a parameter.
mycombobox.Add(new Item("Test1", firstConnection));
Assuming your connection strings are correct and functioning, the reason it is displaying nothing is because it is throwing an error with your SQL.
This line is where your mistake lies
string queryString = "SELECT *;";
It is not a valid SQL query, you need to also specify a table. To help in the future, its is often wise to use try-catch statements to help identify potential errors.
For example in your code you could use
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
MessageBox.Show(reader.GetValue(1).ToString());
}
//dont need to close the reader as the using statement will dispose of it once finished anyway
}
connection.Close();
}
catch (Exception ex)
{
connection.Close();
Console.WriteLine(ex.Message);
//or, depending on the package Debug.WriteLine(ex.Message);
}
}
This will print out the exception and stop your program locking up too. As it stands, your current one won't throw an error saying nothing was found, but it will throw an SQL exception in the output log but won't give you details. Exeception.Message will give you details, or SqlException.Message can provide SQL related messages.
Edit: In response to the comment you posted (and something I missed previously)
Looking at the way you have added your ComboBox items, you haven't even added the objects that you think you have. From your code, your combobox items will be "TEST1" and "TEST2" - not the connection strings.
Instead, you could add your objects to the box like so
comboBox1.Items.Add(new ComboItemExample() {DisplayString ="TEST1",ConnectionString = "Data Source= np-2 ;Initial Catalog= TESTDB1 Integrated Security=true"});
comboBox1.Items.Add(new ComboItemExample() {DisplayString ="TEST2",ConnectionString = "Data Source= np-2 ;Initial Catalog= TESTDB2 Integrated Security=true"});
comboBox1.DisplayMember = "DisplayString";
comboBox1.ValueMember = "ConnectionString";
Then to retrieve the value from the combobox for your query
string myConnectionVal = comboBox1.SelectedValue.ToString();
The reason you are getting the cast error is because you never assigned the ComboItemExample to the combobox in the first place. With the item adding code above you would be able to do this in the future, but if all you need is a single value from the object, ValueMember is easier to use.

Datagridview cell value change update database

I have retrieved data from Mysql database into a DataGridView1. Let us suppose I am in Row 0. When I change the contents of Row 0, Cell 1 and press enter key or a button, the Update query should modify that row, but I am unable to modify the value of the cell. The cell maintains its previous value when i reload data and the database is not modified. For example, if I change the contents of a cell under column Client_Name from "Acs" to "Gmt", how can I change the value of the cell from "Acs" to "Gmt"? and to have it updated into Mysql database, I am using c# in Vs 2012. below is my code that retrieves my database into datagridview1 any help is welcomed thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Data.SqlClient;
namespace PI.Gen
{
public partial class frmMain : Form
{
MySqlConnection Conn;
public frmMain()
{
InitializeComponent();
btnDisconnect.Enabled = true;
btnLoadData.Enabled = false;
btnLoadClients.Enabled = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
string strConnect = "server=" + txtServer.Text + ";uid=" + txtUsername.Text + ";pwd=" + txtPassword.Text + ";database=" + txtDatabase.Text;
try
{
if (txtServer.TextLength <= 0 || txtUsername.TextLength <= 0 || txtDatabase.TextLength <= 0)
{
MessageBox.Show("You have an empty database connection field. Please supply a valid value.");
return;
}
Conn = new MySqlConnection(strConnect);
Conn.Open();
if (Conn.State.ToString() != "Open")
{
MessageBox.Show("Could not open database connection");
return;
}
btnDisconnect.Enabled = true;
btnConnect.Enabled = false;
btnLoadData.Enabled = true;
btnLoadClients.Enabled = true;
// btnSubmitClient.Enabled = true;
}
catch (Exception ex) // catch on general exceptions, not specific
{
MessageBox.Show(ex.Message);
return;
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (Conn != null)
{
Conn.Close();
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
try
{
Conn.Close();
Conn = null;
btnDisconnect.Enabled = false;
btnConnect.Enabled = true;
btnLoadData.Enabled = false;
btnLoadClients.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void btnLoadData_Click(object sender, EventArgs e)
{
try
{
string CmdString = "SELECT * FROM t_receipients";
MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void btnLoadClients_Click(object sender, EventArgs e)
{
try
{
string CmdString = "SELECT * FROM t_clients";
MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
After series of trials and error, i finally found what i was looking for, thus being able to update database from datagridview below is my worked around code which works 100% hope it helps someone in future, and thanks #RageComplex for helping out, but one more thing does anyone know how to implement that i mean instead of hitting the enter button to take changes in the datagridview you rather click on a button ty
private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
{
try
{
DataTable changes = ((DataTable)dataGridView1.DataSource).GetChanges();
if (changes != null)
{
MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
mySqlDataAdapter.Update(changes);
((DataTable)dataGridView1.DataSource).AcceptChanges();
MessageBox.Show("Cell Updated");
return;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You are not updateing your changes to the database. While you keep your connection open doesn't mean that this will automatically update your data.
First of all, don't keep your connection open. In your app you have a connect button which is good for testing but not for really keeping the connection open, not with databases in my opinion.
The way you load data is correct.
You give the datagridview an DataSource which is a table from your DataSet. So changes made in the datagridview ARE saved to your DataSet but not to your database.
This is how you update your database
public void UpdateTable(DataSet ds)
{
using (MySqlConnection connect = new MySqlConnection(ConnString))
{
connect.Open();
MySqlDataAdapter adapt = new MySqlDataAdapter();
MySqlCommandBuilder commbuilder = new MySqlCommandBuilder(adapt);
adapt.SelectCommand = new MySqlCommand("SELECT * FROM t_receipients", connect);
adapt.Update(ds.Tables[0]);
}
}
Make sure, before you Update your database, you use datagridview1.EndEdit()
Also, you using, this will ensure a connection is closed again after completing that code, best is to always have it in a try-except.
You had struggles with connecting the database as it appears to be in the commends.
I've also forgot to include MySqlDataAdapter above, I used an adapter globally in that case.
I didn't want to report this question as duplicated, but now it kinda does look like this answer.
I would like to give code which I have tested in my application.I used it for button click event.
private void button3_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
string MyConnection2 = "server=localhost;user id=root;password=;database=k";
using (MySqlConnection conn = new MySqlConnection(MyConnection2))
{
using (MySqlCommand comm = new MySqlCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
StrQuery = #"update s set Quantity='" + dataGridView3.Rows[i].Cells["Quantity"].Value.ToString() + "' where No='" + dataGridView3.Rows[i].Cells["Item No"].Value.ToString() + "';";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch
{
}
}
I think it may help you

SQL to Arduino via C♯

As part of a project I'm putting together, I have an Arduino updating a MySQL database via C♯ and, in another location I have another C♯ program doing a simple SELECT query on the database, and communicating its findings to another Arduino via Serial. I have written most of the code for this second program but am having some annoying issues at the end of it all.
Below is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Xml;
using System.IO.Ports;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string hkday;
string hkall;
//SERIAL
SerialPort serialPort1 = new SerialPort();
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.NewLine = "\n";
//OPEN SERIAL
serialPort1.Open();
//SQL
string connString = "Server=xxxx;Uid=xxxx;Password=xxxx;Port=xxxx;Database=xxxx;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command1 = conn.CreateCommand();
command1.CommandText = "Select USERS from HK where UPTIME='HKDAY'";
MySqlCommand command2 = conn.CreateCommand();
command2.CommandText = "Select USERS from HK where UPTIME='HKALL'";
//EXECUTE QUERIES
if (_continue = true)
{
conn.Open(); //Connect
MySqlDataReader reader1 = command1.ExecuteReader();
while (reader1.Read())
{
//Write to value and string
Console.WriteLine(reader1["USERS"].ToString());
hkday = reader1["USERS"].ToString();
}
Console.ReadLine();
_continue = false;
conn.Close(); //Disconnect
}
else
{
conn.Open(); //Connect
MySqlDataReader reader2 = command1.ExecuteReader();
while (reader2.Read())
{
//Write to console and string
Console.WriteLine(reader2["USERS"].ToString());
}
hkall = reader2["USERS"].ToString();
Console.ReadLine();
_continue = true;
conn.Close(); //Disconnect
//WRITE STRINGS TO SERIAL
serialPort1.WriteLine(
String.Format(hkday, hkall));
}
serialPort1.Close();
}
public static bool _continue { get; set; }
}
}
I can't work out how my section titled WRITE STRINGS TO SERIAL needs to be syntaxed and placed within the code to be able to reference both 'hkday' and 'hkall'
My 'if (_continue = true)' flag doesn't seem to work, and I'm not sure why.
I think that if these two issues are solved, the program ought to work, can you see any other glaring issues?
Thank you, I know these are only tiny issues, but I can't seem to work them out.
Potentially important: I'm trying to get the output as '123,456\n' as my arduino program already recognises this as its input.
UPDATE
Having received the answers I have, I have compounded this project with the other one I'm currently doing to try and have an arduino update a MySQL database via C# and then also have it download the table's data that it isn't updating to display out through another arduino.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using MySql.Data.MySqlClient;
namespace SQL_Scraper
{
public partial class Sandro : Form
{
//Serial Settings
SerialPort UNO = new SerialPort("COM4", 9600);
SerialPort MEGA = new SerialPort("COM3", 9600);
//Incoming Data String
string RxString;
//Int for download
int? vnday = 0;
int? vnall = 0;
public Sandro()
{
InitializeComponent();
//Open UNO port
UNO.Open();
//Open MEGA Port
MEGA.Open();
}
private void MEGA_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
}
private void Sandro_FormClosing(object sender, FormClosingEventArgs e)
{
if (UNO.IsOpen | MEGA.IsOpen)
{
UNO.Close();
MEGA.Close();
}
}
private void DisplayText(object sender, EventArgs e)
{
}
private void Begin_Click(object sender, EventArgs e)
{
//Turn off start button
Begin.Enabled = false;
//?
this.Invoke(new EventHandler(DisplayText));
//Create Event Handler if data is receiverd
MEGA.DataReceived += new SerialDataReceivedEventHandler(MEGA_DataReceived);
string SQLString = "Server=benchmarkcount.db.9506323.hostedresource.com;Uid=benchmarkcount;Password=Watercress2428;Port=3306;Database=benchmarkcount;";
MySqlConnection SQLConnection = new MySqlConnection(SQLString);
//Receive data
RxString = MEGA.ReadExisting();
//Append Serial Input to Output box)
outputBox.AppendText(RxString);
//Get Unsaved input from text box
string input = outputBox.Text;
string[] inputLines = input.Split('\n');
//Upload findings from MEGA to SQL
foreach (string line in inputLines)
{
if (line.EndsWith("\r")) //Makes sure line is complete
{
if (line.StartsWith("Today's total users: "))
{
string dayUsers = line.Substring(20).Trim();
MySqlCommand UpdateHKDAY = SQLConnection.CreateCommand();
UpdateHKDAY.Parameters.AddWithValue("param1", dayUsers);
UpdateHKDAY.CommandText = "UPDATE HK SET USERS=?param1 WHERE UPTIME='HKDAY'";
SQLConnection.Open();
UpdateHKDAY.ExecuteNonQuery();
SQLConnection.Close();
}
else if (line.StartsWith("All-time total users: "))
{
string allUsers = line.Substring(21).Trim();
MySqlCommand UpdateHKALL = SQLConnection.CreateCommand();
UpdateHKALL.Parameters.AddWithValue("param2", allUsers);
UpdateHKALL.CommandText = "UPDATE HK SET USERS=?param2 WHERE UPTIME='HKALL'";
SQLConnection.Open();
UpdateHKALL.ExecuteNonQuery();
SQLConnection.Close();
}
}
}
//Only keep unparsed text in text box
outputBox.Text = inputLines[inputLines.Length - 1];
//Download Numbers Query
MySqlCommand DownUsers = new MySqlCommand("Select USERS, UPTIME from VN where UPTIME IN ('VNDAY', 'VNALL')", SQLConnection);
//Open Connection
SQLConnection.Open();
//Execute Downloading Numbers
MySqlDataReader theResults = DownUsers.ExecuteReader();
while (theResults.Read())
{
switch (theResults["UPTIME"] as string)
{
case "VNDAY":
vnday = theResults["USERS"] as int?;
break;
case "VNALL":
vnall = theResults["USERS"] as int?;
break;
}
}
//Do things with the results
UNO.WriteLine(String.Format("{0},{1}", vnday, vnall));
Console.WriteLine(String.Format("{0},{1}", vnday, vnall));
//Close Connection
SQLConnection.Close();
}
private void Sandro_Load(object sender, EventArgs e)
{
}
private void Cease_Click(object sender, EventArgs e)
{
Begin.Enabled = true;
Cease.Enabled = false;
}
}
}
However, I would like to be able to check this data - the data being sent to the arduino - in my inputBox to make sure it's in the format "vnday, vnall\n"
Your question and example has too many contradictions. It appears that you are under impression that there is static persistence between separate app runs. There isn't. All your static variables will be cleared with each run. It would be different if you had a method that you called in a loop inside the same app domain.
Also, judging by your variable names and your output requirement, the USERS field is a numeric.
So, assuming you have following table:
USERS UPTIME
------ ------
123456 HKALL
234567 HKDAY
following code:
public static void Main()
{
int? hkday = 0;
int? hkall = 0;
using (MySqlConnection conn = new MySqlConnection("..."))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("Select USERS, UPTIME from HK where UPTIME IN ('HKDAY', 'HKALL')", conn);
MySqlDataReader reader = cmd.ExecuteReader();
//this assumes that there is only one record per 'HKDAY' and 'HKALL',
//otherwise the last value will be stored
while (reader.Read())
{
switch (reader["UPTIME"] as string)
{
case "HKDAY":
hkday = reader["USERS"] as int?;
break;
case "HKALL":
hkall = reader["USERS"] as int?;
break;
}
}
}
Console.WriteLine(String.Format("{0:N0}\n{1:N0}\n", hkday, hkall));
}
will output:
234,567
123,456
Or if you desire to run independent queries:
private static int? GetUSERS(string hkval)
{
using (MySqlConnection conn = new MySqlConnection("..."))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("Select USERS from HK where UPTIME=#hkval", conn);
cmd.Parameters.AddWithValue("hkval", hkval);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
return reader["USERS"] as int?;
return null;
}
}
public static void Main()
{
int hkday = (int)GetUSERS("HKDAY");
int hkall = (int)GetUSERS("HKALL");
Console.WriteLine(String.Format("{0:N0}\n{1:N0}\n", hkday, hkall));
}
You could also pass HKDAY/HKALL as a parameter to you app using args.
I'm not a C programmer but know a lot of serial ports, I suppouse that this solves your first issue.
//WRITE STRINGS TO SERIAL
serialPort1.Write(hkday); // do not append line feed
serialPort1.WriteLine(hkall); // append line feed

An unhandled exception of type 'System.StackOverflowException' occurred in GUI_Login.DLL

I am changing a console app login over to a web based application and recieve the following error about an Unhandled exception.
In the console app I have the following line of code which resides in the StoredProcDemo class:
StoredProcDemo spd = new StoredProcDemo();
In the Web Application I have:
Login spd = new Login();
I am not sure what to change it over to. Could someone shed some insight thanks and maybe why? Thanks so much.
Here is the full code if needed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data.SqlTypes;
namespace GUI_Login
{
public partial class Login : System.Web.UI.Page
{
SqlConnection conn = null;
SqlParameter parmReturnValue;
Login spd = new Login();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
RunStoredProcParams();
}
public void RunStoredProcParams()
{
//run simple stored procure
spd.RunStoredProcParams();
int Result;
Result = -1;
conn = conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\UserDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True; Integrated Security=SSPI");
conn.Open();
try
{
//create and open a connection object
conn = conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\UserDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True; Integrated Security=SSPI");
conn.Open();
//Create the command object indentifying the stored procedure
SqlCommand cmd = new SqlCommand("PassParamUserID", conn);
//set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#FirstName", txtUserName.Text));
parmReturnValue = cmd.Parameters.AddWithValue("#UserId", SqlDbType.Int);
parmReturnValue.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
Result = Convert.ToInt32(cmd.Parameters["#UserId"].Value);
conn.Close();
// lblResult.Text = Result;
if (Result > 0)
{
lblResult.Text = ("User does exist in database");
}
else if (Result < 0)
{
lblResult.Text = ("Denied, try another user name");
}
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
Even ignoring RunStoredProcParams you'll get a stack overflow as soon as you try to create a new instance:
public partial class Login : System.Web.UI.Page
{
// Removed extraneous stuff...
Login spd = new Login();
}
Why do you want every instance of Login to have a reference to another instance of Login, which it creates immediately?
Basically the constructor is going to be called recursively until it goes bang.
What are you trying to do here, and why? In the console app you may well be creating an instance of StoredProcDemo, but I'm sure it wouldn't be within StoredProcDemo itself (as an instance variable initializer). Perhaps it's in Program or something similar? That would make more sense.
You run RunStoredProcParams() recursively indefinitely.
Comment out this line:
spd.RunStoredProcParams();
Also comment this one:
Login spd = new Login();

Categories

Resources