Change database connection and update datagridview - c#

I'm trying to display the database records after changing connection string data source. Here's my code:
m_dbConnection = new SQLiteConnection("Data Source=" + connFile + "; Version=3; FailIfMissing=True; Foreign Keys=True;");
getTable("SELECT * FROM tbl_programs WHERE int_is" +
lastDisplayedBuild.ToString() +
"=1 ORDER BY txt_programName;");
And my global variables are:
private SQLiteConnection m_dbConnection;
private SQLiteDataAdapter sqliteDataAdapter = new SQLiteDataAdapter();
private DataTable dataTable = new DataTable();
private BindingSource bindingSource = null;
How can I display new records in datagridview?

used this function to
public DataTable getData(string sqlCommand)
{
DataTable dt = new DataTable();
using (var con = new SQLiteConnection { ConnectionString = "your connection string" })
{
using (var command = new SQLiteCommand { Connection = con })
{
if (con.State == ConnectionState.Open)
con.Close();
con.Open();
command.CommandText = sqlCommand;
dt.Load(command.ExecuteReader());
}
return dt;
}
}
//Call to load your Data
public void loadData()
{
this.DatagridView.DataSource = getData("Command string here");
}

Related

Why do I get the error "Cannot Implicitly convert type 'Form.QueryExecute' to 'string'." when creating a DB connection in C#?

I'm trying to architect the structure of code for a DB connection. I've created a class which I called 'DbConn.cs':
class DbConn
{
public SqlConnection getDbConnection()
{
String connectionString = "Data Source=172.26.187.34, 1181;Initial Catalog=LoansDev;User ID=AppUser;Password=Passw0rd";
SqlConnection conn = new SqlConnection(connectionString);
return conn;
}
public bool isConnectionEstablish()
{
try
{
getDbConnection();
return true;
}
catch(Exception e)
{
return false;
}
}
}
Now every time I try to execute a query I'll just call the class DbConn conn = new DbConn(); then I'll use the conn.getDbConnection().open() to open and connection and vice versa. I don't know if it's a proper way of handling connections since all tutorials I've seen is the handler for connection is also where the query is being executed.
Now I have a class 'QueryExecute.cs' which will hold all my queries.
The problem is if try to call the method on my form, I always get the error
"Cannot Implicitly convert type 'Form.QueryExecute' to 'string'.
Here is the code for my form:
StatusViewForm.cs:
private void StatusViewForm_Load(object sender, EventArgs e)
{
// frmLogin loginForm = new frmLogin();
//String loggedUser = loginForm.getUserID;
//MessageBox.Show(LoggedUser, "Who is logged in?", MessageBoxButtons.OK);
QueryExecute taskEmp = new QueryExecute();
DbConn dbConn = new DbConn();
DataTable dt = new DataTable();
String userID = taskEmp.getEmployeeDetails(userID: LoggedUser);
String query = taskEmp.getTaskDetails(LoggedUser);
//MessageBox.Show(query, "Query", MessageBoxButtons.OK);
SqlDataAdapter da = new SqlDataAdapter(query, dbConn.getDbConnection());
dbConn.getDbConnection().Open();
da.Fill(dt);
dbConn.getDbConnection().Close();
dgvTaskView.DataSource = dt;
}
Then here is my QueryExecute.cs:
public QueryExecute getEmployeeDetails(String userID)
{
DataTable empDetails = new DataTable("EmployeeDetails");
QueryExecute empInfo = new QueryExecute();
DbConn conn = new DbConn();
using (conn.getDbConnection())
{
String query = "SELECT * FROM dbo.Employee WHERE UserID = '" + userID + "'";
SqlCommand cmd = new SqlCommand(query, conn.getDbConnection());
cmd.Parameters.AddWithValue("#UserID", userID);
conn.getDbConnection().Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(empDetails);
if(empDetails.Rows.Count > 0)
{
empInfo.UserID = (string)empDetails.Rows[0]["UserID"];
empInfo.Name = (string)empDetails.Rows[0]["Name"];
empInfo.IsAdmin = (bool)empDetails.Rows[0]["IsAdmin"];
}
conn.getDbConnection().Close();
}
return empInfo;
}
I'm wondering if it's my DbConn class that is causing the problem...

Is there a way to save dataRow as strings even though some datatypes are different in database

