How run a C# query? - c#

I use Visual Studio community 2015 and i use MySQL connector (MySQL for Visual Studio) for connection my MySQL database to Visual Studio, this part is already done and i have Visual Studio connected to database.
Now i like to know what is my next step to get (using a select query) data from the database to my form program ?
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;
namespace Test_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// How can i get data from the database in here ?
}
}
}
I got my answer ! Check best answer.

I've gotta run for a bit so I'll take you at yoyur word that you've tried something and post this in hopes it may help you (it's nice to see what you've done to know how to help you).
You said you had the connection working. Here's some examples of basic queries. The most important thing to remember is there's a lot of different ways to do this, so these are just intended as examples. They are all manual -- for help databinding omething automatically, you'll have to post and ask.
Please PLEASE as you learn to do this - make SURE you always use parameters and don't do things like "UPDATE myUserData set DRIVER_LICENSE = 'U7439821' WHERE LAST_NAME = 'Smith'". You are begging for bad things to happen to you if you do that. Take the extra 30 seconds to use command.Parameter.Add(,).
Finally, these examples are for MS-SQL Server. You'll need to change the connection from SqlConnection to MySqlConnection and from SQLCommand to MySqlCommand.
If you have any other questions, just ask.
//these are connection methods that help connect you to your database manually.
public SqlConnection getConn()
{
return new SqlConnection(getConnString());
}
public string getConnString()
{
return #"Data Source=lily.arvixe.com;Initial Catalog={My_Database_Name};Persist Security Info=True;User ID={My_Database_Username};Password={My_Database_Password};Connection Timeout=7000";
}
//to get a single value from a single field:
public object scalar(string sql)
{
object ret;
using (SqlConnection conn = getConn())
{
conn.Open();
using (SqlCommand com = conn.CreateCommand())
{
com.CommandText = sql;
ret = com.ExecuteScalar();
}
conn.Close();
}
return ret;
}
//To do a SELECT with multiple rows returned
private List<string> get_Column_Names(string tableName)
{
List<string> ret = new List<string>();
using (SqlConnection conn = getConn())
{
conn.Open();
using(SqlCommand com = conn.CreateCommand())
{
com.CommandText = "select column_Name from INFORMATION_SCHEMA.COLUMNS where table_Name = '" + tableName + "'";
com.CommandTimeout = 600;
SqlDataReader read = com.ExecuteReader();
while (read.Read())
{
ret.Add(Convert.ToString(read[0]));
}
}
conn.Close();
}
return ret;
}
// to do an INSERT or UPDATE or anything that does not return data
// USE PARAMETERS if people go anywhere near this data
public void nonQuery(string sql)
{
using(SqlConnection conn = getConn())
{
conn.Open();
using(SqlCommand com = conn.CreateCommand())
{
com.CommandText = sql;
com.CommandTimeout = 5900;
com.ExecuteNonQuery();
}
conn.Close();
}
}
//to save a DataTable manually:
public void saveDataTable(string tableName, DataTable table)
{
using (SqlConnection conn = getConn())
{
conn.Open();
using (var bulkCopy = new SqlBulkCopy(conn))//, SqlBulkCopyOptions.KeepIdentity))
{
// my DataTable column names match my SQL Column names, so I simply made this loop. However if your column names don't match, just pass in which datatable name matches the SQL column name in Column Mappings
foreach (DataColumn col in table.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, "[" + col.ColumnName + "]");
}
bulkCopy.BulkCopyTimeout = 8000;
bulkCopy.DestinationTableName = tableName;
bulkCopy.BatchSize = 10000;
bulkCopy.EnableStreaming = true;
// bulkCopy.SqlRowsCopied += BulkCopy_SqlRowsCopied;
//bulkCopy.NotifyAfter = 10000;
//isCopyInProgess = true;
bulkCopy.WriteToServer(table);
}
conn.Close();
}
}
Again, there are more than a few ways to accomplish each of these tasks programatically - I'm just showing you the most basic. If you want to learn how to automatically bind a control to data, try searching for "C-sharp Databind CONTROL_NAME Visual studio" and you should get all the help you need.

I got my answer :
MySqlConnection sqlConnection1 = new MySqlConnection("server=server;uid=username;" + "pwd=password;database=database;");
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader reader;
cmd.CommandText = "SELECT * FROM table";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
try
{
reader.Read();
value = reader.GetString(x);
}
finally
{
reader.Close();
}

Related

c# System.InvalidOperationException: 'The connection is already open.'

