Issues with autofilling checkboxes - c#

Could I use a read only collection here and drop the dataset? I am new to C# and I am stumped at how to do this. I have a dropdown-box that is being filled from a column in SQL that holds client names. I have a text-box that you enter an email address into that will update the email address in SQL with the values checked in the dropdown-box. Now when the email is entered into the textbox is there a way I can pull these saved values from SQL and have the checkboxes "auto" checked based on what is already in the table for the corresponding email? I have seen this done with coded values but not values from SQL. Also if an email has access to more than 1 client, the client names are pipe delimited when inserted into SQL.
Here Is what I have so far.
if (EmailList.Value == "") Connection ls = new Connection(); Recordset rs = new Recordset();
ls.Open(connections.myconn);
rs.Open("select email from users order by email", ls);
string emails = "";
while (!rs.EOF) { emails += rs.Fields[0].Value + " "; rs.MoveNext(); }
EmailList.Value = emails;
using (SqlCommand cmd1 = new SqlCommand("SELECT * FROM tracking_mpc order by ClientName"))
{
cmd1.CommandType = CommandType.Text;
cmd1.Connection = con1;
con1.Open();
webreport.DataSource = cmd1.ExecuteReader();
webreport.DataTextField = "ClientName";
webreport.DataValueField = "CltID";
webreport.DataBind();
con1.Close();
}
public string StringFromDatabase()
{
try
{
var dataSet = new DataSet();
string constr=ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection myConnect = new SqlConnection(constr))
myConnect.Open();
var command = new SqlCommand("SELECT Clients from users WHERE Email =" + EmailTextBox.Text)
{
CommandType = CommandType.StoredProcedure
};
var dataAdapter = new SqlDataAdapter { SelectCommand = command };
dataAdapter.Fill(dataSet);
return dataSet.Tables[0].Rows[0]["Clients"].ToString();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}

Here is a better implementation of your StringFromDatabase:
public List<string> GetClientNames(string email)
{
var constr=ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
var sql = "SELECT Clients FROM users WHERE Email=#email";
using (var conn = new SqlConnection(constr))
using (var cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#email",SqlDbType.VarChar).Value = email;
conn.Open();
return ((string)cmd.ExecuteScalar()).Split('|').ToList();
}
}
Here is the same, but in a database agnostic way (works if you change your connection string to say MySql, Oracle, etc):
public List<string> GetClientNames(string email)
{
var constr = ConfigurationManager.ConnectionStrings["myConnectionString"];
var sql = "SELECT Clients FROM users WHERE Email=#email";
var factory = DbProviderFactories.GetFactory(constr.ProviderName);
using (var conn = factory.CreateConnection())
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
conn.ConnectionString = constr.ConnectionString;
var param = cmd.CreateParameter();
param.ParameterName = "#email";
param.Value = email;
cmd.Parameters.Add(param);
conn.Open();
return ((string)cmd.ExecuteScalar()).Split('|').ToList();
}
}

Related

How to store multiple SQL data columns into different variables C#