I am getting data as text from the spreadsheet ,but when i try to save it i get 'Failed to convert parameter value from a String to a Double.'
public void TableSaveImportedData(DataTable dataTable)
{
string tableName = "Cable";
using (OleDbConnection oleDbConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\1Des\\SampleProjects\\SampleProj01\\SampleProj01.MDB"))
{
oleDbConnection.Open();
using (OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter())
{
using (OleDbCommand dbCommand = new OleDbCommand("select * from "+ tableName ,oleDbConnection ))
{
oleDbDataAdapter.SelectCommand = dbCommand;
using (OleDbCommandBuilder oleDbCommandBuilder = new OleDbCommandBuilder(oleDbDataAdapter))
{
oleDbDataAdapter.InsertCommand = oleDbCommandBuilder.GetInsertCommand();
DataSet dataSet = new DataSet();
oleDbDataAdapter.Fill(dataSet ,tableName);
oleDbCommandBuilder.RefreshSchema();
oleDbDataAdapter.Update(dataTable);
dataTable.AcceptChanges();
XtraMessageBox.Show("Successfully Saved");
}
}
}
}

Fill datagridview with SQL Server table data

I'm trying to fill a datagridview with SQL Server table data and I get an error:
ExecuteReader: Connection property has not been initialized.
How do I fix this ?
private void BlackListLoad()
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
BindingSource bs = new BindingSource();
var table = dt;
var connection =
#"Data Source=someone-someone\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
using (var con = new SqlConnection { ConnectionString = connection })
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.CommandText = #"SELECT * FROM [dbo].[Blacklist1]";
table.Load(cmd.ExecuteReader());
bs.DataSource = table;
ListGrid.ReadOnly = true;
ListGrid.DataSource = bs;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
You haven't given your SqlCommand a connection! As it states you need to do this. You can fix this by doing:
cmd.Connection = con; just before you execute the reader.
Read here for more information: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.connection(v=vs.110).aspx
It also looks like you're not opening your connection, which can be fixed with:
con.Open();
With a new connection object, you do not need to check whether it's open, because it won't be.
Try it this way.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
}
}

How to add the same value to a datatable from excel?

private void btnSelectFile_Click(object sender, EventArgs e)
{xxxxxxxxxxxxxxxxxxx
}
private void btnUpload_Click(object sender, EventArgs e)
{
string path = txtfilepath.Text;
string ConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
DataTable Data = new DataTable();
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(#"SELECT * FROM [Inventory List (HK)$]", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(Data);
conn.Close();
}
string ConnStr = MyConString;
using (SqlBulkCopy sqlBC = new SqlBulkCopy(ConnStr))
{
sqlBC.DestinationTableName = "dbo.InventoryList";
sqlBC.ColumnMappings.Add("User ID", "username");
sqlBC.ColumnMappings.Add("User Name", "username");
sqlBC.ColumnMappings.Add("Remarks", "remarks");
sqlBC.WriteToServer(Data);
}
Data.Columns.Add("InventoryListType", typeof(System.String));
foreach (DataRow row in Data.Rows)
{
row["InventoryListType"] = "HK";
}
MessageBox.Show("UPLOAD SUCCESSFULLY");
}
}
}
I build a windows Forms Application with 3 buttons and I already have a column name call InventoryListType in my datatable, I want to add a value "HK" in every row in sheet Inventory List and in column InventoryListType, but I cannot do this and my code is above. How to solve this problem?

Updating table with SqliteDataAdapter

I have a bit of an issue when it comes to updating view in datagridview. My function successfully deletes selected row from database but DataAdapter does not fill datatable dt. Function with the same structure works perfectly when adding rows.
private string ConString;
private SQLiteCommand cmd;
DataTable dt = new DataTable();
SQLiteConnection sql_con;
SQLiteDataAdapter DB;
// Function to delete rows
public void DeleteRow(string value)
{
string sqlStatement = "DELETE FROM Trades WHERE ID = " + value;
try
{
sql_con = new SQLiteConnection(ConString);
sql_con.Open();
cmd = sql_con.CreateCommand();
cmd.CommandText = sqlStatement;
cmd.ExecuteNonQuery();
DB = new SQLiteDataAdapter();
dt.Clear();
DB.Fill(dt);
}
finally
{
sql_con.Close();
}
}

Categories