How can I load SQL data source from a TextBox in C#? - c#

I am developing a program where I need to make a settings form for my database connection. I stopped at how to set the connection string from textboxes. Here is my code:
In the settings form:
public string adresa_servera()
{
return textBox1.Text;
}
The text in this textbox is: MICHAL-PC\SQLEXPRESS
In my main Form I use:
db_nastavenia nastavenia = new db_nastavenia(); //db_nastavenia is the name of the settings Form
string x = nastavenia.adresa_servera();
SqlConnection databaza = new SqlConnection();
databaza.ConnectionString = "Data Source=" + x + ";Initial Catalog=ZBERUDAJOVTEPLA;Persist Security Info=False;User ID=sa; password=diplomovka";
To x I load text from the textbox of the settings Form.
When I try it by manually typing the connection string like this, it works well:
databaza.ConnectionString = "Data Source=MICHAL-PC\\SQLEXPRESS;Initial Catalog=ZBERUDAJOVTEPLA;Persist Security Info=False;User ID=sa; password=diplomovka";

Michal, if this is the whole code and you don't have set a default value for your textbox, it's no surprise it isn't working. You need to retrieve the value while reacting on some event, for example when you push some button... Or maybe monitor OnTextChanged event...
This example shows you create some form and immediately try to retrieve a value. That won't work, because the textbox has no value yet.
Edit:
Those double-double slashes are causing you these problems. Don't know where it is applying this escaping logic, it may be some setting you set, but there's an easy solution:
string x = nastavenia.adresa_servera().Replace("\\", "\");
Please let me know if this helped you.

Hi you can do something like this:
try
{
string x = TextBox1.Text;
string Connection ="Data Source=" + x + ";Initial Catalog=ZBERUDAJOVTEPLA;Persist Security Info=False;User ID=sa; password=diplomovka";
using (var conn = new SqlConnection(Connection))
{
using (var cmd = new SqlCommand("Select * from Yourtable", conn))
{
try
{
conn.Open();
}
catch (SqlException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
Best Regards

Related

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.

Record inserted successfully but database not updated C# and SQL Server Compact Database

private void button1_Click(object sender, EventArgs e)
{
string usernames = textBox1.Text;
string passwords = textBox2.Text;
string emailid = textBox5.Text;
string telno = textBox6.Text;
string connectionstring = "Data Source=|DataDirectory|\\libdb.sdf; Persist Security Info=False ;";
using (SqlCeConnection con = new SqlCeConnection(connectionstring))
{
con.Open();
using (SqlCeCommand Query = new SqlCeCommand("INSERT INTO Registers " + "(usernames,passwords,emailid,telno) " + "VALUES (#usernames,#passwords,#emailid,#telno)", con))
{
Query.Parameters.AddWithValue("#usernames", usernames);
Query.Parameters.AddWithValue("#passwords", passwords);
Query.Parameters.AddWithValue("#emailid", emailid);
Query.Parameters.AddWithValue("#telno", telno);
Query.ExecuteNonQuery();
}
MessageBox.Show("QueryExecuted");
con.Close();
MessageBox.Show("Closedconnecrion");
con.Dispose();
MessageBox.Show("disposed");
this.Close();
/*string conString = "Data Source=" +
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"MyAppData\\database.sdf") + ";Password=yourPassword;";
even this method dosent works */
}
}
}
on executing this code I find it executes successfully. But when I go and check the database, I find the entries empty...
I even tried refreshing database..
I didn't find problem in connectivity.
Query no error executed successfully.
The problem is I didn't find result or the data I gave as input in database.
Please be descriptive with code eg and mail to scarlet.gabriel#gmail.com
Test your connection with the database first, You can get the connection string by creating the udl file.
create a textfile and savaas it with the extension udl (example connection.udl).
double click and run this file.
a window will be opened where you can get the option for getting the connection string.
after testing the connection, close this window and open this file with a note pad.
copy the connection string and paste it in the below statement.
string connectionstring =" paste here";
How can you be sure if the connection is open and has done the job? Use try... catch block to catch if any error occurs:
using (SqlCeConnection con = new SqlCeConnection(connectionstring))
{
try{con.Open();}
catch(Exception ex)
{
// database connection error. log/display ex. > return.
}
if(con.State==ConnectionState.Open)
{
using (SqlCeCommand Query = new SqlCeCommand("INSERT INTO Registers " + "(usernames,passwords,emailid,telno) " + "VALUES (#usernames,#passwords,#emailid,#telno)", con))
{
Query.Parameters.AddWithValue("#usernames", usernames);
Query.Parameters.AddWithValue("#passwords", passwords);
Query.Parameters.AddWithValue("#emailid", emailid);
Query.Parameters.AddWithValue("#telno", telno);
try{
Query.ExecuteNonQuery();
}
catch(Exception ex)
{
// database communication error. log/display ex
}
}
MessageBox.Show("QueryExecuted");
}
if(con.State==ConnectionState.Open)
{
try{con.Close();}
catch{}
}
}
Instead of using connectionstring = "Data Source=|DataDirectory|\libdb.sdf; Persist Security Info=False ;"; Please try to use absolute path like
connectionstring = "Data Source=C:\Users\chandra\Documents\Visual Studio 2010\Projects\Window\LMS\AppData\LMSDatabase.sdf;Persist Security Info=False;";
I hope this will work.
Thanks

MySql connection in C#

i was making a simple windows application form, to register some people in a database, so i made a connection class there is it:
public void Query_send(string cmd)
{
String config = "server=127.0.0.1;uid=root;database=bdcliente;";
MySqlConnection conn = new MySqlConnection(config);
MySqlCommand comm = new MySqlCommand(cmd, conn);
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = config;
conn.Open();
}
catch
{
MessageBox.Show("Error when connecting to the database!");
}
finally
{
conn.Close();
}
}
and then in the BUTTON to give the informations for the MySql i use this:
private void button1_Click(object sender, EventArgs e)
{
Query instance = new Query();
instance.Query_send("INSERT INTO `tbcliente`(`codCliente`, `name`, `cpf`, `telephone`) VALUES ([" + textBox1 + "],[" + textBox2 + "],[" + textBox3 + "],[" + textBox4 + "])");
}
i always get the error with the connection when i click the register button, may someone help me or give me a link of a tutorial that teaches the correct way of doing this?
Thanks, Iago.
My guess is that you need to wrap the VALUES clause results in single quotes as the SQL you are generating will be invalid.
VALUES ('" + textbox1 + "')
Brackets are only required when referring to table or column names. Not when you're referring to string literals.
Odd question, but have you tried applying a password to the database? Depending on the version of MySQL, I have had some issues with leaving the root password unassigned (on local machine you can be safe and just assign 'root' as the password as well). Another option would be to create a user account with permissions and try connection with those credentials.
Not sure if that will help, but it's process of elimination.
Also not sure if method was work in process, but even if it connected there was no execute command against the database.
public void Query_send(string cmd)
{
String config = "server=localhost;uid=root;database=bdcliente;";
MySqlConnection conn = new MySqlConnection(config);
MySqlCommand comm = new MySqlCommand(cmd, conn);
try
{
conn.Open();
comm.ExecuteNonQuery(); '--this was missing
}
catch
{
MessageBox.Show("Error when connecting to the database!");
}
finally
{
conn.Close();
}
}

Connection issue in C# WinForms application with multiple forms

When I run the application, are all forms in the app loaded/initialized even though I have not opened them yet? (I.E. Form.Show)
this is how I closed the connection in the login form:
if (usertype == "UT1") //admin rights
{
//GET LOGGED USER
Home_Admin homeAdmin = new Home_Admin();
homeAdmin.SetUsername(username);
cString.Close();
this.Close();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(OpenHomeAdmin));
t.Start();
}
And how I got to the back up form from Home_Admin's menu strip
private void backUpToolStripMenuItem_Click(object sender, EventArgs e)
{
BackUp BackUpForm = new BackUp();
BackUpForm.Show();
}
I am trying to create a back up of my database and it works perfectly if I run only the back up form. If I start the app from the very beginning, it says back up failed the database is in use. I already closed the connection from login to the form where I will launch the back up form and even set a
if(conn.State = connectionState.Open)
{
conn.close();
}
prior to the back up procedure. Is there any way I can just kill all connections to the SQL database > back up > and then restore the connections?
BACK UP CODE
public void BackupDatabase(String destinationPath)
{
SqlConnection cString = new SqlConnection();
cString.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\MY_THESIS\\WORKING FILES\\NNIT-RMS.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
if (cString.State == ConnectionState.Open)
{
cString.Close();
}
try
{
//MY SERVER
String userName = "NNIT-Admin";
String password = "password";
String serverName = #"RITZEL-PC\SQLEXPRESS";
ServerConnection connection = new ServerConnection(serverName, userName, password);
Server sqlServer = new Server(connection);
Backup BackupMgr = new Backup();
BackupMgr.Devices.AddDevice(destinationPath, DeviceType.File);
BackupMgr.Database = "NNIT DB";
BackupMgr.Action = BackupActionType.Database;
BackupMgr.SqlBackup(sqlServer);
MessageBox.Show("Back up saved!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " " + ex.InnerException);
}
}
FORM LOAD
private void BackUp_Load(object sender, EventArgs e)
{
string date = DateTime.Now.Day.ToString();
string year = DateTime.Now.Year.ToString();
string month = DateTime.Now.Month.ToString();
Filename_txt.Text = "NNIT-RMSDB_" + month + date + year;
}
Error message
http://img824.imageshack.us/img824/8541/error1lj.jpg
In this piece of code:
SqlConnection cString = new SqlConnection();
cString.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\MY_THESIS\\WORKING FILES\\NNIT-RMS.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
if (cString.State == ConnectionState.Open)
{
cString.Close();
}
You are instantiating a new connection and never opening it. The code in the if clause will never be hit.
Your mistake is assuming that the new connection is the only one - there may be multiple connections (opened in other forms and never properly closed) - some not even from your application (for example, using SQL Server Management Studio - having an open query window to your database will mean there is an open connection).
The best solution for to kill all connections to db is to take it offline, other solutions almost fail
using (SqlConnection sqlcnn = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=True"))
{
SqlCommand sqlcmd = new SqlCommand("ALTER DATABASE DB_NAME SET OFFLINE WITH ROLLBACK IMMEDIATE", sqlcnn);
sqlcnn.Open();
sqlcmd.ExecuteNonQuery();
sqlcnn.Close();
}
Add the above code before your backup or restore code and then your backup or restore will work even if you have open connections to your db.

Null Reference Exception in database handling

in c sharp in win forms i am encountering an error, something like null reference exception
this is my code...and also I don't find any entries in the database table...
public partial class Form1 : Form
{
string strCon, strQry;
SqlConnection con;
SqlCommand cmd;
int rowsaffected;
public Form1()
{
InitializeComponent();
}
box s2 = new box();
class box
{
protected string fname;
protected string lname;
public void name(string s1, string s2)
{
fname = s1;
lname = s2;
}
}
void func(string x, string y)
{
s2.name(x, y);
}
private void btnClick_Click(object sender, EventArgs e)
{
string first = txtFname.Text;
string last = txtLname.Text;
func(first, last);
strQry = "Insert Into Practice Values(" + first + "," + last + " )";
cmd = new SqlCommand(strQry, con);
cmd.Connection.Open();
rowsaffected = cmd.ExecuteNonQuery();
cmd.Connection.Close();
MessageBox.Show(+rowsaffected + " row(s) affected");
}
private void Form1_Load(object sender, EventArgs e)
{
strCon = " Data Source = (local); Initial Catalog = Student; User Id= sa; Password=sa;";
con = new SqlConnection(strCon);
}
alt text http://img682.imageshack.us/img682/6017/hjki.jpg
sorry i didnt mention initialize it u mean to say con = new SqlConnection(strCon); i have done dat in dat case error is {"The name 'xyz' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted."}
You are not instantiating the con variable, for example:
SqlConnection con = new SqlConnection(connectionString);
I suppose the error happens because you use con, that is not initialized.
I don't see a SqlConnection con = new SqlConnection(strCon);
I bet your problem is with the connection string, and the connection object is null. Here is a quick way to generate and test a connection string:
Right click the windows desktop or inside a folder in windows explorer,
Click New -> Text Document
Rename the new file to Test.udl (.udl stands for Universal Data Link)
Create and test your connection with the UDL Dialog and click OK
Rename Test.udl to Test.txt and open the text file.
The text file will have a valid connection string that you can use in your code.
Also for your reference, I have simplified your code. The following should be much easier to debug:
private const string dbConnection = "USE THE UDL STRING HERE";
private void btnClick_Click(object sender, EventArgs e)
{
string first = txtFname.Text;
string last = txtLname.Text;
//I think the orig code was missing the single quotes
string query = string.Format("INSERT INTO Practice ('{0}','{1}')", first, last);
int rowsAffected = 0;
//Using statement will automatically close the connection for you
//Using a const for connection string ensures .NET Connection Pooling
using (SqlConnection conn = new SqlConnection(dbConnection))
{
//Creates a command associated with the SqlConnection
SqlCommand cmd = conn.CreateCommand();
//Set your sql statement
cmd.CommandText = query;
//open the connection
cmd.Connection.Open();
//Execute the connection
rowsAffected = cmd.ExecuteNonQuery();
}
MessageBox.Show(rowsAffected + " rows Affected");
}
Are you setting a connection string? It appears you are accessing the Connection object without telling it where to insert the data.
cmd.Connection.ConnectionString = "some string";
I don't think you need cmd.Connection.Open and cmd.Connection.Close.
cmd will open the connection & close it, in order to execute the query/stored procedure.
You are actually creating you connection correctly. What is happening is if you look at your connection string
strCon = " Data Source = (local); Initial Catalog = Student; User Id= sa; Password=sa;";
when it tries to connect it reads this as:
Data Source: " (local)"
Initial Catalog: " Student"
User Id= " sa"
Password - "sa"
So the spaces that you have after the equals signs are getting passed to the SQL server. What your string should look like is this
strCon = "Data Source =(local); Initial Catalog=Student;User Id=sa;Password=sa;"
I am pretty sure that you are never getting an actual connection to your database, but it's failing silently.
Any time you get a null reference on a line that has multiple calls linked together like:
something.somethingElse.somethingElse
break it apart and check each piece. For example, in your case this code:
cmd = new SqlCommand(strQry, con);
SqlConnection sc = cmd.Connection;
System.Diagnostics.Debug.Assert(sc != null, "You got a null connection from the SqlCommand.");
sc.Open();
may demonstrate what the problem is.

Categories

Resources