SQL Server connection in WPF - c#

I have a data base in SQL Server 2008 and connecting it in WPF application.I want to read data from table and show in datagrid. Connection is successfully created but when I show it in grid,it show db error(Exception handling).
This is what I am doing.Thanks in advance.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}
It shows connected when i comment the line sda.Fill(dt);

Your SqlCommand doesn't know you opened the connection- it requires an instance of SqlConnection.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = Get_Data;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}

You don't assign the command any connection. You open the connection then create a command, but don't link the two.
Try something like:
SqlConnection conn = new SqlConnection(#"Server(local);Database=Sample_db;Trusted_Connection=Yes;");
conn.Open();
string sql= "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(sql);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);

Assign Connection Object to SqlCommand Object.
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandTimeout = 15;
command.CommandType = CommandType.Text;
command.CommandText = queryString;
connection.Open();
//Perfom desired Action
}

Add thisConnection as 2nd parameter in
Sqlcommand cmd = new SqlCommand(Get_Data, thisConnection)
try {
string connectionstring = "#"
Server = (local) Database = Sample_dbTrusted_Connection = Yes;
"";
SqlConnection thisConnection = new SqlConnection(connectionstring);
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data, thisConnection);
SqlDataAdapter sda = new SqlDataAdapter(cmd);`
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
} catch {
MessageBox.Show("db error");
}

I use this code with Oracle and hope it will help you.
First add reference Oracle.DataAccess then add namespace using Oracle.DataAccess.Client;
And using the following code
try
{
string MyConString = "Data Source=localhost;User Id= yourusername;Password=yourpassword;";
using (OracleConnection connection = new OracleConnection(MyConString))
{
connection.Open();
sqldb1 = "select * from DEMO_CUSTOMERS;";
using (OracleCommand cmdSe1 = new OracleCommand(sqldb1, connection))
{
DataTable dt = new DataTable();
OracleDataAdapter da = new OracleDataAdapter(cmdSe1);
da.Fill(dt);
db1.ItemsSource = dt.DefaultView;
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
XAML code:
<DockPanel>
<DataGrid Margin="10.0" DockPanel.Dock="Left" Name="db1" AutoGenerateColumns="True" >
</DataGrid>
</DockPanel>

public DataTable Execute(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
DataTable dt = new DataTable();
sda.SelectCommand = command;
command.Connection = connection;
connection.Open();
sda.Fill(dt);
connection.Close();
if (dt != null && dt.Columns.Count > 0)
return dt;
else
return null;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
else
{
Console.WriteLine("Network is disconnect");
return null;
}
return null;
}
or :
public void ExecuteNonQuery(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

Related

dropdownlist is not showing the selecteditem from the database

am trying to get the selected item from the database, but its not displaying nothing
code behind:
private void bindRows()
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand cmd = new SqlCommand("select id, message from Dropdown", connection);
SqlDataReader reader = cmd.ExecuteReader();
reader.Close();
SqlDataAdapter adapter = new SqlDataAdapter("select id, message from Dropdown", connection);
DataSet ds = new DataSet();
adapter.Fill(ds);
DdlRegister.DataSource = ds;
DdlRegister.DataTextField = "message";
DdlRegister.DataValueField = "id";
DdlRegister.DataBind();
DdlRegister.Items.Insert(0, new ListItem("I Want", "0"));
connection.Close();
}
catch (Exception e)
{
}
}
code of buttonclick
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string selectCommand = "Insert into Register (name,designation,company,mobile,email,message) values(#name,#designation,#company,#mobile,#email,#message);";
SqlCommand cmd = new SqlCommand(selectCommand, connection);
cmd.Parameters.AddWithValue("#name", txtname.Text.Trim());
cmd.Parameters.AddWithValue("#designation", txtdesignation.Text.Trim());
cmd.Parameters.AddWithValue("#company", txtcompany.Text.Trim());
cmd.Parameters.AddWithValue("#mobile", txtmobile.Text.Trim());
cmd.Parameters.AddWithValue("#email", txtemail.Text.Trim());
cmd.Parameters.AddWithValue("#message", DdlRegister.SelectedItem.Text.Trim());
int cnt = cmd.ExecuteNonQuery();
if (cnt > 0)
{
ShowMessage("Registeration is done");
}
Response.Redirect("Index.aspx");
connection.Close();
}
catch (Exception ex)
{
}
design
<asp:DropDownList ID="DdlRegister" runat="server" CssClass="form-control ddl " OnSelectedIndexChanged="DdlRegister_SelectedIndexChanged" AutoPostBack="true" >
</asp:DropDownList>
private void bindRows()
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter("select id, message from Dropdown", connection);
DataSet ds = new DataSet();
adapter.Fill(ds);
DdlRegister.DataSource = ds;
DdlRegister.DataTextField = "message";
DdlRegister.DataValueField = "id";
DdlRegister.DataBind();
DdlRegister.Items.Insert(0, new ListItem("I Want", "0"));
connection.Close();
}
catch (Exception e)
{
}
}
try something like this
string mainconn = ConfigurationManager.ConnectionStrings["MY"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[sortcompany]";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlconn.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
Company.ValueMember = "company_name";
Company.DisplayMember = "company_name";
Company.DataSource = dt;

Trying to pass SqlCommand in SqlDataAdapter as parameters

I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();
I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.
Running code (aspx page code)
if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
// username & password logic
DataTable dt = new DataTable();
string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = #USERNAME AND PASSWORD = #PASSWORD";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
cmd.Parameters.Add("#PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();
DBConnection conn_ = new DBConnection();
dt = conn_.SelectData(cmd);
if (conn_.SQL_dt.Rows.Count > 0)
{
Response.Redirect("Home.aspx", false);
}
}
Successful connection class code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter();
command.CommandType = CommandType.Text;
command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
How can I pass CommandType.Text as parameters for SqlDataAdapter?
Error code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);
// command.CommandType = CommandType.Text;
// command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
I am getting this error:
System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.
at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...
public DataTable SelectData(string query)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Your Connection String here"))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(dt);
return dt;
}
}
}
}
To use:
SelectData("select * from yourTable");
Reds has the answer. Just to clean the code up a little bit...
public DataTable SelectData(string query)
{
using (var connection = new SqlConnection("myConnectionString"))
using (var command = new SqlCommand(query, connection))
using (var adapter = new SqlDataAdapter(command))
{
var dt = new DataTable();
connection.Open();
adapter.Fill(dt);
return dt;
}
}
Actually you should pass the connection object on SQLCommand.Hope it helped you
DBConnection conn_ = new DBConnection();
SqlCommand cmd = new SqlCommand(strQuery,conn_);
The error that you are getting is not related to CommandType.Text, it says you have initialised the connection property of of SelectCommand. Basically you should uncomment "command.Connection = conn;" to get rid of this error. If you still face any other issue , it is better to provide those details in the questions to provide accurate answer.

DataTable Not Returning Data

What is my method missing? It is not returning the data table.
public DataTable GetHotelReportData(int _ratpropid) {
var _connectionString = _isDevelopment ? CommonTypes.Dev : CommonTypes.Prod;
DataTable dt = new DataTable();
dt.Clear();
SqlConnection conn = new SqlConnection(_connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("ww.HotelRpt_spGenerateData2018", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#RatPropId", _ratpropid);
SqlDataAdapter da = new SqlDataAdapter();
try {
da.SelectCommand = cmd;
da.Fill(dt);
}
catch (Exception _ex) {
new ErrorLogging().Log(_ex);
}
finally {
conn.Close();
da.Dispose();
cmd.Dispose();
}
return dt;
}
Try cutting the data adapter out and just using the command. No need for an adapter as far as I can tell:
public DataTable GetHotelReportData(int _ratpropid) {
var _connectionString = _isDevelopment ? CommonTypes.Dev : CommonTypes.Prod;
DataTable dt = new DataTable();
dt.Clear();
SqlConnection conn = new SqlConnection(_connectionString);
SqlCommand cmd = new SqlCommand("ww.HotelRpt_spGenerateData2018", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#RatPropId", _ratpropid);
try {
conn.Open();
dt.Load(cmd.ExecuteReader);
return dt;
}
catch (Exception _ex) {
new ErrorLogging().Log(_ex);
}
finally {
conn.Close();
cmd.Dispose();
}
}
If that doesn't work, try executing your stored procedure natively in SSMS (or another DBMS) to see if you get any results there.

Why Datatables return Null when it is executed via SQL Command text?

I got two classes, one for db connection and another to get data. When I use the SqlCommand type as stored procedure it returns the data table properly, but when I change the command type to text and change the command text properly it returns a null value. Why is this happening?
Class 1
public class DB_Connection
{
public SqlConnection cnn;
public SqlCommand cmd;
public SqlDataAdapter ada;
public DB_Connection()
{
cnn = new SqlConnection("Data Source=svr01;Initial Catalog=PDFScramble;Integrated Security=True");
cnn.Open();
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;// *changed in here SP or Text*
cmd.Connection = cnn;
ada = new SqlDataAdapter();
ada.SelectCommand = cmd;
}
Class 2
public class Data : DB_Connection
{
public string DException { get; set; }
public DataTable Datatable { get; set; }
public bool GetCivicEntities()
{
try
{
cmd.CommandText = "SELECT Id, Description, StateId ,EntityTypeId FROM CivicEntities";
ada.Fill(Datatable);// *Null in here*
return true;
}
catch (Exception ex)
{
DException = ex.Message;
return false;
}
}
Your Datatable is null, because of that you have this problem. This should fix it.
cmd.CommandText = "SELECT Id, Description, StateId ,EntityTypeId FROM CivicEntities";
Datatable = new DataTable();
ada.Fill(Datatable);
return true;
There is something wrong with the class structure. Check with this
using (SqlConnection conn = new SqlConnection("connectionString"))
{
SqlCommand cmd = null;
SqlParameter prm = null;
SqlDataAdapter dad = null;
DataTable dt = new DataTable();
cmd = new SqlCommand("SPName", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
dad = new SqlDataAdapter(cmd);
dad.Fill(dt);
conn.Close();
}
using (SqlConnection conn = new SqlConnection("connectionString"))
{
SqlCommand cmd = null;
SqlParameter prm = null;
SqlDataAdapter dad = null;
DataTable dt = new DataTable();
cmd = new SqlCommand("select * from dummy",conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
dad = new SqlDataAdapter(cmd);
dad.Fill(dt);
conn.Close();
}

Populate a datagridview with sql query results

I'm trying to present query results, but I keep getting a blank data grid.
It's like the data itself is not visible
Here is my code:
private void Employee_Report_Load(object sender, EventArgs e)
{
string select = "SELECT * FROM tblEmployee";
Connection c = new Connection();
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
What's wrong with this code?
Here's your code fixed up. Next forget bindingsource
var select = "SELECT * FROM tblEmployee";
var c = new SqlConnection(yourConnectionString); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
String strConnection = Properties.Settings.Default.BooksConnectionString;
SqlConnection con = new SqlConnection(strConnection);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from titles";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;
You don't need bindingSource1
Just set dataGridView1.DataSource = table;
Try binding your DataGridView to the DefaultView of the DataTable:
dataGridView1.DataSource = table.DefaultView;
This is suppose to be the safest and error pron query :
public void Load_Data()
{
using (SqlConnection connection = new SqlConnection(DatabaseServices.connectionString)) //use your connection string here
{
var bindingSource = new BindingSource();
string fetachSlidesRecentSQL = "select top (50) * from dbo.slides order by created_date desc";
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(fetachSlidesRecentSQL, connection))
{
try
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource.DataSource = table;
recent_slides_grd_view.ReadOnly = true;
recent_slides_grd_view.DataSource = bindingSource;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString(), "ERROR Loading");
}
finally
{
connection.Close();
}
}
}
}
You may get a blank data grid if you set the data Source to a Dataset that you added to the form but is not being used. Set this to None if you are programatically setting your dataSource based on the above codes.
You may try this sample, and always check your Connection String, you can use this example with or with out bindingsource you can load the data to datagridview.
private void Employee_Report_Load(object sender, EventArgs e)
{
var table = new DataTable();
var connection = "ConnectionString";
using (var con = new SqlConnection { ConnectionString = connection })
{
using (var command = new SqlCommand { Connection = con })
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
try
{
command.CommandText = #"SELECT * FROM tblEmployee";
table.Load(command.ExecuteReader());
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
}
you have to add the property Tables to the DataGridView Data Source
dataGridView1.DataSource = table.Tables[0];
if you are using mysql this code you can use.
string con = "SERVER=localhost; user id=root; password=; database=databasename";
private void loaddata()
{
MySqlConnection connect = new MySqlConnection(con);
connect.Open();
try
{
MySqlCommand cmd = connect.CreateCommand();
cmd.CommandText = "SELECT * FROM DATA1";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagrid.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Years late but here's the simplest for others in case.
String connectionString = #"Data Source=LOCALHOST;Initial Catalog=DB;Integrated Security=true";
SqlConnection cnn = new SqlConnection(connectionString);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblEmployee;", cnn);
DataTable data = new DataTable();
sda.Fill(data);
DataGridView1.DataSource = data;
Using DataSet is not necessary and DataTable should be good enough. SQLCommandBuilder is unnecessary either.
I think this professional way to Write from start, but you can use this code with MySQL bout I think they both are the same:
1/
using System.Data; AND using MySql.Data.MySqlClient;
2/
MySqlConnection con = new MySqlConnection("datasource=172.16.2.104;port=3306;server=localhost;database=DB_Name=root;password=DB_Password;sslmode=none;charset=utf8;");
MySqlCommand cmd = new MySqlCommand();
3/
public void SetCommand(string SQL)
{
cmd.Connection = con;
cmd.CommandText = SQL;
}
private void FillGrid()
{
SetCommand("SELECT * FROM `transport_db`ORDER BY `id` DESC LIMIT 15");
DataTable tbl = new DataTable();
tbl.Load(cmd.ExecuteReader());
dataGridView1.DataSource = tbl;
}
for oracle:
var connString = new ConfigurationBuilder().AddJsonFile("AppSettings.json").Build()["ConnectionString"];
OracleConnection connection = new OracleConnection();
connection.ConnectionString = connString;
connection.Open();
var dataAdapter = new OracleDataAdapter("SELECT * FROM TABLE", connection);
var dataSet = new DataSet();
dataAdapter.Fill(dataSet);

Categories

Resources