Properly Loading DataGridView From DataReader - c#

Reading this documentation I was unde the impression that the following code would work:
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.C_Str))
{
try
{
using (SqlCommand cmd = new SqlCommand("PerformSearch", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string SearchString = textBoxSearchSting.Text;
cmd.Parameters.Add("SearchString", SqlDbType.VarChar).Value = SearchString;
con.Open();
dataGridView1.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
}
catch (Exception) { throw; }
finally { con.Close(); }
}
Or that I could atleast use the following:
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.C_Str))
{
try
{
using (SqlCommand cmd = new SqlCommand("PerformSearch", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string SearchString = textBoxSearchSting.Text;
cmd.Parameters.Add("SearchString", SqlDbType.VarChar).Value = SearchString;
con.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
dataGridView1.DataSource = reader;
}
}
catch (Exception) { throw; }
finally { con.Close(); }
}
but niether of the above work. Using the below code does work, with the same search value, is the below the best way to fill my datagridview with my query though? And why won't either of the above work?
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.C_Str))
{
try
{
using (SqlCommand cmd = new SqlCommand("PerformSearch", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string SearchString = textBoxSearchSting.Text;
cmd.Parameters.Add("SearchString", SqlDbType.VarChar).Value = SearchString;
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection));
if (dt.Rows.Count > 0 && dt != null)
{
dataGridView1.DataSource = dt;
}
}
}
catch (Exception) { throw; }
finally { con.Close(); }
}
Below also works, would I be better of using a data adapter, for any reason?
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.C_Str))
{
try
{
using (SqlCommand cmd = new SqlCommand("PerformSearch", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string SearchString = textBoxSearchSting.Text;
cmd.Parameters.Add("SearchString", SqlDbType.VarChar).Value = SearchString;
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
con.Open();
da.Fill(dt);
if (dt.Rows.Count > 0 && dt != null)
{
dataGridView1.DataSource = dt;
}
}
}
}
catch (Exception) { throw; }
finally { con.Close(); }
}

Related

SqlDataAdapter filling with DataTable does not work