I'm coding a Windows Forms login page for an administration application. My problem is, that when I try to log on, I get the error message
System.InvalidOperationException: 'The connection is already open.'
Any help would be appreciated
public partial class Form1 : Form
{
MySqlConnection con = new MySqlConnection (#"Database= app2000; Data Source = localhost; User = root; Password =''");
int i;
public Form1()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnLogin_Click(object sender, EventArgs e)
{
i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM adminlogin WHERE username='" + txtBoxUsername + "'AND password='" + txtBoxPassword + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i == 0)
{
lblerrorInput.Show();
}
else
{
this.Hide();
Main ss = new Main();
ss.Show();
}
}
}
Do not cache Connection, it's a typical antipattern, but recreate it when you need it
public partial class Form1 : Form {
...
//DONE: Extract method
private static bool UserExists(string userName, string password) {
//DONE: Do not cache connections, but recreate them
using (MySqlConnection con = new MySqlConnection (#"...") {
con.Open();
//DONE: wrap IDisposable into using
using (MySqlCommand cmd = con.CreateCommand()) {
cmd.CommandType = CommandType.Text;
//DONE: Make query being readable
//DONE: Make query being parametrized
cmd.CommandText =
#"SELECT *
FROM adminlogin
WHERE username = #UserName
AND password = #PassWord"; // <- A-A-A! Password as a plain text!
//TODO: the simplest, but not the best solution:
// better to create parameters explicitly
// cmd.Parameters.Add(...)
cmd.Parameters.AddWithValue("#UserName", txtBoxUsername);
cmd.Parameters.AddWithValue("#PassWord", txtBoxPassword);
// If we have at least one record, the user exists
using (var reader = cmd.ExecuteReader()) {
return (reader.Read());
}
}
}
}
Finally
private void btnLogin_Click(object sender, EventArgs e) {
if (!UserExists(txtBoxUsername.Text, txtBoxPassword.Text))
lblerrorInput.Show();
else {
Hide();
Main ss = new Main();
ss.Show();
}
}
You forgot to close the connection, use con.Close() at the end to close the connection and avoid this error the next time the event fires.
There are some mistakes in your code.
You should close the sql connection when you finished your process.
I suggest you to use using statement to dispose connection instance after complete database actions.
Also, you should use command parameters to prevent Sql injection.
You can declare connection string like this;
private string _connectionString = #"Database= app2000; Data Source = localhost; User = root; Password =''";
The method part looks like;
using (var con = new MySqlConnection(_connectionString))
{
i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM adminlogin WHERE username = #username and password = #password";
cmd.Parameters.AddWithValue("#username", txtBoxUsername);
cmd.Parameters.AddWithValue("#password", txtBoxPassword);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i == 0)
{
lblerrorInput.Show();
}
else
{
this.Hide();
Main ss = new Main();
ss.Show();
}
con.Close();
}
First, don't cache your Connection objects. It's a terrible practice and I've had to go back and fix it every time I accept a new job and inherit code. Most database access classes implement IDisposable, so use using and take advantage of it to keep your code clean. FYI, Readers and Adapters are also IDisposable so you can do the same with them, too.
string command = "select stuff from mydata";
string connection = GetConnectionStringFromEncryptedConfigFile();
using (var conn = new SqlConnection(connection))
{
using (var cmd = new SqlCommand(command, conn))
{
cmd.Connection.Open();
//do stuff
}
}
Second, if you're forced to use a cached connection (i.e., you inherited horrible code and don't have time to fix it yet), check your State first.
if(conn.State != System.Data.ConnectionState.Open)
{
conn.Open();
}
Note that there are a lot more states than just Open and Closed, and if you try to open a connection that is busy, you'll still get errors. It's still a much wiser approach to use the IDisposable implementations with using so you don't have to worry about this sort of thing so much.

Connect a C# Windows Form App to a MySQL Database on a Linux based server

I am working on an C# application which would use the remote MySQL database located in my website hosted on a Linux server with PHP & MySQL support.
I tried to connect directly to the MySQL database using MySql.Data.MySQLClient Reference, as a result, my program is throwing following exception :
"Unable to connect to any of the specified MySQL hosts."
I searched many tutorials but got no solutions... getting the same error.
Can anybody please tell me how to do this.
Please suggest any online links or tutorials or your own idea.
Please help me.
here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace mysq
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string conn = "Server = myserver;database = db ;uid = username ;password = pwd ;";
MySqlConnection con = new MySqlConnection(conn);
con.Open();
if (con.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand("Select * from table", con);
DataTable dt = new DataTable();
MySqlDataAdapter ad = new MySqlDataAdapter(cmd);
ad.Fill(dt);
dataGridView1.DataSource = dt;
}
}
catch (Exception)
{
throw;
}
}
}
}
Thanks in advance..
I've written an own class with functions for my mysql-connection.
First of all declare the server connection:
string ServerConnection = "Server=localhost;Port=1234;Database=YourDb;Uid=user;password=pass;"
This is how I select data:
public static void DB_Select(string s, params List<string>[] lists)
{
try
{
using(var conn = new MySqlConnection(ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
using(var sqlreader = cmd.ExecuteReader())
while (sqlreader.Read())
{
if (sqlreader[0].ToString().Length > 0)
{
for (int i = 0; i < lists.Count(); i++)
{
lists[i].Add(sqlreader[i].ToString());
}
}
else
{
foreach (List<string> save in lists)
{
save.Add("/");
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error while selecting data from database!\nDetails: " + ex);
}
}
The call:
List<string> allRows = new List<string>();
DB_Select("SELECT field1 FROM table1 WHERE 1", allRows);
Notice: For every field you are selecting, you have to pass an own list which will be filled with the output.
For updating your database it would be quite the same function. You just wouldnt have to grad the output. Could look like this:
public static void DB_Update(string s)
{
try
{
using (var conn = new MySqlConnection(ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
int numRowsUpdated = cmd.ExecuteNonQuery();
if(numRowsUpdated < 0)
{
MessageBox.Show("Warning DB-Contact: Affected_rows < 0!");
}
}
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Updating database failed!\n\nSQL: {0}\n\nERROR: {1}",s,ex.Message));
}
}
You have to provide proper connection string in your program, i am suspecious you are passing proper IP address or hostname of the server where you hosted the database. As a first step try to ping the db server to make sure it is reachable from your machine. If it is reachable try as follows:
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
string conn = "Server =<provide proper ip address >;database = db ;uid = username ;password = pwd ;";
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
More details here : http://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-open.html

Return value from SQL local database to global double variable

I'm trying to get data from a SQL Server local database. I have created Table with 1 columns buyEURrate type float and the table name is CurrencyRates I have global double variable and I'm trying to set its value the same as the first Row from the buyEURrate columns in CurrencyRates on FormLoad so this code below is inside FormLoad. I'm really new to SQL with C#.
I'm using Visual Studio 2012 and the this is Windows Forms App
using (SqlCeConnection conn =
new SqlCeConnection(#"Data Source=C:\Users\FluksikartoN\Documents\Visual Studio 2012\Projects\BuroFoki\BuroFoki\MainDB.sdf"))
using (SqlCeCommand cmd = conn.CreateCommand())
{
conn.Open();
//commands represent a query or a stored procedure
cmd.CommandText = "SELECT buyEURrate FROM CurrencyRates";
using (SqlCeDataReader rd = cmd.ExecuteReader())
{
while (rd.Read())
{
EURbuy = Convert.ToDouble(rd[0]);
EURsell = Convert.ToDouble(rd[1]);
//Index was outside the bounds of the array. error
}Table
}
conn.Close();
}
SOmething like this should work:
using (SqlCeConnection conn =
new SqlCeConnection(#"Data Source=C:\Users\FluksikartoN\Documents\Visual Studio 2012\Projects\BuroFoki\BuroFoki\MainDB.sdf"))
using (SqlCeCommand cmd = conn.CreateCommand())
{
conn.Open();
//commands represent a query or a stored procedure
cmd.CommandText = "SELECT buyEURrate FROM CurrencyRates";
using (SqlCeDataReader rd = cmd.ExecuteReader())
{
while(rd.Read())
{
double variable = Convert.ToDouble(rd[0]);
string foo = rd.GetString[1];
//do something with variable and foo before going to next row in query
}
}
conn.Close();
}
This may also work
double variable = rd.GetDouble(0);
Although I'm not 100% sure GetDouble is an actual function like GetString() is
Edit
After double checking double variable = rd.GetDouble(0) will work to pull the first column data as a double
using (SqlCeConnection conn = new SqlCeConnection ("Server=.;Database=Northwind;User Id=sa;Password=as"))
{
using (SqlCeCommand cmd = conn.CreateCommand())
{
conn.Open();
//commands represent a query or a stored procedure
cmd.CommandText = "SELECT buyEURrate FROM CurrencyRates";
using (SqlCeDataReader rd = cmd.ExecuteReader())
{
double rate = 0;
if (rd.Read()) // if datareader has rows
{
rate = Convert.ToDouble(rd[0]);
}
}
conn.Close();
}
}
Try this:
using (SqlCeConnection conn =
new SqlCeConnection(#"Data Source=C:\Users\FluksikartoN\Documents\Visual Studio 2012\Projects\BuroFoki\BuroFoki\MainDB.sdf"))
using (SqlCeCommand cmd = conn.CreateCommand())
{
conn.Open();
//commands represent a query or a stored procedure
cmd.CommandText = "SELECT buyEURrate FROM CurrencyRates";
using (SqlCeDataReader rd = cmd.ExecuteReader())
{
if(rd.Read())
{
double variable = rd.GetDouble(0);
}
}
conn.Close();
}
You first need to Read a tuple using DataReader, if it returns true, you can go ahead and read get actual data.
You can also use cmd.ExecuteScalar() method if you are pretty sure that you want to read exactly first column of the first tuple of your table.
Here's more info at MSDN

Cannot insert data into mbf database

I have been trying to insert data into a sql database for the last hours. for one or other reason I am able to connect to the database, but no data is inserted into the database. if I run the sql statement directly in the database it does seem to work. So therefore, I was able to conclude that the statement is correct. Furthermore, there were no errors in runtime. I have got the following c# code:
//Neither of these statements seem to work.
string sqlStatement = "INSERT INTO dbo.eventTable (colA, colB, colC, colD, colE, colF, colG, colH, colI) VALUES (#a,#b,#c,#d,#e,#f,#g,#h,#i)";
string altSqlStatement = "INSERT INTO dbo.eventTable (colA, colB, colC, colD, colE, colF, colG, colH, colI) VALUES (#a,#b,#c,#d,#e,#f,#g,#h,#i)";
foreach (DataRow row in importData.Rows)
{
using (SqlConnection conn = new SqlConnection(form1.Properties.Settings.Default.showConnectionString))
{
using (SqlCommand insertCommand = new SqlCommand())
{
insertCommand.Connection = conn;
insertCommand.CommandText = sqlStatement;
insertCommand.CommandType = CommandType.Text;
insertCommand.Parameters.AddWithValue("#a", row["CUE"].ToString());
insertCommand.Parameters.AddWithValue("#b", row["HH"].ToString());
insertCommand.Parameters.AddWithValue("#c", row["MM"].ToString());
insertCommand.Parameters.AddWithValue("#d", row["SS"].ToString());
insertCommand.Parameters.AddWithValue("#e", row["FF"].ToString());
insertCommand.Parameters.AddWithValue("#f", row["ADDR"].ToString());
insertCommand.Parameters.AddWithValue("#g", row["Event Description"].ToString());
insertCommand.Parameters.AddWithValue("#h", row["CAL"].ToString());
insertCommand.Parameters.AddWithValue("#i", row["PFT"].ToString());
try
{
conn.Open();
int _affected = insertCommand.ExecuteNonQuery();
}
catch(SqlException e)
{
// do something with the exception
}
}
}
}
if I change the connection parameters to something false, an error occurs, so that seems correct.
Any help would be greatly appreciated.
Thanks!
Alex
Try using this function as a template, big difference is that it is opening the connection before creating the command. I've not seen it done the way you have it setup. You also really should be opening the connection outside of the for loop, not in the for loop. Why open and close it repeatedly; the foreach should be inside the inner 'using'
public void ExecuteQuery(string query, Dictionary<string, object> parameters)
{
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
if (parameters != null)
{
foreach (string parameter in parameters.Keys)
{
cmd.Parameters.AddWithValue(parameter, parameters[parameter]);
}
}
cmd.ExecuteNonQuery();
}
}
}

Loading combobox from database in C#

I am creating an application, where I can add a customer's first name, last name, email, the date, service type (pc repair), the technician PC brand, pc type, type of OS, and the problem with the computer. I am able to insert data into the MySQL database using phpMyAdmin.
However, I a stuck on this part. I am trying to view the service order that was just created. I would like to load the combobox by the last name of the customer, and once I click on the customer's name, it populates all the fields that were mentioned above and the service number that it was inserted into the database. I am having issues loading the combobox and texfields.
Any ideas are appreciated! If a combobox is a bad idea and there is a better way, please let me know! I tried this code, but SQLDataAdapter is not working for me. I somehow can't find an example that I can relate too.
private void cbViewServices_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbViewServices.SelectedIndex >- 1)
{
string lastName = cbViewServices.SelectedValue.ToString();
MySqlConnection conn = new MySqlConnection("server=localhost;uid=******;password=**********;database=dboserviceinfo;");
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select distinct LastName from tserviceinfo where LastName='" + lastName + "'", conn);
DataSet ds = new DataSet();
da.Fill(ds); conn.Close();
}
}
I do not recommend using the 'Lastname' as a parameter to load your details since that field most likely isn't unique. Unless that is the case in your program.
This sample does the following:
Load customer ID (or lastname in your case) to a combobox.
Handle the combobox's change event and pass it as a parameter to a
method that will use that to load the details.
Load the customer details using the passed parameter.
A couple of guidelines:
Enclose disposable objects in a 'using' statement so it will be
disposed properly.
Do not use string concatenation to create your SQL statements. Use
SQL parameters instead, that way you'll avoid SQL injection and make
your code clearer.
Take a look at MySQL .NET connector provider documentation for best practices.
//Load customer ID to a combobox
private void LoadCustomersId()
{
var connectionString = "connection string goes here";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "SELECT Id FROM Customers";
using (var command = new MySqlCommand(query, connection))
{
using (var reader = command.ExecuteReader())
{
//Iterate through the rows and add it to the combobox's items
while (reader.Read())
{
CustomerIdComboBox.Items.Add(reader.GetString("Id"));
}
}
}
}
}
//Load customer details using the ID
private void LoadCustomerDetailsById(int id)
{
var connectionString = "connection string goes here";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "SELECT Id, Firstname, Lastname FROM Customer WHERE Id = #customerId";
using (var command = new MySqlCommand(query, connection))
{
//Always use SQL parameters to avoid SQL injection and it automatically escapes characters
command.Parameters.AddWithValue("#customerId", id);
using (var reader = command.ExecuteReader())
{
//No customer found by supplied ID
if (!reader.HasRows)
return;
CustomerIdTextBox.Text = reader.GetInt32("Id").ToString();
FirstnameTextBox.Text = reader.GetString("Firstname");
LastnameTextBox.Text = reader.GetString("Lastname");
}
}
}
}
//Pass the selected ID in the combobox to the customer details loader method
private void CustomerIdComboBox_SelectedIndexChanged(object s, EventArgs e)
{
var customerId = Convert.ToInt32(CustomerIdComboBox.Text);
LoadCustomerDetailsById(customerId);
}
I'm not entirely sure if this is what your looking for but most of the guidelines still applies.
Hope this helps!
Try something like this to bind data to the combo box:
public void ListCat()
{
DataTable linkcat = new DataTable("linkcat");
using (SqlConnection sqlConn = new SqlConnection(#"Connection stuff;"))
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT LastName FROM list WHERE LastName <> 'NULL'", sqlConn))
{
da.Fill(linkcat);
}
}
foreach (DataRow da in linkcat.Rows)
{
comboBox1.Items.Add(da[0].ToString());
}
}
Taken from my own question.
SqlDataAdapter is used to communicate with SQL Server rather than MySQL.
Try the following:
MySqlDataAdapter da = new MySqlDataAdapter("select distinct LastName from tserviceinfo where LastName='" + lastName + "'", conn);
We can also use while loop. When completing the database connection after the SQLDatareader we can use while loop.
"userRead " is SQLData reader
while (userRead.Read())
{
cboxReportNo.Items.Add(userRead[1].ToString());
}
bind your dataset in ComboBox DataSource
this.comboBox1.DataSource = ds;
this.comboBox1.DisplayMember = "LastName";
this.comboBox1.ValueMember = "Id";
this.comboBox1.SelectedIndex = -1;
this.comboBox1.AutoCompleteMode = AutoCompleteMode.Append;
this.comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
//USING
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace YourNamespace
{
//Initialization
string connetionString = null;
SqlConnection cnn;
SqlCommand cmdDataBase;
SqlDataReader reader;
DataTable dt;
public frmName()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
FillComboNameOfCombo();
}
void FillcmbNameOfCombo()
{
string sqlQuery = "SELECT * FROM DATABASENAME.[dbo].[TABLENAME];";
connetionString = "Data Source=YourPathToServer;Initial Catalog=DATABASE_NAME;User ID=id;Password=pass";
cnn = new SqlConnection(connetionString);
cmdDataBase = new SqlCommand(sqlQuery, cnn);
try {
cnn.Open();
reader = cmdDataBase.ExecuteReader();
dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("COLUMN_NAME", typeof(string));
dt.Load(reader);
cnn.Close();
cmbGender.DataSource = dt;
cmbGender.ValueMember = "ID";
cmbGender.DisplayMember = "COLUMN_NAME";
dt = null;
cnn = null;
cmdDataBase = null;
connetionString = null;
reader = null;
}
catch (Exception ex) {
MessageBox.Show("Can not open connection ! " + ex.ToString());
}
}
}

Categories

Resources