I am trying to store sql data that I have for a voucher id and voucher amount into a variable and display it into a label on a click of a button.
protected void Button1_Click(object sender, EventArgs e)
{
string voucherId = String.Empty;
string voucherAmount = String.Empty;
string queryVoucherId = "select voucherid from ReturnForm where email = '" + Session["username"] + "';";
string queryVoucherAmount = "select voucheramount from ReturnForm where email = '" + Session["username"] + "';";
int index = 0;
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherId, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherId = reader[index].ToString();
index++;
}
}
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherAmount, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherAmount = reader[index].ToString();
index++;
}
}
if (txtVoucher.Text == voucherId)
{
Label3.Visible = true;
Label3.Text = voucherAmount;
}
}
When I click the button its giving me an error saying that the index is out of bounds.
Building on #JSGarcia's answer - but using parameters as one ALWAYS should - you'd get this code:
string email = Session['username'];
string query = $"SELECT voucherid, voucheramount FROM ReturnFrom WHERE Email = #email";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
// set the parameter before opening connection
// this also defines the type and length of parameter - just a guess here, might need to change this
cmd.Parameters.Add("#email", SqlDbType.VarChar, 100).Value = email;
conn.Open();
sda.Fill(dt);
conn.Close();
}
Personally, I'd rather use a data class like
public class VoucherData
{
public int Id { get; set; }
public Decimal Amount { get; set; }
}
and then get back a List<VoucherData> from your SQL query (using e.g. Dapper):
string query = $"SELECT Id, Amount FROM ReturnFrom WHERE Email = #email";
List<VoucherData> vouchers = conn.Query<VoucherData>(query).ToList();
I'd try to avoid the rather clunky and not very easy to use DataTable construct...
I strongly recommend combining your sql queries into a single one, write it into a datatable and continue your logic from there. IMHO it is much cleaner code:
string email = Session['username'];
string query = $"SELECT voucherid, voucheramount FROM ReturnFrom where Email = '{email}'";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = conn.CreateCommand())
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
conn.Open();
sda.Fill(dt);
conn.Close();
}
// Work with DataTable dt from here on
...
Well, one more big tip?
You ONLY as a general rule need a dataadaptor if you going to update the data table.
And you ONLY need a new connection object if you say not using the sql command object.
The sqlcommand object has:
a connection object - no need to create a separate one
a reader - no need to create a separate one.
Note how I did NOT create a seperate connection object, but used the one built into the command object.
And since the parameter is the SAME in both cases? Then why not re-use that too!!
So, we get this:
void TestFun2()
{
String str = "some conneciton???";
DataTable rstVouch = new DataTable();
using (SqlCommand cmdSQL =
new SqlCommand("select voucherid from ReturnForm where email = #email",
new SqlConnection(str)))
{
cmdSQL.Parameters.Add("#email", SqlDbType.NVarChar).Value = Session["username"];
cmdSQL.Connection.Open();
rstVouch.Load(cmdSQL.ExecuteReader());
// now get vouch amount
cmdSQL.CommandText = "select voucheramount from ReturnForm where email = #email";
DataTable rstVouchAmount = new DataTable();
rstVouchAmount.Load(cmdSQL.ExecuteReader());
if (rstVouch.Rows[0]["vourcherid"].ToString() == txtVoucher.Text)
{
Label3.Visible = true;
Label3.Text = rstVouchAmount.Rows[0]["voucheramount"].ToString();
}
}
}

Fetching Data from MySQL and Inserting it in MS SQL SERVER in visual studio c#

Am trying to read a table from a Mysql database and store all of it in a ms sql server in c# am reading from mysql correctly my problem is how to store the data i read in ms sql in the second part of code
string constring= ConfigurationManager.ConnectionStrings["cnxMysql"].ConnectionString;
MySqlConnection conn = new MySqlConnection(constring);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM i_evt WHERE Updt=0",conn);
conn.Open();
cmd.ExecuteNonQuery();
string constring2 = ConfigurationManager.ConnectionStrings["cnxsql"].ConnectionString;
SqlConnection conn2 = new SqlConnection(constring2);
SqlCommand cmd2 = new SqlCommand("INSERT INTO i_evt",conn2);
conn2.Open();
cmd2.ExecuteNonQuery();
conn2.Close();
conn.Close();
I have a reverse issue, I have to transfer data from MS SQL Server to MySQL.
I have used below snippet for this, but I personally don't recommend this for production as it adds data one by one row. But you can use it for a small dataset or local environment. You can add a try-catch as well as customize as per your need. This is for just reference.
public void Main()
{
var table = GetDataTableFromSQLServer();
AddToMySQL(table);
}
private DataTable GetDataTableFromSQLServer()
{
var connection = GetSqlServerConnection();
string query = "SELECT Column1, Column2 FROM TableName WHERE Column3 is NOT NULL";
var command = new SqlCommand(query, connection);
connection.Open();
var reader = command.ExecuteReader();
DataTable table = new DataTable();
table.Load(reader);
connection.Close();
return table;
}
private void AddToMySQL(DataTable table)
{
var connection = GetMySQLConnection();
connection.Open();
string query = "INSERT INTO TableName (column1, column2) VALUES(#column1, #column2);";
int i = 0;
foreach (DataRow row in table.Rows)
{
if (i % 1000 == 0)
{
// Closing & Reopening connection after 1000 records
connection.Close();
connection.Open();
}
Console.WriteLine($"Adding ({++i}/{table.Rows.Count})");
MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.Add(new MySqlParameter("#column1", MySqlDbType.Int64) { Value = row.Field<long>("column1").Trim() });
command.Parameters.Add(new MySqlParameter("#column2", MySqlDbType.VarChar) { Value = row.Field<string>("column2").Trim() });
var affectedRows = command.ExecuteNonQuery();
}
connection.Close();
}
private SqlConnection GetSqlServerConnection()
{
string connectionString = #"Data Source=...";
SqlConnection connection = new SqlConnection(connectionString);
return connection;
}
private MySqlConnection GetMySQLConnection()
{
MySqlConnectionStringBuilder connectionBuilder = new MySqlConnectionStringBuilder
{
Server = "...",
Database = "...",
UserID = "...",
Password = "...",
Port = 3306
};
MySqlConnection connection = new MySqlConnection(connectionBuilder.ToString());
return connection;
}
Refer below code, you can optimize this code as there is alot of space for optimization but this is simple for beginner to understand basic level:
MySqlConnection conn = new MySqlConnection(constring);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM i_evt WHERE Updt=0", conn);
conn.Open();
DataSet data;
using (MySqlDataAdapter sqlAdapter = new MySqlDataAdapter(mySqlCommand))
{
data = new DataSet();
sqlAdapter.Fill(data);
}
string constring2 = ConfigurationManager.ConnectionStrings["cnxsql"].ConnectionString;
SqlConnection conn2 = new SqlConnection(constring2);
conn2.Open();
for (int i = 0; i < data.Tables[0].Rows.Count; i++)
{
SqlCommand cmd2 = new SqlCommand("INSERT INTO i_evt(column1,column2) values(#col1,#col1)", conn2);
cmd2.Parameters.AddWithValue("col1", data.Tables[0].Rows[i][0].ToString());
cmd2.Parameters.AddWithValue("col12", data.Tables[0].Rows[i][1].ToString());
cmd2.ExecuteNonQuery();
}
conn2.Close();
conn.Close();

