I have this piece of code which should be pretty straight forward.
private void btnSave_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection sqlConn = new SqlConnection(connString))
{
sqlConn.Open();
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand("SELECT Id, FirstName, LastName, TcReadOnly FROM PersonTable", sqlConn);
using (SqlCommandBuilder builder = new SqlCommandBuilder(da))
{
DataTable dt = (DataTable)dgvUsers.DataSource;
da.UpdateCommand = builder.GetUpdateCommand();
da.Update(dt);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Der er sket en fejl \r\n \r\n" + ex.ToString());
}
}
However, I recieve this error when the code is run.
Line 96 in Userform being
da.Update(dt);
I have already checked that my SelectCommand return a primary in Id, so that shouldn't be the problem.
Of course, seconds after asking the question I found the answer.
The SelectCommand I'm using to actually fill the DataTable looks like this
da.SelectCommand = new SqlCommand("SELECT Id, FirstName AS Fornavn, LastName AS Efternavn, " +
"TcReadOnly AS 'Read only' FROM PersonTable", sqlConn);
Which means that the columns in my DataTable doesn't have the same names as the ones I'm trying to update the database with :-) Brainfart....
Related
I'm currently practicing to make a barcode attendance application. After scanning the barcode, the barcode is automatically showing in a text box. There is a add button to send the barcode to the database. But when I click the add button only a blank dataset is adding.(It's working when directly type in the textbox)
private void VideoCaptureDevice_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
BarcodeReader reader = new BarcodeReader();
var result = reader.Decode(bitmap);
if (result != null)
{
textBox1.Invoke(new MethodInvoker(delegate ()
{
textBox1.Text = result.ToString();
}));
}
pictureBox1.Image = bitmap;
}
Here is the add button code
private void button1_Click(object sender, EventArgs e)
{
cmd = new MySqlCommand();
cmd.CommandText = "insert into student_att (`id`, `nic`, `name`, `address`, `number`, `batch`) select* from student_dt where nibm_id like '" + textBox1.Text + "%'";
if (textBox1.Text == "")
{
MessageBox.Show("Please provide all data");
}
else
{
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted");
string Query = "select * from student_att ;";
MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
dataGridView2.DataSource = dTable;
}
try
{
textBox1.Text = string.Empty;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
1st of all, your queries are quite weird, when you do INSERT, I dont see anywhere what do you actually insert (no data specified in your code), it should be like:
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text!=string.Empty)
{
//using means it will close and dispose the classes by it self! So no need to type Close() or Dispose() methods.
using (SqlConnection conn = new SqlConnection("ConnectionStringHere"))
{
bool bAllOK = false; //using and helping with some custom flag to get it all right
string query1 = #"INSERT INTO student_att (id, nic, name, address, number, batch) VALUES (#id, #nic, #name, #address, #number, #batch)";
string query2 = #"SELECT * FROM studetnt_att WHERE nibm_id LIKE #myText%";
//1. INSERT:
using (SqlCommand cmd = new SqlCommand(query1, conn))
{
cmd.Parameters.AddWithValue("#id", 1); //get new ID, best is to look for the last one in the DB, and increment by 1
cmd.Parameters.AddWithValue("#nic", "nickname1"); //get his nick name
//same way and and set all the other 4 parameters for name, address, number and batch here
try
{
connection.Open();
command.ExecuteNonQuery();
bAllOK = true;
}
catch(SqlException)
{
// error here if occures
}
}
if(bAllOK)
{
//2. SELECT:
using (SqlCommand cmd = new SqlCommand(query2, conn))
{
cmd.Parameters.AddWithValue("#myText", textBox1.Text);
DataTable table = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(table);
dataGridView2.DataSource = table;
}
}
}
}
}
else
MessageBox.Show("Please type some name...");
}
The 2nd query makes no sence, since you are looking for nibm_id is looking for IDS which starts with the number in textBox. Is that really what you are looking for? LIKE SOMETHING% means that it looks for SOMETHINGS which starts with that.
I want insert some data to localdatabace and insert is successfully done but don't show in my datagridview tile second insert do for debog it I Call Select All end of my insert and see the last insert don't show in it but whene i insert a next data , last data will be showing can every one help me pleas?
public void connect()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(conString);
String sqll = "Insert into TblBank (txtTodayDate" +
",txtSahebanHesab" +
",txtShobe" +
",txtShomareMoshtari" +
",txtShoareHesab" +
",cmbNoeHesab" +
",txtSarresid" +
")";
try
{
sql.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqll, sql);
SqlCommand sc = new SqlCommand(sqll,sql);
sc.Parameters.AddWithValue("todayDate", new PersianDateTime(dtpTodayDate.the_date).ToString("yyyy/MM/dd"));
sc.Parameters.AddWithValue("sahebanHesab", txtSahebHesabName.Text);
sc.Parameters.AddWithValue("shobe", txtshobe.Text);
sc.Parameters.AddWithValue("shomareMoshtari", txtShomareMoshtari.Text);
sc.Parameters.AddWithValue("shoareHesab", txtShomareHesab.Text);
sc.Parameters.AddWithValue("noeHesab", cmbNoeHesab.SelectedIndex);
sc.Parameters.AddWithValue("sarresid", txtSarResidMah.Text);
sc.ExecuteNonQuery();
sql.Close();
select();
}
catch (Exception ex)
{
}
}
and select is
private void select()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection cn = new SqlConnection(conString);
String sqlString = "SELECT * FROM TblBank Order BY Id desc ";
SqlConnection sql = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(sqlString, cn);
try {
sql.Open();
SqlDataAdapter sa = new SqlDataAdapter(sqlString, sql);
using (SqlDataReader read = sa.SelectCommand.ExecuteReader())
{
if (read.Read())
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
sql.Close();
}
catch (Exception ex)
{
}
}
The DataReader.Read() method will iterate result set before DataTable.Load(). Because the DataReader is a forward-only stream, it has empty result set when DataTable.Load() executes and DataTable content is still empty while setting DataSource for DataGridView. Try DataReader.HasRows property to check result set availability:
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlString, cn))
{
try
{
cn.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
// check if the reader returns result set
if (read.HasRows)
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
}
catch (Exception ex)
{
// do something
}
}
}
I am trying to show Oracle Data in a DataGridView in my Windows Form Application but it just returns a grey blank view. My code for this currently is:
string insertquery = "select * from Candidate where CandidateName like '"+ txtBoxSearchData.Text +"%'";
OracleConnection con = new OracleConnection(oradb);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = insertquery;
try
{
OracleDataReader reader = cmd.ExecuteReader();
OracleDataAdapter orada = new OracleDataAdapter(cmd);
DataTable dataTable = new DataTable();
orada.Fill(dataTable);
dataTable.Load(reader);
BindingSource bSource = new BindingSource();
bSource.DataSource = dataTable;
dataGridViewSearch.DataSource = bSource;
orada.Update(dataTable);
}
catch(ArgumentException ex)
{
MessageBox.Show("Error: " + ex.Message);
}
catch(OracleException ex1)
{
MessageBox.Show("Error: " + ex1.Message);
}
finally
{
cmd.Dispose();
con.Dispose();
}
}
I am positive I do not require all those functions in my Try statement but I have come across many different methods to do this - I just included all of those into my code to experiment. The connection string is correct too as I have succeeded in adding data into the tables through queries in another part of my application.
Doing something like the following should be enough. There should be no need for an OracleDataAdapter or BindingSource. Just can't test it here, as I do not have an Oracle database around.
public void fillDataGrid()
{
try
{
using(OracleConnection connection = new OracleConnection("connectstring"))
using(OracleCommand cmd = new OracleCommand("select * from my super table", connection ))
{
connection .Open();
using(OracleDataReader oracleDataReader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(oracleDataReader );
myDataGrid.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I'm trying to update data from DataGridView to my database. While I was looking for the solution of this problem on google, I noticed that all of the solutions are managed by using class variables (for DataTable,SqlDataAdapter,...). I'm trying to do this just by using function variables.
This is how I loaded data to DataGridView:
private void LoadDataGridView(int ID)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT SENTENCE FROM Sentences WHERE CategoryID = #ID",connection);
cmd.Parameters.Add("#ID",SqlDbType.Int).Value = ID;
DataTable dataTable = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(dataTable);
DataGridView.DataSource = dataTable;
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING TO DATABASE!");
}
}
DataGridView is showing just those sentences that match particular ID.
This is what I have tried so far:
private void RefreshBtn_Click(object sender, EventArgs e)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT SENTENCE FROM Sentences WHERE CategoryID IN(#CategoryID)", connection);
cmd.Parameters.Add("#CategoryID",SqlDbType.Int).Value = CategoryID;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Update(dataTable);
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE!");
}
}
This is the error that comes up:
Cannot insert value NULL into column CategoryID, table ...;column does not allow nulls.Insert fails. The statement has been terminated.
if your Id data type is int ,you don't need put it inside "".
private void RefreshBtn_Click(object sender, EventArgs e)
{
try
{
string connString;//WHAT EVER IT IS
string Query=string.Format(#"SELECT QUESTION FROM Questions WHERE CategoryID = '{0}'",CategoryID);
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Query, connection);
connection.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd,connString);
DataTable DataTable=new DataTable();
dataAdapter.Fill(DataTable);
datagridview1.DataSource=DataTable;
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE!");
}
catch (SqlException)
{
MessageBox.Show("SqL Error!");
}
}
SOLUTION of my problem:
Firstly, I have shown all columns of database table in DataGridView and then I have hided Primary Key column and CategoryID column. That is shown in the following code:
private void LoadDataGridView(int ID)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Sentences WHERE CategoryID = #ID";
cmd.Connection = connection;
cmd.Parameters.Add("#ID",SqlDbType.Int).Value = ID;
dataTable = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(dataTable);
dataGridView.DataSource = dataTable;
dataGridView.Columns[0].Visible = false;
dataGridView.Columns[2].Visible = false;
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE!");
}
}
Then, I have set default value only for CategoryID column, because Primary Key column has an option of Auto - Increment. That is show in the following code:
private void dataGridView_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
e.Row.Cells["CategoryID"].Value = CategoryID;
}
The last thing I have done is implement the code for RefreshBtn (the following code is practically the same as the code in question):
private void RefreshBtn_Click(object sender, EventArgs e)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Questions WHERE CategoryID = #CategoryID";
cmd.Connection = connection;
cmd.Parameters.Add("#CategoryID", SqlDbType.Int).Value = CategoryID;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Update(dataTable);
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE !");
}
}
I am trying to display my database details on a datagrid using the following methods. I am able to establish connection with the database and do updates so that's all fine. Just having issues with displaying the data after making a query.
The first method query below does the query. I am trying to use that info and run the codes under the 2nd method which is called when I click a button.
I am having problem callign my query method. I was under the impression I can call it under adapter.SelectCommand but that returns an error saying "cannot implicitly convert type". Please advice if I am running the query wrongly. Thanks.
public MySqlDataReader Query(string queryString)
{
MySqlDataReader reader;
MySqlCommand cmd2;
try
{
cmd2 = new MySqlCommand(queryString, conn);
reader = cmd2.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + " " + reader.GetString(1) + " " + reader.GetDouble(2));
}
return reader;
}
catch(Exception e)
{
Console.WriteLine("Error in query");
Console.Read();
}
return null;
}
private void Button_Retrieve(object sender, RoutedEventArgs e)
{
try
{
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = dataSource.Query("SELECT * FROM PERSONS WHERE Name = 'Sam';");//THis line returns the error
DataTable dt = new DataTable("PERSONS");
adapter.Fill(dt);
dataGrid1.ItemsSource = dt.DefaultView;
adapter.Update(dt);
}
catch (Exception error)
{
MessageBox.Show(error.StackTrace);
}
}
Your adapter does not have a connection
// Assumes that connection is a valid SqlConnection object.
string queryString =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet customers = new DataSet();
adapter.Fill(customers, "Customers");