I have question about my problem. Thru manustrip in form1 i have made new form2 when i click on a right option. This form is for deleting data in access database if you pick in combobox ID of row it deletes the whole row wher is ID 4 or somethig else... My combobox is connected on my database.
my code:
public partial class Form2 : Form
{
public string myConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Bojan\Desktop\Programiranje\School\Novo\Novo\Ure.accdb"; // to je provider za Access 2007 in več - če ga ni na lokalni mašini ga je treba namestiti!!!
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dataSet1.Ure' table. You can move, or remove it, as needed.
this.ureTableAdapter.Fill(this.dataSet1.Ure);
}
private void Brisanje_Click(object sender, EventArgs e)
{
OleDbConnection myConnection = null;
myConnection = new OleDbConnection(); // kreiranje konekcije
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
OleDbCommand cmd = myConnection.CreateCommand();
cmd.Connection = myConnection;
cmd.CommandText = "DELETE FROM Ure WHERE (ID) = '"+Izbor.SelectedValue+"'";
cmd.ExecuteNonQuery();
cmd.Prepare();
myConnection.Close();
}
}
Thanks for your help
As #musefan pointed out, you should really be using parameterised queries, the other issue seems to be the single quotes around ID which will result in a data type mismatch error. Finally, your connection and command objects implement IDisposable so I would recommend wrapping them in a using block.
The following code should work
using (var myConnection = new OleDbConnection(myConnectionString))
using (var myCommand = myConnection.CreateCommand())
{
var idParam = new OleDbParameter("#id", Izbor.SelectedValue);
myCommand.CommandText = "DELETE FROM Ure WHERE (ID) = #id";
myCommand.Parameters.Add(idParam);
myConnection.Open();
myCommand.ExecuteNonQuery();
}
Related
When selecting a line for deletion, these errors appear, what is the problem?
enter image description here
private void button3_Click(object sender, EventArgs e)
{
con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\desk\new\abusalem\abusalem\Database1.mdf;Integrated Security=True");
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "delete from datauser where id= "+dataGridView1.CurrentRow.Cells[0].Value;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
filltable();
}
Here is a conceptual path to follow. The example is setup for a DataTable, if not using a DataTable but not setting the DataGridView.DataSource consider what is shown below. There is no need to reload the DataGridView once a row has been removed.
Setup a BindingSource scoped form level, set the DataSource to what you are using to populate the DataGridView currently e.g. a Datatable then dataGridView1.DataSource = someBindingSource. Set the primary key column to hidden so it is not seen.
If no primary key than adjust dataGridView1.CurrentRow.Cells[0].Value the code below to accept that value.
To remove a row, in the button click event. Here I have Id as the key.
public class Operations
{
private static string _connectionString =
#"Data Source=(LocalDB)\MSSQLLocalDB;" +
#"AttachDbFilename=E:\desk\new\abusalem\abusalem\Database1.mdf;" +
"Integrated Security=True";
public static bool Remove(int id)
{
using (var cn = new SqlConnection(_connectionString))
{
using (var cmd = new SqlCommand() {Connection = cn})
{
cmd.CommandText = "delete from datauser where id=#Id";
cmd.Parameters.Add("#Id", SqlDbType.Int).Value = id;
return cmd.ExecuteNonQuery() == 1;
}
}
}
}
Form code
private BindingSource someBindingSource = new BindingSource();
private void RemoveButton_Click(object sender, EventArgs e)
{
DataRow row = ((DataRowView)someBindingSource.Current).Row;
if (Operations.Remove(row.Field<int>("id")))
{
someBindingSource.RemoveCurrent();
}
}
In the future provide enough code so we have a idea what exactly is being done in regards to how the DataGridView gets loaded.
I'm fairly new to C# and coding in general. I've looked through similar questions and didn't have much luck fixing this.
I am making an app that stores Student details for attendance in tables, in a database. Currently when I run it, the details are added to the tables from textboxes. A button opens a separate form with a datagridview, but the details are not updated in this. If I rerun the application and open the second form, the datagridview has been updated. How do I get the datagridview to update based on information added to the table while the application is running?
This is the code that adds the details to the table
using (SqlConnection sc = new SqlConnection())
{
sc.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\corry\Desktop\StudentAttendanceBurton\Attendance.mdf;Integrated Security=True";
sc.Open();
using (SqlCommand com = sc.CreateCommand())
{
com.CommandText =
"insert into BUS102(\n" +
" Name,\n" +
" [Student ID],\n" +
" Date)\n" +
"values(\n" +
" #prm_Name,\n" +
" #prm_Student_ID,\n" +
" #prm_Date)";
com.Parameters.Add("#prm_Name", SqlDbType.NVarChar, 50).Value = student.Name;
com.Parameters.Add("#prm_Student_ID", SqlDbType.Int).Value = student.StudentID;
com.Parameters.Add("#prm_Date", SqlDbType.SmallDateTime).Value = student.Date;
com.ExecuteNonQuery();
}
}
This is the code for the form that has the datagridview
public partial class AttendanceForm : Form
{
public AttendanceForm()
{
InitializeComponent();
}
private void bUS102BindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.bUS102BindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.attendanceDataSet);
}
private void AttendanceForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'attendanceDataSet.BUS102' table. You can move, or remove it, as needed.
this.bUS102TableAdapter.Fill(this.attendanceDataSet.BUS102);
}
}
public partial class Form1 : Form {
private DataSet m_ds = new DataSet();
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
using (SqlConnection conn = new SqlConnection(#"Data Source=YOURSql;Initial Catalog=YOURDB;Integrated Security=True")) {
// set command
SqlCommand cmd = new SqlCommand("SELECT * FROM YourTable", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
da.Fill(m_ds);
// bind data to dataGrid
dataGridView1.DataSource = m_ds.Tables[0];
// refresh Data
dataGridView1.Refresh();
conn.Close();
}
}
private void cmdChangeData_Click(object sender, EventArgs e) {
// add new row explicit
DataRow nr = m_ds.Tables[0].NewRow();
nr[0] = "0000";
nr[1] = "xxxx";
// add new row to DataSet (just in memory, NOT TO DB)
m_ds.Tables[0].Rows.Add(nr);
// Refresh Data
dataGridView1.Refresh();
}
}
You have to refresh datagridview
this.dataGridView1.Refresh();
So I'm trying to create sort of an overview utility of sites, with different infos on each site.
I'd like to have a dropdown list / combobox, reading a sqldb and create items according to the db. Then I would like different textboxes to get populated with a value from a column.
Say my db table is called "AvSites" so far (just for the sake of it) i have "projectNr", "siteName", "siteClients" and "siteLicenses" columns I'd like each of these to populate some textbox / label somewhere.
I've tried the following, which kinda works, Ive had the code working most of the time, but the thing that defeats me is having the data change with the combobox item selected.
I hope you can help, and so here is my code so far (I have a login window, before this "main" program starts, just so you're not wondering)
And I'm quite new to C# so if there's something thats done inefficient thats the reason :) Im still learning.
namespace AvOverview{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
//btn_LogOut Click Event
this.Hide();
Form1 fl = new Form1();
fl.Show();
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void FrmMain_Load(object sender, EventArgs e)
{
string cs = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf";
SqlConnection con = new SqlConnection(cs);
con.Open();
string strCmd = "select * from AvSites";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
combo1.ValueMember = "id";
combo1.DisplayMember = "siteName";
combo1.DataSource = ds.Tables[0];
combo1.Enabled = true;
this.combo1.SelectedIndex = -1;
cmd.ExecuteNonQuery();
con.Close();
}
private void Combo1_SelectedIndexChanged(object sender, EventArgs e)
{
string cs = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf";
string strCmd = "select id from AvSites";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(strCmd, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{//this last part is solely for testing if the text changed the way I wanted.
label1.Text = dr.GetValue(1).ToString();
label2.Text = dr.GetValue(2).ToString();
label3.Text = dr.GetValue(0).ToString();
label4.Text = dr.GetValue(3).ToString();
You don't need to call the database again. All the info are in the current selected item.
When you set the DataSource of your combo to a datatable like you do in the click event each element of the combo is a DataRowView and from this element you can get all the info extracted from the database from your initial query
private void Combo1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView rv = Combo1.SelectedItem as DataRowView;
if(rv != null)
{
label1.Text = rv[1].ToString();
label2.Text = rv[2].ToString();
label3.Text = rv[0].ToString();
label4.Text = rv[3].ToString();
}
}
Side note: There are some improvements needed in your code.
First you should store the connection string in the config file and read it back with the ConfigurationManager class. Read about Configuration in NET
Second you shouldn't work with disposable objects like you do now. A disposable object should be disposed as soon as you have finished to use it. In particular the SqlConnection keeps valuable system resources both on your machine and on the server. You should start to use the using statement
string strCmd = "select * from AvSites";
using(SqlConnection con = new SqlConnection(.......))
using(SqlCommand cmd = new SqlCommand(strCmd, con)))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
combo1.ValueMember = "id";
combo1.DisplayMember = "siteName";
combo1.DataSource = ds.Tables[0];
combo1.Enabled = true;
this.combo1.SelectedIndex = -1;
// ??? not needed ==> cmd.ExecuteNonQuery();
// not needed with using ==> con.Close();
}
// Here the connection is closed and disposed and resources are released
Hi im trying to insert data into my DataBase. The program runs but it never save the values!!.
heres the code:
using System.Data.SqlClient;
namespace Database_1._0
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"DataSource=LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Luis\documents\visual studio 2015\Projects\Database_1._0\Database_1._0\DB.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
DateTime dateTime = DateTime.UtcNow.Date;
string user = "1614258779876465426";
string pass = "3Cp5CeXrfghdfght";
string frecuencyCode = "ANNUAL";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void logo_Click(object sender, EventArgs e)
{
MessageBox.Show("Database_1._0 \nWritten by: Luis", "About");
}
private void button1_Click(object sender, EventArgs e)
{
cn.Open();
using (SieteWS SieteWS = new SieteWS())
{
Respuesta respuesta = SieteWS.SearchSeries(user, pass, frecuencyCode);
foreach (internetSeriesInfo seriesInfo in respuesta.SeriesInfos)
{
cmd.CommandText = "INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency]) VALUES (#SerieID, #SerieName, #SerieFrecuency)";
cmd.Parameters.AddWithValue("#SerieID", seriesInfo.seriesId);
cmd.Parameters.AddWithValue("#SerieName", seriesInfo.spanishTitle);
cmd.Parameters.AddWithValue("#SerieFrecuency", seriesInfo.frequency);
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
}
}
and the Error says:
errorCS0103: The name 'CommandText' does not exist in the current context. And when I use a watch I found out this: cmd.CommandText =""; . Can somebody tell me what im doing wrong please.?
So first of all. move cn.Close(); outside of the loops. If it's not the cause for your problem now, it will cause a problem later.
If that doesn't fix your problem look further.
It's just a poke in the dark given the information I have, but try running following code sets (inside foreach loop) and see if any of them work:
set 1:
cmd = new SqlCommand("INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency])
VALUES ('"+seriesInfo.seriesId+"', '"+seriesInfo.spanishTitle+"'
, '"+seriesInfo.frequency+"')", cn);
cmd.ExecuteNonQuery();
set 2:
cmd = new SqlCommand("INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency])
VALUES (#SerieID, #SerieName, #SerieFrecuency)", cn);
cmd.Parameters.AddWithValue("#SerieID", seriesInfo.seriesId);
cmd.Parameters.AddWithValue("#SerieName", seriesInfo.spanishTitle);
cmd.Parameters.AddWithValue("#SerieFrecuency", seriesInfo.frequency);
Let me know how it works out
Try this...
Modify the line below to include the name of the database. So that it will read [Your database Name].[dbo].[Serie]
cmd.CommandText = "INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency]) VALUES (#SerieID, #SerieName, #SerieFrecuency)";
Your default database may not be the one that has your "Serie" table in it.
Im trying to build up a little status-tool. I need to get results of multiple queries (about 4-5). The general connection-setup and 'how-to-read-data' is already done but I cant figure out how the another query executed.
Everything I found while searching for it is for the SqlClient. Im totally overcharged with this.
Here is my code so far (be patient, im a newbie to this):
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
// SQL PART //
string connString = "Server=10*****;Port=3306;Database=e***;Uid=e***;password=********************;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC";
try
{
conn.Open();
}
catch (Exception ex)
{
listView1.Items.Add("Error: " + ex);
}
MySqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
listMember.Add(reader["fullname"].ToString());
listOnline.Add(reader["online"].ToString());
}
conn.Close();
// SQL ENDING //
// SET ENTRIES TO LISTVIEW //
int counter = 0;
foreach(string member in listMember)
{
ListViewItem item = new ListViewItem(new[] { member, listOnline.ElementAt(counter) });
item.ForeColor = Color.Green;
listView1.Items.Add(item);
counter++;
}
}
Im not really sure how the design/layout will look like in the end, so I would like to just append the results to lists in the sql-part to process the data later out of the lists.
Do I really have to setup a complete new connection after conn.Close()? Or is there any other way? I can just imagine: 5 queries with their own connection,try,catch and 2 loops... this will get about 100-200 lines just for getting the results out of 5 queries. Isnt that a bit too much for such an easy thing?
Hope for some help.
Greetings.
According to the new comments my latest code:
Top:
public partial class Form1 : Form
{
public static string connString = "Server=10****;Port=3306;Database=e****;Uid=e****;password=****;";
public Form1()
{
InitializeComponent();
MySqlConnection conn = new MySqlConnection(connString); // Error gone!
}
Body part:
public void QueryTwoFields(string s, List<string> S1, List<string> S2)
{
try
{
MySqlCommand cmd = conn.CreateCommand(); // ERROR: conn does not exist in the current context.
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
S1.Add(sqlreader[0].ToString());
S2.Add(sqlreader[1].ToString());
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
using (conn) // ERROR: conn does not exist in the current context.
{
conn.Open();
///...1st Query
QueryTwoFields("SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC",listMember,listOnline);
//...2nd query
//QueryTwoFields("your new Select Statement", otherList, otherList);
}
}
You don't have to close connection every time you execute one query rarher than close the sqlreader assigned to that connection. Finally when all of your queries have been executed you close the connection. Consider also the use of using:
You cal also define a method for execution your Query in order for your code not to be repetive:
public void QueryTwoFields(string s, List<string> S1, List<string> S2)
///Select into List S1 and List S2 from Database (2 fields)
{
try
{
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
S1.Add(sqlreader[0].ToString());
S2.Add(sqlreader[1].ToString());
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
// SQL PART //
using (conn)
{
conn.Open();
///...1st Query
QueryTwoFields("SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC",listmember,listonline)
//...2nd query
QueryTwoFields("your new Select Statement",myOtherList1,myOtherlist2)
....
}
}
EDIT :
Take in mind you cant define QueryTwoFields method inside button handler. You must define it outside (see code above).
Also Define your connection data in the start of the programm:
namespace MyProject
{
/// <summary>
/// Defiine your connectionstring and connection
/// </summary>
///
public partial class Form1 : Form
{ public static string connString = "Server=10*****;Port=3306;Database=e***;Uid=e***;password=********************;";
MySqlConnection conn = new MySqlConnection(connString);
.........
Datatables are fantastic
Using a data table is a nice way to do both read and write. And it comes with the luxury of eveything you can do with a datatable - like asssigning it directly to a datagrid control, sorting, selecting and deleting while disconnected.
The sample below assumes a MySqlConnection conection property managed by calls to your own OpenConnection() and CloseConnection() methods not shown.
Simple datatable read demo:
public DataTable Select(string query = "")
{
//Typical sql: "SELECT * FROM motorparameter"
DataTable dt = new DataTable();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
dt.Load(dataReader);
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return data table
return dt;
}
else
{
return dt;
}
}
In case of writing back the datatable to the database - supply the SQL you used in the read (or would have used to read to the data table):
public void Save(DataTable dt, string DataTableSqlSelect)
{
//Typically "SELECT * FROM motorparameter"
string query = DataTableSqlSelect;
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand mySqlCmd = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(mySqlCmd);
MySqlCommandBuilder myCB = new MySqlCommandBuilder(adapter);
adapter.UpdateCommand = myCB.GetUpdateCommand();
adapter.Update(dt);
//close Connection
this.CloseConnection();
}
else
{
}
}
The neat thing the datatable is extremely flexible. You can run your own selects against the table once it contains data and before writing back you can set or reset what rows needs updating and by default the datatable keeps track of what rows you update in the table. Do not forget primary key column(s) for all tables in the db.
For multiple queries consider if possible using a join between the database tables or same table if data related or use a UNION sql syntax if column count and type of data is the same. You can allways "create" your extra column in the select to differ what data comes from what part of the UNION.
Also consider using CASE WHEN sql syntax to conditionally select data from different sources.