Object reference is not set to an instance Access query C#

I'm trying to make a query into the Clients table, when the user enters a mobile number, the code checks if it matches any record, if it does, it returns the client's Name & Address into text boxes, but I'm getting this error "Object reference is not set to an instance of an object" by the time I enter anything into that textbox
here is the code, what could be the problem?
private void textBox11_TextChanged(object sender, EventArgs e)
{
clientsearch();
clientsearch2();
}
public void clientsearch()
{
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"select Cname From Clients where Cmobile = #mobile";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, conn);
cmd.Parameters.Add("#mobile", System.Data.OleDb.OleDbType.Integer).Value = textBox11.Text;
cmd.ExecuteNonQuery();
string result = cmd.ExecuteScalar().ToString();
textBox12.Text = #result;
}
}
public void clientsearch2()
{
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"select Caddress From Clients where Cmobile = #mobile";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, conn);
cmd.Parameters.Add("#mobile", System.Data.OleDb.OleDbType.Integer).Value = textBox11.Text;
cmd.ExecuteNonQuery();
string result = cmd.ExecuteScalar().ToString();
textBox13.Text = #result;
}
}
string result = cmd.ExecuteScalar().ToString();
textBox12.Text = #result;
#result isn't anything. You just want result. Additionally, sending separate queries to the server for this data is pointlessly inefficient. Do this instead:
public void clientsearch()
{
string query = #"select Cname, Caddress From Clients where Cmobile LIKE #mobile + '*'";
using (var conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
using (var cmd = System.Data.OleDb.OleDbCommand(query, conn))
{
cmd.Parameters.Add("#mobile", System.Data.OleDb.OleDbType.Integer).Value = textBox11.Text;
conn.Open();
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
textBox12.Text = rdr["Cname"].ToString();
textBox13.Text = rdr["Caddress"].ToString();
}
rdr.Close();
}
}
}
Finally, it's better style to also abstract your database code away from user interface. Ideally you would return a Client class, but since I don't see one I'll show an example using a tuple instead:
public Tuple<string, string> FindClientByMobile(string mobile)
{
string query = #"SELECT Cname, Caddress FROM Clients WHERE Cmobile LIKE #mobile + '*'";
using (var conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
using (var cmd = System.Data.OleDb.OleDbCommand(query, conn))
{
cmd.Parameters.Add("#mobile", System.Data.OleDb.OleDbType.Integer).Value = mobile;
conn.Open();
using (var rdr = cmd.ExecuteReader())
{
rdr.Read();
return Tuple<string, string>.Create(rdr["Cname"].ToString(), rdr["Caddress"].ToString());
}
}
}
If you're playing with a Visual Studio 2017 release candidate, you can also use the new Tuple shortcuts:
public (string, string) FindClientByMobile(string mobile)
{
string query = #"SELECT Cname, Caddress FROM Clients WHERE Cmobile LIKE #mobile + '*'";
using (var conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
using (var cmd = System.Data.OleDb.OleDbCommand(query, conn))
{
cmd.Parameters.Add("#mobile", System.Data.OleDb.OleDbType.Integer).Value = mobile;
conn.Open();
using (var rdr = cmd.ExecuteReader())
{
rdr.Read();
return (rdr["Cname"].ToString(), rdr["Caddress"].ToString());
}
}
}
And then use them like this:
private void textBox11_TextChanged(object sender, EventArgs e)
{
var result = FindClientByMobile(textBox11.Text);
textBox12.Text = result.Item1;
textBox13.Text = result.Item2;
}

SQLite Database is not open Error

I have a constructor that takes data from a SQL Server database and puts it in a local SQLite database:
public ForemanController()
{
connectionString.DataSource = "dxdb02v";
connectionString.InitialCatalog = "QTRAX4619410";
connectionString.UserID = "tunnelld";
connectionString.Password = "david";
string queryString = "SELECT * FROM [QTRAXAdmin].[vwQT_Foreman]";
List<Foreman> list;
// Creates a SQL connection
using (var connection = new SqlConnection(connectionString.ToString()))
{
using (var command = new SqlCommand(queryString, connection))
{
connection.Open();
using (var reader = command.ExecuteReader())
{
list = new List<Foreman>();
while (reader.Read())
{
list.Add(new Foreman { ForeBadge = reader.GetString(0), ForeName = reader.GetString(1) });
}
}
}
connection.Close();
allForeman = list.ToArray();
}
string deleteSQL = "DELETE FROM Foreman;";
using (SQLiteConnection SQLconn1 = new SQLiteConnection(SQLiteConnectionString))
{
using (var command = new SQLiteCommand(deleteSQL, SQLconn1))
{
command.Connection.Open();
command.ExecuteNonQuery();
}
}
using (SQLiteConnection SQLconn2 = new SQLiteConnection(SQLiteConnectionString))
{
SQLiteCommand cmd2 = SQLconn2.CreateCommand();
foreach (Foreman row in allForeman)
{
cmd2.CommandText = "INSERT INTO Foreman (ForeBadge, ForeName) VALUES (#param1, #param2);";
cmd2.Parameters.Add(new SQLiteParameter("#param1", row.ForeBadge));
cmd2.Parameters.Add(new SQLiteParameter("#param2", row.ForeName));
cmd2.ExecuteNonQuery();
}
}
}
Everything seems to be working fine until the last using statement:
using (SQLiteConnection SQLconn2 = new SQLiteConnection(SQLiteConnectionString))
{
SQLiteCommand cmd2 = SQLconn2.CreateCommand();
foreach (Foreman row in allForeman)
{
cmd2.CommandText = "INSERT INTO Foreman (ForeBadge, ForeName) VALUES (#param1, #param2);";
cmd2.Parameters.Add(new SQLiteParameter("#param1", row.ForeBadge));
cmd2.Parameters.Add(new SQLiteParameter("#param2", row.ForeName));
cmd2.ExecuteNonQuery();
}
}
I'm getting this error:
That's because that's the only place you forgot to open the connection.
add this: SQLconn2.Open();
You forgot to open the connection.
SQLConn2.Open();

C# MySql Storing multiple database rows in C#

I'm struggling a bit with this. I want to get the list of ids from the database where a certain value is equal to a certain value in the row. This call will likely return multiple ids. I want to store the value in the ids returned in a list or arraylist in the c# code but I am finding this troublesome. I have the code up to here:
string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection = new MySqlConnection(strConnection);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader reader;
command.CommandText = "SELECT idprojects FROM `test`.`projects` WHERE application_layers = " + applicationTiers + "";
connection.Open();
reader = command.ExecuteReader();
Any help would be much appreciated
string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection = new MySqlConnection(strConnection);
List<string> array = new List<string>();
using (MySqlCommand cmd = new MySqlCommand("SELECT idprojects FROM `test`.`projects` WHERE application_layers = " + applicationTiers, connection))
{
try
{
using (MySqlDataReader Reader = cmd.ExecuteReader())
{
while (Reader.Read())
{
array.Add(Reader["idprojects"].ToString());
}
}
}
catch (Exception ex)
{
throw;
}
}
string[] ret= array.ToArray();

Categories

Resources