I have this code running in form_load event:
using (SqlConnection sqlConn = new SqlConnection(strConn))
{
sqlConn.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("pp_sp_MachineAndOp", sqlConn);
DataTable sqlDt = Helper.ExecuteDataTable("pp_sp_MachineAndOp", new SqlParameter("#MachineAndOpID", 7));
sqlDa.Fill(sqlDt);
dgvMachineAndOp.AutoGenerateColumns = false;
dgvMachineAndOp.DataSource = sqlDt;
sqlDa.Dispose();
sqlConn.Close();
}
I get error 'Procedure or function 'pp_sp_MachineAndOp' expects parameter '#MachineAndOpID', which was not supplied.' at line:
sqlDa.Fill(sqlDt);
Important to say that if I open DataTable Visualizer of sqlDt at runtime I see expected results!
Here is a code behind Helper.ExecuteDataTable:
public static DataTable ExecuteDataTable(string storedProcedureName, params SqlParameter[] arrParam)
{
DataTable dt = new DataTable();
// Open the connection
using (SqlConnection sqlConn = new SqlConnection(strConn))
{
try
{
sqlConn.Open();
// Define the command
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcedureName;
// Handle the parameters
if (arrParam != null)
{
foreach (SqlParameter param in arrParam)
{
sqlCmd.Parameters.Add(param);
}
}
// Define the data adapter and fill the dataset
using (SqlDataAdapter da = new SqlDataAdapter(sqlCmd))
{
da.Fill(dt);
}
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return dt;
}
What I am missing?
Remove everything except
DataTable sqlDt = Helper.ExecuteDataTable("pp_sp_MachineAndOp", new SqlParameter("#MachineAndOpID", 7));
dgvMachineAndOp.AutoGenerateColumns = false;
dgvMachineAndOp.DataSource = sqlDt;
your Helper.ExecuteDataTable is doing everything. you don't need to replicate same this in your code.
I think your helper class is creating connection with database as your data table has data.
So, try to remove stored proc name and connection object from adaptor and then check.
SqlDataAdapter sqlDa = new SqlDataAdapter();//use this only.
you can use below function(modification required as per your need):
public IDataReader ExecuteReader(string spName, object[] parameterValues)
{
command = GetCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = spName;
if (parameterValues != null)
{
for (int i = 0; i < parameterValues.Length; i++)
{
command.Parameters.Add(parameterValues[i]);
}
}
reader = command.ExecuteReader();
if (parameterValues != null)
command.Parameters.Clear();
return reader;
}

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.

How to display same format repeater for each row that has the same cell value

I have 50 different format repeaters. Each has to be bind according to the state.
I created a gridview with checkboxes. Whichever rows are checked to display those rows data in the corresponding repeater.
I am sending to the stored procedure multiple parameter and return a datatable. I loop through the datatable and on button click I get all repeaters except when the state is the same - it returns only the last one. I debug and the code runs through it but overwrites the previous row that had that state. How can I display all repeaters for the same state?
protected void GetVinData()
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["DBConnection"]);
SqlCommand cmmd = new SqlCommand();
cmmd.CommandType = CommandType.StoredProcedure;
cmmd.CommandText = c
cmmd.Connection = cn;
cn.Open();
try
{
cmmd.Parameters.Add("#POLICY", SqlDbType.VarChar);
cmmd.Parameters["#POLICY"].Value = ddlPolicy.SelectedValue;
cmmd.Parameters.Add("#VIN", SqlDbType.VarChar);
cmmd.Parameters["#VIN"].Value = txtMsg.Value;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmmd);
adapter.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["DBConnection"]);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetAllVinNumbers";
cmd.Connection = conn;
cmd.Parameters.Add("#POLICY", SqlDbType.VarChar);
cmd.Parameters["#POLICY"].Value = ddlPolicy.SelectedValue;
cmd.Parameters.Add("#VIN", SqlDbType.VarChar);
cmd.Parameters["#VIN"].Value = dr["VIN"].ToString();
if (dr["STATE"].ToString() == "AL")
{
try
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
Repeater_AL.DataSource = cmd.ExecuteReader();
Repeater_AL.DataBind();
Repeater_AL.Visible = true;
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.Visible = true;
}
finally
{
conn.Close();
conn.Dispose();
}
}
else if (dr["STATE"].ToString() == "AK")
{
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
Repeater_AK.DataSource = cmd.ExecuteReader();
Repeater_AK.DataBind();
Repeater_AK.Visible = true;
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.Visible = true;
}
finally
{
conn.Close();
conn.Dispose();
}
}
else if (dr["STATE"].ToString() == "AZ")
{
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
Repeater_AZ.DataSource = cmd.ExecuteReader();
Repeater_AZ.DataBind();
Repeater_AZ.Visible = true;
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.Visible = true;
}
finally
{
conn.Close();
conn.Dispose();
if (Repeater_AZ.Visible == true)
{
Repeater_AZ.Visible = true;
}
}
} ... and so on for 50 states
This slight refactoring may help:
protected void BindVin(string state)
{
Repeater rpt = null;
Control ctl = null;
string name = string.Empty;
SqlConnection conn = null;
SqlCommand cmd = null;
name = "Repeater_" + state;
ctl = Page.FindControl(name);
rpt = ctl as Repeater;
if (rpt != null) {
try {
conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings("DBConnection"));
cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetAllVinNumbers"; // should this have the state to get VINs for?
cmd.Connection = conn;
cmd.Parameters.Add("#POLICY", SqlDbType.VarChar);
cmd.Parameters("#POLICY").Value = ddlPolicy.SelectedValue;
cmd.Parameters.Add("#VIN", SqlDbType.VarChar);
cmd.Parameters("#VIN").Value = dr("VIN").ToString();
if (conn.State != ConnectionState.Open) {
conn.Open();
}
rpt.DataSource = cmd.ExecuteReader();
rpt.DataBind();
rpt.Visible = true;
conn.Close();
conn.Dispose();
} catch (Exception ex) {
lblMessage.Text = ex.Message;
lblMessage.Visible = true;
} finally {
conn.Close();
conn.Dispose();
}
}
}
protected void GetVinData()
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["DBConnection"]);
SqlCommand cmmd = new SqlCommand();
cmmd.CommandType = CommandType.StoredProcedure;
cmmd.CommandText = c
cmmd.Connection = cn;
cn.Open();
try
{
cmmd.Parameters.Add("#POLICY", SqlDbType.VarChar);
cmmd.Parameters["#POLICY"].Value = ddlPolicy.SelectedValue;
cmmd.Parameters.Add("#VIN", SqlDbType.VarChar);
cmmd.Parameters["#VIN"].Value = txtMsg.Value;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmmd);
adapter.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
BindVin(dr["STATE"].ToString());
}
}
}

SQL Server connection in WPF

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);
}
}
}

Categories

Resources