I am trying to get my Winforms app to query a SQL Server CE database and return all rows that correspond to the column name specified by the user through a drop down list. When I run the programs it will return just a blank dataGrid. This is my first time working with SQL Server CE so any help would be appreciated.
My code is:
private void srchBTN_Click(object sender, EventArgs e)
{
string conString = Properties.Settings.Default.CurricularChangeTrackerConnectionString;
using (SqlCeConnection conn = new SqlCeConnection(conString))
{
string queryString = ("SELECT * FROM SecondaryEducation WHERE ProgramCode='" + PrgmCde.SelectedValue + "'");
try
{
conn.Open();
using (SqlCeDataAdapter adapter = new SqlCeDataAdapter(queryString, conn))
{
DataTable table = new DataTable();
adapter.Fill(table);
dataGridView1.DataSource = table;
adapter.Dispose();
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
If a property is not specified in ValueMember, SelectedValue returns the results of the ToString method of the object.
My point is you may not be getting what you think from the comboBox.
Try this:
string queryString = ("SELECT * FROM SecondaryEducation WHERE ProgramCode='" + PrgmCde.Items[PrgmCde.SelectedIndex].ToString() + "'");
You are declaring the data table inside the using statement, try this
private void srchBTN_Click(object sender, EventArgs e)
{
string conString = Properties.Settings.Default.CurricularChangeTrackerConnectionString;
DataTable table = new DataTable();
using (SqlCeConnection conn = new SqlCeConnection(conString))
{
string queryString = ("SELECT * FROM SecondaryEducation WHERE ProgramCode='" + PrgmCde.SelectedValue + "'");
try
{
conn.Open();
using (SqlCeDataAdapter adapter = new SqlCeDataAdapter(queryString, conn))
{
adapter.Fill(table);
dataGridView1.DataSource = table;
adapter.Dispose();
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
That way the table wont be disposed of when the scope of the using statement is ended.
Related
I'm attempting to update a SQL table from C# project datagridview "Work_Table". However when I attempt to make the update I get this error
"Update unable to find TableMapping ['Work_Table'] or DataTable 'Work_Table'"
Any ideas?
Here is my code below:
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
string query = #"Select * from person.addresstype";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dAdapter.Update(ds, "Work_Table");
MessageBox.Show("Saved");
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
You need to retrieve the DataTable from the .DataSource property of the grid. This will have the information on what was added, updated and deleted.
You can skip the command and pass the select string and connection string directly to the DataAdapter constructor.
Create a CommandBuilder to provide the Insert, Update and Delete text for the DataAdapter.Update. Pass the DataAdapter to the constructor of the CommandBuilder.
private string connString = "Your connection string";
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)dataGridView1.DataSource;
try
{
using (SqlDataAdapter dAdapter = new SqlDataAdapter("Select * from person.addresstype", connString))
using (SqlCommandBuilder cb = new SqlCommandBuilder(dAdapter))
{
dAdapter.Update(dt);
}
MessageBox.Show("Saved");
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
I am trying to load the data from MySQL database where the images are also placed in my table but when the form loads it gives the exception:
Any help would be appreciated
private void DealSuggestion_Load(object sender, EventArgs e)
{
try
{
status.Items.Add("active");
status.Items.Add("inactive");
id.Visible = false;
label7.Text = "";
conn.Open();
MySqlCommand cm = new MySqlCommand();
string query = "SELECT * from dealSuggestion where Status='inactive' LIMIT 8";
cm.CommandText = query;
cm.Connection = conn;
MySqlDataAdapter da = new MySqlDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
DataGridViewImageColumn dgvimgcol = new DataGridViewImageColumn();
Check this out
https://www.c-sharpcorner.com/UploadFile/009464/insert-images-into-datagridview-in-windows-application-using/
Columns in datagridview are consider as string so you need to create an imagecolumn instead of binding it
I have code that checks for unique values when the user updates an ID field, but I am so new I am wondering if there is a better way.
private void tbPrinterID_Validating(object sender, CancelEventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.LazerMaintenance_Conn))
{
try
{
string query = "SELECT COUNT(*) as Count FROM Printers WHERE PrinterID = '" + tbPrinterID.Text + "'";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
DataTable dt = new DataTable();
da.Fill(dt);
if ((Int32)dt.Rows[0]["Count"] > 0)
{
MessageBox.Show("There is already a printer with ID = " + tbPrinterID.Text);
}
}
catch (Exception ex)
{
MessageBox.Show("Error occured! : " + ex);
}
}
}
Your example is vulnerable to SQL injection, I suggest reading this What are good ways to prevent SQL injection?.
You can make the query a bit more idiomatic:
var sql = "SELECT 1 FROM Printers WHERE PrinterID = #IdToCheck";
using (var command = new SqlCommand(sql, con))
{
command.Parameters.AddWithValue("#IdToCheck", tbPrinterID.Text);
con.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
..........
}
}
}
I wanna compare list items in a listbox with with a DataTable column rows named "time" when I select a date in the monthcalendar, Im trying to remove the items in the listbox if they are equal to the values in the column, if not then use the default items I have in the begining. But Iam getting the message: item colection cannot be modified when Datasource property is set. Please help me correct the code:
private void monthCAL_DateChanged(object sender, DateRangeEventArgs e)
{
string date = monthCAL.SelectionStart.Date.ToString("yyyyMMdd");
string connetionString = null;
MySqlConnection connection;
MySqlCommand command;
MySqlDataAdapter adapter = new MySqlDataAdapter();
DataSet ds = new DataSet();
string sql = null;
connetionString = "datasource=localhost; database=bokning;port=3306;username=root;password=666666";
sql = "select day, time from system where day='" + date + "'";
connection = new MySqlConnection(connetionString);
try
{
connection.Open();
command = new MySqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
MyDateT = ds.Tables[0];
if (MyDateT.Rows.Count > 0)
{
foreach (DataRow dr in MyDateT.Rows) {
for (int i = 0; i < MydefaultList.Length; i++)
{
if (MydefaultList[i].ToString().Equals(dr["time"].ToString())) {
listB1.Items.Remove(MydefaultList[i]);
//listB1.DataSource = MydefaultList;
}
}
}
}
else
{
listB1.DataSource = MydefaultList;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
From my understanding you are not able to remove items from a Listbox that have a DataSource property.
This link can describe more in depth:
http://www.codeproject.com/Questions/758161/Items-collection-cannot-be-modified-when-the-DataS
You will need to set the DataSource to null, make the changes you want to make and then re-add the DataSource.
You have to create a new list to store the limited options. Please see the edited code below.
private void monthCAL_DateChanged(object sender, DateRangeEventArgs e)
{
string date = monthCAL.SelectionStart.Date.ToString("yyyyMMdd");
string connetionString = null;
MySqlConnection connection;
MySqlCommand command;
MySqlDataAdapter adapter = new MySqlDataAdapter();
DataSet ds = new DataSet();
string sql = null;
connetionString = "datasource=localhost; database=bokning;port=3306;username=root;password=666666";
sql = "select day, time from system where day='" + date + "'";
connection = new MySqlConnection(connetionString);
try
{
connection.Open();
command = new MySqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
MyDateT = ds.Tables[0];
List<string> limitedList = MyDefaultList; //added line
if (MyDateT.Rows.Count > 0)
{
foreach (DataRow dr in MyDateT.Rows) {
for (int i = 0; i < MydefaultList.Length; i++)
{
if (MydefaultList[i].ToString().Equals(dr["time"].ToString())) {
limitList.Remove(MyDefaultList[i]);
listB1.DataSource = limitedList;
//listB1.Items.Remove(MydefaultList[i]); offending line
//listB1.DataSource = MydefaultList; offending line
}
}
}
}
else
{
listB1.DataSource = MydefaultList;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have 2 tables in MySql (privacy , lawsuit_under_500) ,
In privacy i have 2 columns (id , nameofcase ) ,
In lawsuit_under_500 4 columns(id,nameofcase,priceone,pricetwo) ,
I make a form with a datagridview and i want to execute this query :
select privacy.id,lawsuit_under_500.id,privacy.nameofcase, lawsuit_under_500.priceone, lawsuit_under_500.pricetwo
From privacy inner join lawsuit_under_500
where lawsuit_under_500.id=5 and privacy.id=1 || lawsuit_under_500.id=1 and privacy.id=2 || lawsuit_under_500.id=10 and privacy.id=3
ORDER BY privacy.id
In the form i have:
public Form55()
{
InitializeComponent();
}
private void Form55_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
I have put the tables in my DataSet but I cant figure out how to make it. I tried to make privacyBindingSourse in the datagridview and i added manually 2 buttons for priceone and pricetwo put i cant put the query so i can get the information.
Any ideas/help how to make it ?
BEFORE YOU ANSWER IF YOU HAVE ANY QUESTION PLEASE ASK ME
using MySql.Data.MySqlClient;
MySqlConnection conn = new MySqlConnection("Your MY SQL connection");
MySqlCommand cmd = new MySqlCommand("Your Mysql query");
MySqlDataReader dr=cmd.ExecuteReader();
gridview1.datasource=dr;
gridview1.databind();
// try this also
connectionString = "Your Connection";
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("Your Query", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
//close connection
this.CloseConnection();
}
I made it with this way
private void Form56_Load(object sender, EventArgs e)
{
try
{
MySqlConnection cnn = new MySqlConnection("MY CONNECTION");
cnn.Open();
// - DEBUG
// MessageBox.Show("Connection successful!");
MySqlDataAdapter MyDA = new MySqlDataAdapter();
MyDA.SelectCommand = new MySqlCommand("MY QUERY", cnn);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
Close();
}
}
static public SqlCeConnection OpenSQL()
{
SqlCeConnection cncount = new SqlCeConnection(#"Data Source = " + Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + #"\Database.sdf; Password =''");
return cncount;
}
static public DataTable DoSelect( string strSQL)
{
SqlCeConnection cn = OpenSQL();
DataTable dtRetValue = new DataTable();
using (SqlCeDataAdapter da = new SqlCeDataAdapter())
{
using (SqlCeCommand cmd = cn.CreateCommand())
{
cmd.CommandText = strSQL;
da.SelectCommand = cmd;
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
try
{
//using (SqlCeDataReader reader = da.SelectCommand.ExecuteReader())
SqlCeDataReader metsDr = da.SelectCommand.ExecuteReader();
dtRetValue.Load(metsDr);
return dtRetValue;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error - DoSelect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
return null;
}
}
}
}
Insert in Button
string sql1 = "YOURE QUERY ";
DataTable dt1 = SQLcode.DoSelect(sql1);
dgvcompany.DataSource = dt1;