What am I doing wrong here? I am trying to display data from a remote database and inserting,editing, and deleting data. The database that I am connecting to is a remote which I was successfully able to connect and view the information however when I insert the syntax to edit the data I get an error (see bottom of the post).
I am using Devexpress Scheduler Controller to view appointments as well edit them.
This is the entire code.
public partial class MainWindow : Window
{
CarsDBDataSet dataSet;
public MainWindow()
{
InitializeComponent();
intSchedular();
}
private void intSchedular()
{
schudlerControl1.Storage.AppointmentStorage.Mappings.AllDay = "AllDay";
schudlerControl1.Storage.AppointmentStorage.Mappings.Description = "Description";
schudlerControl1.Storage.AppointmentStorage.Mappings.End = "EndTime";
schudlerControl1.Storage.AppointmentStorage.Mappings.Label = "Label";
schudlerControl1.Storage.AppointmentStorage.Mappings.Start = "StartTime";
schudlerControl1.Storage.AppointmentStorage.Mappings.Location = "Location";
schudlerControl1.Storage.AppointmentStorage.Mappings.ReminderInfo = "RemindderInfo";
schudlerControl1.Storage.AppointmentStorage.Mappings.Subject = "Subject";
schudlerControl1.Storage.AppointmentStorage.Mappings.Status = "Status";
schudlerControl1.Storage.AppointmentStorage.Mappings.Type = "EventType";
schudlerControl1.Storage.AppointmentStorage.Mappings.RecurrenceInfo = "RecurrenceInfo";
System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection()
{
ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" + #"Data source= \\UNDERFOOT-PC\CalUnderFootDB\CarsDB.mdb"
};
con.Open();
OleDbCommand createCommand = new OleDbCommand("select * from CarScheduling", con);
createCommand.ExecuteNonQuery();
OleDbDataAdapter adapter = new OleDbDataAdapter(createCommand);
CarsDBDataSet dataSet = new CarsDBDataSet();
// Bind the scheduler storage to appointment data.
schudlerControl1.Storage.AppointmentStorage.DataSource = dataSet.CarScheduling;
// Load data into the 'CarsDBDataSet.CarScheduling' table.
adapter.Fill(dataSet.CarScheduling);
schudlerControl1.Storage.AppointmentsInserted +=
new PersistentObjectsEventHandler(Storage_AppointmentsModified);
schudlerControl1.Storage.AppointmentsChanged +=
new PersistentObjectsEventHandler(Storage_AppointmentsModified);
schudlerControl1.Storage.AppointmentsDeleted +=
new PersistentObjectsEventHandler(Storage_AppointmentsModified);
adapter.Adapter.RowUpdated +=
new System.Data.OleDb.OleDbRowUpdatedEventHandler(adapter_RowUpdated);
}
void Storage_AppointmentsModified(object sender, PersistentObjectsEventArgs e)
{
adapter.Adapter.Update(dataSet);
this.dataSet.AcceptChanges();
}
private void adapter_RowUpdated(object sender, System.Data.OleDb.OleDbRowUpdatedEventArgs e)
{
if (e.Status == UpdateStatus.Continue && e.StatementType == StatementType.Insert)
{
int id = 0;
using (OleDbCommand cmd = new OleDbCommand("SELECT ##IDENTITY", adapter.Connection))
{
id = (int)cmd.ExecuteScalar();
}
e.Row["ID"] = id;
}
}
}
The error I am getting is from the word adapter from "void Storage_AppointmentsModified" saying "the name 'adapter' does not exist in the current context". I know I have to define adapter but how? I am new to C# so I am not "fluent" with writing C# syntax.
You have defined the adapter variable inside the intSchedular method. But this variable is local to that method and cannot be used outside of it (It will be destroyed when you exit from intSchedular)
To be able to use the variable in Storage_AppointmentsModified, you need to define it at the global class scope like you already do with the CarsDBDataSet
public partial class MainWindow : Window
{
CarsDBDataSet dataSet;
OleDbDataAdapter adapter;
.....
private void intSchedular()
{
.....
adapter = new OleDbDataAdapter(createCommand);
.....
}
void Storage_AppointmentsModified(object sender, PersistentObjectsEventArgs e)
{
this.adapter.Update(dataSet);
this.dataSet.AcceptChanges();
}
Another thing to fix in your code is the Handling of the connection. A Connection should be used following a precise pattern. Create, Open, Use, Close and Destroy. You should be using the using statement in your intSchedular to be sure of the destruction of the connection
private void intSchedular()
{
// CREATE
using(OleDbConnection con = new OleDbConnection(... con string here....))
using(OleDbCommand createCommand = new OleDbCommand("select * from CarScheduling", con))
{
// OPEN
con.Open();
// NO USING HERE BECAUSE WE WANT THE ADAPTER OUTSIDE OF THIS METHOD
adapter = new OleDbDataAdapter(createCommand);
// USE
....
adapter.Fill(dataSet.CarScheduling);
....
} // CLOSE + DISPOSE
}
The same thing should be done in the adapter_RowUpdated
private void adapter_RowUpdated(object sender, System.Data.OleDb.OleDbRowUpdatedEventArgs e)
{
if (e.Status == UpdateStatus.Continue && e.StatementType == StatementType.Insert)
{
int id = 0;
using (OleDbConnection con = new OleDbConnection( .... con string here ....))
using (OleDbCommand cmd = new OleDbCommand("SELECT ##IDENTITY", con))
{
con.Open();
id = (int)cmd.ExecuteScalar();
}
e.Row["ID"] = id;
}
}
Related
this is my code
i have tried every step i can find
i have moved con.close(); before and after it is still not working
please guide me to what to do
thank you
I am following this youtube video to make the crud operation https://www.youtube.com/watch?v=C7ukAjQtsxE
using System.Data;
using System.Data.SqlClient;
namespace crudingtime
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=DESKTOP-6381H14\\SQLEXPRESS;Initial Catalog=yarabthis;Integrated Security=True");
private void Form1_Load(object sender, EventArgs e)
{
GetEmpList();
}
private void imtired_Click(object sender, EventArgs e)
{
con.Open();
int id = int.Parse(idbox.Text);
string fname=fnametxt.Text, lname=lnametxt.Text;
SqlCommand c = new SqlCommand("exec ughh'"+id+"','"+fname+"','"+lname+"','",con);
con.Close();
MessageBox.Show("Successfully inserted");
}
void GetEmpList()
{
SqlCommand c = new SqlCommand("exec Listughh", con);
SqlDataAdapter sd=new SqlDataAdapter(c);
DataTable dt = new DataTable();
sd.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}```
don't try and persist the connection at the form class level - since then you can't control when you dispose of it.
So, try say like this, and always have a using code block (which will clean up all your connections for you).
And it not clear why you have a public form method here, so let's just leave that issue out of the picture for the time being.
and I assume that a hard coded connection string was JUST for this post, not that you are using hard coded connection strings all over the place - (don't do that!!!).
And you tagged this as asp.net so we assuem this is a web page, right?
Thus, this "air code" should suffice:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GetEmpList();
}
private void imtired_Click(object sender, EventArgs e)
{
int id = int.Parse(idbox.Text);
SqlCommand c = new SqlCommand("ughh");
c.Parameters.Add("#ID", SqlDbType.Int).Value = id;
c.Parameters.Add("#fname", SqlDbType.NVarChar).Value = fnametxt.Text;
c.Parameters.Add("#lname", SqlDbType.NVarChar).Value = lnametxt.Text;
MyRstP(c, false);
MessageBox.Show("Successfully inserted");
}
void GetEmpList()
{
SqlCommand c = new SqlCommand("Listughh");
DataTable dt = new DataTable();
DataGridView1.DataSource = MyRstP(c);
DataGridView1.DataBind();
}
public DataTable MyRstP(SqlCommand cmdSQL, bool returnData = true)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
cmdSQL.CommandType = CommandType.StoredProcedure;
if (returnData)
{
rstData.Load(cmdSQL.ExecuteReader());
}
else
{
cmdSQL.ExecuteNonQuery();
}
}
}
return rstData;
}
And as for that file in use.
Reboot your computer.
So, "isolate" your connection routine(s). Don't attempt to persist the connection at the form/class level, move your connection string to config or settings. (and bonus points is you can use the connection builder).
I am trying to make it so that when changing the value in the comboBox, the database is displayed in the dataGridview. Everything seems to work, but when you close the form it gives an error:
enter image:
Code:
namespace Cursach
{
public partial class VoucherForm : Form
{
public VoucherForm()
{
InitializeComponent();
}
public void VoucherCountry()
{
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = false;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.AllowDrop = false;
dataGridView1.ReadOnly = true;
DB dB = new DB();
SqlCommand command = new SqlCommand("SELECT * FROM Voucher WHERE Name_Country= #nC", dB.ConnectionSQL());
command.Parameters.Add("#nC", SqlDbType.VarChar).Value = comboBox1.SelectedValue;
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter();
dB.OpenSQL();
adapter.SelectCommand = command;
adapter.Fill(table);
dataGridView1.DataSource = table;
dB.ClodeSQL();
}
private void VoucherForm_Load(object sender, EventArgs e)
{
this.countryTableAdapter.Fill(this.cursacDat.Country);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
VoucherCountry();
}
}
You have a DB class which is good to separate you database code from your user interface code. I moved the database code to retrieve the Country data to the DB class. Notice how the DB class knows nothing about the user interface and the user interface knows nothing about the database.
Database objects need to be closed and disposed. using blocks take care of this for you even if there is an error.
public class DB
{
private string ConStr = "Your connection string";
public DataTable GetCountryData(string nC)
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(ConStr))
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Voucher WHERE Name_Country= #nC", cn))
{
cmd.Parameters.Add("#nC", SqlDbType.VarChar, 100).Value = nC;
cn.Open();
dt.Load(cmd.ExecuteReader());
}
return dt;
}
}
Then in the form.
private void OpCode()
{
if (comboBox1.SelectedIndex < 0)
{
MessageBox.Show("Please select a value in the drop down.");
return;
}
DB DataClass = new DB();
dataGridView1.DataSource = DataClass.GetCountryData(comboBox1.SelectedValue.ToString());
}
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();
I have set up a listbox called lboxsupplier, i have also created a data adapter which i then used to populate the supplier listbox. When i run the form the listbox is empty. I want the listbox to populate with supplier ID and company which i will then click on to populate another listbox with products.
Namespace Pennyburn_Greg
{
public partial class FormProcess : Form
{
SqlDataAdapter daSupplier;
DataSet dsPennyburnGreg = new DataSet();
SqlConnection conn;
SqlCommand cmdSupplierDetails;
SqlCommandBuilder cmdBSupplier;
DataRow drSupplier;
String connstr, sqlSupplier;
public FormProcess()
{
InitializeComponent();
}
private void FormProcess_Load(object sender, EventArgs e)
{
connstr = #"Data Source= arlene-pc; Initial Catalog= PennyburnGreg; Integrated Security=True";
//dataAdapter for supplier listbox
sqlSupplier = #"Select* from Supplier";
conn = new SqlConnection(connstr);
cmdSupplierDetails = new SqlCommand(sqlSupplier, conn);
daSupplier = new SqlDataAdapter(cmdSupplierDetails);
daSupplier.FillSchema(dsPennyburnGreg, SchemaType.Source, "Supplier");
}
private void filllboxsupplier(string str)
{
daSupplier.Fill(dsPennyburnGreg, "Supplier");
lboxsupplier.DataSource = dsPennyburnGreg.Tables["Supplier"];
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
}
}
}
First of all, why are you calling FillSchema, rather should be calling Fill method to get the data, like
daSupplier.Fill(dsPennyburnGreg, "Supplier");
Once you have the dataset filled, then in your FormProcess_Load() you can add the dataset as datasource to the listbox like
lboxsupplier.DataSource = dsPennyburnGreg.Tables["Supplier"]
First thing you need to do is loosely couple your UI and data a little bit. Try this code:
// Returns a DataTable of ALL suppliers
private DataTable GetSuppliers()
{
return GetSuppliers(0);
}
// Returns a DataTable of the given supplier
private DataTable GetSuppliers(int supplierId)
{
using (var connection = new SqlCommand())
{
connection.ConnectionString = #"Data Source= arlene-pc; Initial Catalog= PennyburnGreg; Integrated Security=True";
using (var command = new SqlCommand())
{
connection.Open();
command.CommandType = CommandType.Text;
command.Connection = connection;
if (supplierId == 0)
{
command.commandText = "SELECT * FROM Supplier";
}
else
{
command.commandText = "SELECT * FROM Supplier WHERE SupplierId=#id";
command.Parameters.AddWithValue("#id", supplierId);
}
using (var adapter = new SqlDataAdapter())
{
using (var ds = new DataSet())
{
adapter.SelectCommand = command;
adapter.Fill(ds);
if (ds.Tables.Count > 0)
return ds.Tables[0];
}
}
}
}
return null;
}
And now you can just do this:
lboxsupplier.DataSource = GetSuppliers(int.Parse(lboxsupplier.SelectedValue));
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
Or if you need all Suppliers, just do this:
lboxsupplier.DataSource = GetSuppliers();
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
This code will provide some separation. This is still not ideal, but beats what you had.
You're not doing anything with the listbox control in FormProcess_Load, so it will be empty when it first loads. I'm assuming you have lboxsupplier_Click bound to the Click event of lboxsupplier? If so, then you'll need to click on that listbox before it will populate the Dataset (which is a very odd user experience, but if that's truly what you need...). If lboxsupplier_Click isn't an event handler, then you're going to have to manually call it.
If it still isn't populating, then try running your query against the database directly, and make sure that it returns data and has columns named "Company" and "SupplierID"
I am missing something very simple. I have a form with 5 textBox and want to fill them with the data from the SQL Server database. Here is what I have so far:
As I debug this code line by line it returns to the calling block at the connection.open() line.
public void Get_Contact_Info()
{
using (DataAccessClass.sql_Connection)
{
string SQL = "SELECT * FROM Customer_Contacts WHERE Contact_ID = #contact_Id";
SqlCommand sqlCommand = new SqlCommand(SQL, DataAccessClass.sql_Connection);
sqlCommand.Parameters.AddWithValue("#Contact_Id", contact_Id);
sqlCommand.Parameters.AddWithValue("#Contact_Direct_Number", contact_Direct_NumberTextBox);
sqlCommand.Parameters.AddWithValue("#Contact_Cell_Number", contact_Cell_NumberTextBox);
sqlCommand.Parameters.AddWithValue("#Contact_Email", contact_EmailTextBox);
sqlCommand.Parameters.AddWithValue("#Contact_Department", contact_DepartmentTextBox);
DataAccessClass.sql_Connection.Open();
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
contact_Id = sqlDataReader["Contact_ID"].ToString();
}
DataAccessClass.sql_Connection.Close();
}
}
}
I have been doing a pretty good job of getting info from the user and saving it to the SQL Server DataTable but know I want to get some out so that I can edit the info.
Any help will be gratefully appreciated.
Here is my DataAccessClass
public static class DataAccessClass
{
static SqlConnection sqlConnection = new SqlConnection();
public static SqlConnection sql_Connection
{
get { return sqlConnection; }
}
public static void OpenConnection()
{
string sqlString = Properties.Settings.Default.ConnectionString;
sqlConnection.ConnectionString = sqlString;
sqlConnection.Open();
}
public static void CloseConnection()
{
sqlConnection.Close();
}
}
Here is how I am calling Get_Contact_Info.
private void Customer_Add_Contact_Form_Load(object sender, EventArgs e)
{
this.customer_ContactsBindingSource.AddNew();
if (contact_Id == null)
{
contact_NameTextBox.Select();
}
else
{
Get_Contact_Info();
}
}
From a DataGridView I am selecting a row and passing customer_ID to the Customer_Add_Contact_Form so that I can edit the contact information. Here is the code for this step:
DataGridViewRow row = customer_ContactsDataGridView.CurrentCell.OwningRow;
string contact_ID = row.Cells[0].Value.ToString();
string customer_Ship_ID = null;
using (Form Customer_Add_Contact_Form = new Customer_Add_Contact_Form(customer_Ship_ID, contact_ID))
As discussed here it is better to let connection pooling manage the connections, so you can simplify your code to:
public void Get_Contact_Info()
{
using (var connection = new SqlConnection(roperties.Settings.Default.ConnectionString))
{
connection.Open();
var SQL = "SELECT * FROM Customer_Contacts WHERE Contact_ID = #contact_Id";
var sqlCommand = new SqlCommand(SQL, connection);
sqlCommand.Parameters.AddWithValue("#Contact_Id", contact_Id);
using (var sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
contact_Id = sqlDataReader["Contact_ID"].ToString();
TextBoxName.Text = sqlDataReader["Contact_Name"].ToString();
//etc ...
}
}
}
}
I have removed unused parameters and created a new connection. Possibly you tried to open a connection using .Open() without initializing it with a connections string (is it roperties?)