inserting connection of DB to Every other forms inside the functions - c#

namespace PCJ_System
{
class DB_CONNECTION
{
public SqlConnection getConnection()
{
SqlConnection conn = null; ;
try
{
conn = new SqlConnection("data source= DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ; Integrated Security=True;");
conn.Open();
}
catch (Exception ex)
{
MessageBox.Show("Can't Open Connection !" + ex);
}
return conn;
}
}
}
This is my forms code: public partial class Form1 : this below code is working but i typing the sqlconnection again. which should be wrong way of coding.
namespace PCJ_System
{
public partial class Form1 : Form
{
SqlConnection conn;
SqlCommand cmd;
// SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "server = DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ; Integrated Security=True;";/again and again i am calling the=is to every other forms is it the correct way /
SqlConnection conn = new SqlConnection(str);
// DB_CONNECTION x = new DB_CONNECTION();
conn.Open();
string GetData = "Select [FC_Rate] from Forcur where FC_TYPE ='" + comboBox1.Text + "' ";
cmd = new SqlCommand(GetData, conn);
var returnValue = cmd.ExecuteScalar();
textBox1.Text = returnValue.ToString();
conn.Close();
}
}
}
How can I call the my Dbconnection to every single function.
Please help.

Replace your Code:
string str = "server = DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ;Integrated Security=True;";
/again and again i am calling the=is to every other forms is it the correct way /
SqlConnection conn = new SqlConnection(str);
// DB_CONNECTION x = new DB_CONNECTION();
conn.Open();
With the following:
DB_CONNECTION x = new DB_CONNECTION();
SqlConnection conn = x.getConnection();

One way that you could do to avoid repeating your code is create BaseForm and put you general codes in it then All your forms should Inherit BaseForm
public abstract class BaseForm:Form{
public SqlConnection getConnection()
{
SqlConnection conn = null; ;
try
{
conn = new SqlConnection("data source= DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ; Integrated Security=True;");
conn.Open();
}
catch (Exception ex)
{
MessageBox.Show("Can't Open Connection !" + ex);
}
return conn;
}
}
and your Form should change like this :
public partial class Form1 : BaseForm
{
SqlCommand cmd;
// SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "server = DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ; Integrated Security=True;";/again and again i am calling the=is to every other forms is it the correct way /
string GetData = "Select [FC_Rate] from Forcur where FC_TYPE ='" + comboBox1.Text + "' ";
cmd = new SqlCommand(GetData, getConnection());
var returnValue = cmd.ExecuteScalar();
textBox1.Text = returnValue.ToString();
conn.Close();
}
}

Related

Updating SQL database appears to work but no data changed

I am starting out in C# and am making a tool to update a field in a table when the box_id is in the textbox and the button is clicked. I have worked my way through many errors and now everything runs error free, but no data is being changed. Any help with the issue would be a big help.
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
string query = #"UPDATE Shipment_SCK
SET printed = '1'
WHERE box_id IN (#textBox1);";
SqlCommand cmd = new SqlCommand(query, conn);
Form1 a = new Form1();
cmd.Parameters.Add("#textBox1", SqlDbType.VarChar, 7).Value = a.textBox1.Text;
conn.Open();
int rowsaffected = cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show(rowsaffected.ToString() + " Shipments updated");
}
}
catch (Exception ex)
{
MessageBox.Show("Unable to update:" + ex.Message);
}
At this lines:
Form1 a = new Form1();
cmd.Parameters.Add("#textBox1", SqlDbType.VarChar, 7).Value = a.textBox1.Text;
You're instantiating a new Form1 instance, maybe you can't update nothin' due to empty values on your IN statement. I don't know your logic and how data comes to the method, but maybe you can do something like this:
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
string boxIds = "134, 593, 333, 666";
string query = $#"UPDATE Shipment_SCK
SET printed = '1'
WHERE box_id IN ({boxIds});";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
int rowsaffected = cmd.ExecuteQuery();
conn.Close();
MessageBox.Show(rowsaffected.ToString() + " Shipments updated");
}
}
catch (Exception ex)
{
MessageBox.Show("Unable to update:" + ex.Message);
}
Where boxIds its a string containing all the IDs to be used in your query.
Kind regards
According to your description,you want to transfer values between forms when you press a
button and the box_id in database will change.
You can try the following code to solve this problem.
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string text1
{
get
{
return textBox1.Text;
}
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form = new Form2();
form.Show();
}
}
Form2:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
string query = #"UPDATE Shipment_SCK
SET printed = '1'
WHERE box_id IN (#textBox1);";
SqlCommand cmd = new SqlCommand(query, conn);
Form1 a = (Form1)Application.OpenForms["Form1"];
textBox1.Text = a.text1;
cmd.Parameters.Add("#textBox1", SqlDbType.VarChar, 7).Value = a.text1;
conn.Open();
int rowsaffected = cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show(rowsaffected.ToString() + " Shipments updated");
}
}
catch (Exception ex)
{
MessageBox.Show("Unable to update:" + ex.Message);
}
}
}

Delete rows in database

I have the following code, but I can't seem to manipulate it to work the way I want. I would like to have the command search the data base for the first entry in the database that matches textbox2.text and delete the row.
private void button4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DillPickle\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From ACCNT where ACCNTNUM=" + textBox2.Text , con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
ACCNT."txtbox2.text".Rows[0].Delete();
}
else
{
MessageBox.Show("The account does not exist in the record!");
}
}
There's many ways to accomplish what you are trying to do; here's one way:
private readonly string SqlConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DillPickle\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30";
private readonly string SqlDeleteQuery = "DELETE FROM ACCNT WHERE ACCNTNUM=#accountNumber";
private void button4_Click(object sender, EventArgs e)
{
try
{
using (var sqlConnection = new SqlConnection(SqlConnectionString))
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlConnection.Open();
sqlCommand.CommandText = SqlDeleteQuery;
sqlCommand.Parameters.AddWithValue("#accountNumber", textBox2.Text);
sqlCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// Do something with the exception, like log it...
}
}

Trouble filling a DataTable from MS SQL table

This is what I have so far:
static void Main(string[] args)
{
DataTable t = new DataTable();
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password";
cnn = new SqlConnection(connetionString);
string sql = "SELECT * FROM shiplabels";
SqlDataAdapter a = new SqlDataAdapter(sql, cnn);
try
{
cnn.Open();
a.Fill(t);
cnn.Close();
}
catch (Exception ex)
{
Console.WriteLine ("Can not open connection ! ");
}
}
I want to connect to this Microsoft DB and pull data from it. I am having trouble just getting this to work! When I use this code datatable t has 0 rows where it should come back with a few hundred. I'm clearly missing something simple here?
DataTable dt = new DataTable();
SqlDataAdapter sqlAdtp = new SqlDataAdapter();
string connectionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password";
string sql = "SELECT * FROM shiplabels";
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.CommandType = CommandType.Text;
try
{
sqlAdtp.SelectCommand = cmd;
sqlAdtp.Fill(dt);
}
catch (Exception ex)
{
}
}
}
First, you don't need to open the connection when using SqlDataAdapter.
Also, you forgot the CommandType.
This should work fine for you.
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
sqlCnn = new SqlConnection(connetionString);
try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
adapter.SelectCommand = sqlCmd;
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);
}
adapter.Dispose();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

Reading tables from SQL Server Express database

I am trying to read my tables that are contained within my database in SQL Server Express, but it keeps coming up empty. What is it that am doing wrong?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Updated but still empty:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try {
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con2 = new SqlConnection(connectionString);
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
SqlCommand cmd2 = new SqlCommand(query, con2);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
comboBox1.Items.Add((string)dr2[0]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}}
Latest Updated code. Think I figured it but still showing empty:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try {
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con2 = new SqlConnection(connectionString);
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES ";
SqlCommand cmd2 = new SqlCommand(query, con2);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
string Dtables = dr2.GetString(dr2.GetOrdinal("TABLE_NAME"));
comboBox1.Items.Add(Dtables);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}}
Full class:
namespace unique_database{ public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
string query = "CREATE TABLE [dbo].[" + textBox1.Text + "](" + "[Code] [varchar] (13) NOT NULL," +
"[Description] [varchar] (50) NOT NULL," + "[NDC] [varchar] (50) NULL," +
"[Supplier Code] [varchar] (38) NULL," + "[UOM] [varchar] (8) NULL," + "[Size] [varchar] (8) NULL,)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
SqlConnection con = new SqlConnection("Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True");
string filepath = textBox2.Text; //"C:\\Users\\jdavis\\Desktop\\CRF_105402_New Port Maria Rx.csv";
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = textBox1.Text;
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "CSV files (*.csv)|*.csv|XML files (*.xml)|*.xml";
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox2.Text = openFileDialog.FileName;
}
}
private void FillCombo()
{
try
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES ";
SqlCommand cmd2 = new SqlCommand(query, con2);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
int col = dr2.GetOrdinal("TABLE_NAME");
comboBox1.Items.Add(dr2[col].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Ok, first, don't use comboBox1_SelectedIndexChanged to fill comboBox1.
use YourForm.OnLoad event, the form constructor, or click a button, but don't use SelectedIndexChanged to fill itself, because you're executing this procedure every time you select one item of comboBox1.
To get column index simply use: dr2.GetOrdinal("TABLE_NAME");
private void FillCombo()
{
try
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
SqlCommand cmd2 = new SqlCommand(query, con2);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
int col = dr2.GetOrdinal("TABLE_NAME");
comboBox1.Items.Add(dr2[col].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Use ExecuteReader() instead of ExecuteNonQuery().then Use SqlDataReader() for get result.

System.NullReferenceException Error while storing data in Access database

I am making a simple project where I take "id" and "name" from user and store it into the Access Data base. Whenever I press the Store button System.NullReferenceException Error Comes out. Here is the Code
Where I declared Oledpconnection.
public OleDbConnection Con;
public Form1()
{
InitializeComponent();
string connetionString = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/Users/Mujahid/Documents/Visual Studio 2008/Projects/ts/ts/ts.accdb";
OleDbConnection Con = null;
Con = new OleDbConnection(connetionString);
try
{
Con.Open();
MessageBox.Show("Connection Open ! ");
Con.Close();
}
catch (Exception)
{
MessageBox.Show("Can not open connection ! ");
}
}
And here is the insert button programing
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText="insert into ts(ID,Name)" +"Values ('"+textBox1.Text+"','"+textBox2.Text+"')" ;
cmd.Connection= Con;
Con.Open();
cmd.ExecuteNonQuery();
Con.Close();
please Help !!
Con needs to be a form scope object, not redeclare in the forms constructor.
public OleDbConnection Con;
public Form1()
{
InitializeComponent();
string connetionString = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/Users/Mujahid/Documents/Visual Studio 2008/Projects/ts/ts/ts.accdb";
Con = new OleDbConnection(connetionString);
try
{
Con.Open();
MessageBox.Show("Connection Open ! ");
Con.Close();
}
catch (Exception)
{
MessageBox.Show("Can not open connection ! ");
}
}
public OleDbConnection Con;
...
OleDbConnection Con = null;
You never initialize the class scoped connection instance.

Categories