Refresh DataGridView after inserting values - c#

I have established connection and inserted values into the table.
However, I am not sure the best method to refresh the DataGridview as the values have been inserted after click button.
private void button1_Click(object sender, EventArgs e)
{
{
string theText = makeTextBox.Text;
string theText2 = modelTextBox.Text;
var value = Convert.ToInt32(yearTextBox.Text);
int i = 6;
cnn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "INSERT INTO cars(Make,Model,Year) VALUES(#Make,#Model,#Year)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#Make", theText);
cmd.Parameters.AddWithValue("#Model", theText2);
cmd.Parameters.AddWithValue("#Year", value);
cmd.ExecuteNonQuery();
{
}
dataGridView1.DataSource = carsBindingSource;
dataGridView1.Refresh();
cnn.Close();
}
}
}
}
enter image description here
EDIT:
here is the code with the working solution of rebinding the datasource and then it will update:
{
string theText = textBox1.Text;
string theText2 = textBox2.Text;
var value = Convert.ToInt32(textBox3.Text);
int i = 6;
cnn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "INSERT INTO cars(Make,Model,Year) VALUES(#Make,#Model,#Year)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#Make", theText);
cmd.Parameters.AddWithValue("#Model", theText2);
cmd.Parameters.AddWithValue("#Year", value);
cmd.ExecuteNonQuery();
{
}
cnn.Close();
carsBindingSource = new BindingSource();
carsBindingSource.DataSource = carsTableAdapter.GetData();
dataGridView2.DataSource = carsBindingSource;
}
}```

Your code is missing the part where the carsBindingSource variable is initialized with data. From your limited code, it should be noted that… if you add/insert a new row into the table in the data base, then this is NOT going to automatically update the carsBindingSource.
It is unknown “what” is used as a DataSource to the carsBindingSource. OR, how this data source is populated. I will assume the DataSource to the BindingSource is a DataTable and that somewhere in the code it is getting this DataTable from a query to the data base. If this process is not already in a single method that returns a DataTable, then, I recommend you create one, and it may look something like…
private DataTable GetCarsDT() {
DataSet ds = new DataSet();
string connString = "Server = localhost; Database = CarsDB; Trusted_Connection = True;";
try {
using (SqlConnection conn = new SqlConnection(connString)) {
conn.Open();
using (SqlCommand command = new SqlCommand()) {
command.Connection = conn;
command.CommandText = "SELECT * FROM Cars";
using (SqlDataAdapter da = new SqlDataAdapter(command)) {
da.Fill(ds, "Cars");
return ds.Tables[0];
}
}
}
}
catch (Exception ex) {
MessageBox.Show("DBError:" + ex.Message);
}
return null;
}
Above will return a DataTable with three (3) columns, Make, Model and Year. This DataTable is used as a DataSource to the BindingSource… carsBindingBource.
Now in the button1_Click event, the code inserts the new values into the data base. However, the carsBindingSource will still contain the data “before” the new items were added to the DB. Therefore, we can simply use the method above to “update” the carsBindingSource after the new items are added to the DB.
Note: you can go two routs here, 1) as described above, simply update “all” the data in the binding source… OR … 2) after updating the new items into the data base, you can also add the new items to the binding source’s data source… i.e. its DataTable. Either way will work and unless there is a large amount of data, I do not think one way would be preferred over the other.
Below shows what is described above. Note, the commented code adds the new items directly to the DataTable. You can use either one but obviously not both.
private void button1_Click(object sender, EventArgs e) {
string connString = "Server = localhost; Database = CarsDB; Trusted_Connection = True;";
try {
using (SqlConnection conn = new SqlConnection(connString)) {
conn.Open();
using (SqlCommand command = new SqlCommand()) {
command.Connection = conn;
command.CommandText = "INSERT INTO cars(Make,Model,Year) VALUES(#Make,#Model,#Year)";
command.Parameters.Add("#Make", SqlDbType.NChar, 50).Value = makeTextBox.Text.Trim();
command.Parameters.Add("#Model", SqlDbType.NChar, 50).Value = modelTextBox.Text.Trim();
int.TryParse(yearTextBox.Text.Trim(), out int year);
command.Parameters.Add("#Year", SqlDbType.Int).Value = year;
command.ExecuteNonQuery();
carsBindingSource.DataSource = GetCarsDT();
//DataTable dt = (DataTable)carsBindingSource.DataSource;
//dt.Rows.Add(makeTextBox.Text.Trim(), modelTextBox.Text.Trim(), year);
}
}
}
catch (Exception ex) {
MessageBox.Show("DBError:" + ex.Message);
}
}
Putting all this together…
BindingSource carsBindingSource;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
carsBindingSource = new BindingSource();
carsBindingSource.DataSource = GetCarsDT();
dataGridView1.DataSource = carsBindingSource;
}
Hope this makes sense.

I dont think its possible. You may need to create a separate button to submit and then refresh the data

Related

Show a data from database to a label

I'm new to c# programming and have a problem retrieving data from database to a label text. Here is the code what I was trying to do.
private void label3_Click_1(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("Server=localhost; Database=car_rental; user=root; Pwd=; SslMode=none");
DataTable dTable = new DataTable();
con.Open();
MySqlDataReader dr = null;
MySqlCommand cmd = new MySqlCommand("Select * from login where username=" + username, con);
dr =cmd.ExecuteReader();
while (dr.Read())
{
label3.Text = (dr["username"].ToString());
}
con.Close();
}
The problem in your code is created by the concatenation of a string (username) to another string (the sql query). This is a well known source of problems, going from syntax errors (the engine is not able to parse correctly the query text) to a much worse problem known as Sql Injection.
The well known solution is to use parameters instead of concatenated strings
private void label3_Click_1(object sender, EventArgs e)
{
using(MySqlConnection con = new MySqlConnection("Server=localhost; Database=car_rental; user=root; Pwd=; SslMode=none"))
{
con.Open();
// A single string with a parameter placeholder
string sqlCmd = "Select * from login where username=#name";
using(MySqlCommand cmd = new MySqlCommand(sqlCmd, con))
{
// Associate a value to the required parameter
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = username;
using(MySqlDataReader dr =cmd.ExecuteReader())
{
// Supposing you have just one user with that name
if(dr.Read())
{
label3.Text = dr["username"].ToString();
}
else
{
label3.Text = "User not found!";
}
}
}
}
Notice how I have added the using statement around each disposable object required to query the database. This statement ensures that the objects involved are disposed at the end of their use freeing the valuable unmanaged resource kept during their usage.

c# display Access Database in DataGridView

First of all, here is my code:
private void Form5_Load(object sender, EventArgs e)
{
string strProvider = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\Users\name\Documents\myprogramms\example.accdb";
string strSql = "Select * from score";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
data_example.DataSource = scores;
}
My goal is to display the data out of a MS Access Database. My codes has no error messages, but everytime I try to open the Data Grid View its completely empty.
your code snippet looks good. I cannot see any obvious issue.
Try to put breakpoint at the end of your method and check if datatable contains rows and rows contains any values in ItemArray.
Make sure your data_example DataGridView control is set AutoGenerateColumns = true (default) and check you have no other data source defined for your data_example DataGridView control. This code works for me.
private void Form1_Load(object sender, EventArgs e)
{
data_example.AutoGenerateColumns = true;
string strProvider = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\aaa\CinemaBooking.accdb";
string strSql = "Select * from Booking";
using (OleDbConnection con = new OleDbConnection(strProvider))
{
using (OleDbCommand cmd = new OleDbCommand(strSql, con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
con.Open();
var scores = new DataTable();
da.Fill(scores);
data_example.DataSource = scores.DefaultView;
con.Close();
}
}
}
}
Maybe you can try to fill dataset with adapter and then use named table as datasource:
var dtSet = new DataSet();
da.Fill(dtSet, "Booking");
data_example.DataSource = dtSet.Tables["Booking"].DefaultView;

Query single data from SQLite to C# textbox or label

I have a single SQlite query that returns "10" to me but I couldn't send it to c# textbox1.text area. I found datagrid examples which work just fine but single value for textbox I could not handle it.
I tried changing datagrid areas to textbox but really I have no idea how to get value with sqlite
private SQLiteConnection con = new SQLiteConnection();
private SQLiteCommand com = new SQLiteCommand();
private SQLiteDataAdapter adapt = new SQLiteDataAdapter();
private DataSet ds = new DataSet();
private DataTable dt = new DataTable();
//private SQLiteDataReader dr = new SQLiteDataReader();
public void set_connection()
{
con = new SQLiteConnection();
con.ConnectionString = ("Data Source=data/lastix_db.s3db");
}
public void execute_q(string txtQuery)
{
set_connection();
con.Open();
com = con.CreateCommand();
com.CommandText = txtQuery;
com.ExecuteNonQuery();
con.Close();
}
public void load_data()
{
set_connection();
con.Open();
com = con.CreateCommand();
string comtext = "SELECT * FROM stok";
adapt = new SQLiteDataAdapter(comtext, con);
ds.Reset();
adapt.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
con.Close();
}
private void Button2_Click(object sender, EventArgs e)
{
set_connection();
string stokout = "SELECT SUM(giris_adet) - SUM(cikis_adet) as mevcutstok from stok where malzeme_kodu = 651";
execute_q(stokout);
label16.Text = Convert.ToString(stokout);
label16.Text = //must be read "10" from sqlite
Insert update delete and all other datagrid solutions are ok but I'm really stuck on read single data and type it to textbox.
SQLiteConnection connect = new SQLiteConnection();
connect.ConnectionString = ("Data Source=data/lastix_db.s3db");
connect.Open();
string sql = "SELECT SUM(giris_adet) - SUM(cikis_adet) as mevcutstok from stok where malzeme_kodu = 651";
SQLiteCommand cmd = new SQLiteCommand(sql, connect);
Int32 totalp = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
baglan.Close();
//MessageBox.Show("Your Balance is: " + totalp);
label16.Text = Convert.ToString(totalp);

C# & SQL Server : searching all database columns and populating datagrid

I am writing a a C# application, and I am stuck at searching the database and populating a data grid view. However I want to use this with command builder.
The issue is, I need the search to work across all columns in the database. I thought using OR and LIKE statements would do this. But instead I get either invalid syntax or no column name exists in the search.
Does anyone know a solution?
My current .cs:
private void btnSearchJob_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = (#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MTR_Database;Integrated Security=True");
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE " +txtSearchJob.Text+ " OR [Manufacturer] LIKE " +txtSearchJob.Text+ ")";
// DataAdapter
myDA = new SqlDataAdapter(selectQuery, con);
// SqlCommand
SqlCommand myCMD = new SqlCommand(selectQuery, con);
// DataAdapter to Command
myDA.SelectCommand = myCMD;
// Define Datatable
myDT = new DataTable();
// Command Builder (IS GOD!)
SqlCommandBuilder cb = new SqlCommandBuilder(myDA);
// Teach Command builder to be a boss!
myDA.UpdateCommand = cb.GetUpdateCommand();
myDA.InsertCommand = cb.GetInsertCommand();
myDA.DeleteCommand = cb.GetDeleteCommand();
// Fill the DataTable with DataAdapter information
myDA.Fill(myDT);
// Fill DataTable with Database Schema
myDA.FillSchema(myDT, SchemaType.Source);
// Bind The Data Table to the DataGrid
dataGridView1.DataSource = myDT;
// AutoSize Datagrid Rows and Colums to fit the Datagrid
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
}
// Catch Exception
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "SQL ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
NOTE:
I am aware of using parameters, I am simply using this to see if it will work when I will add parameters later.
this is what I use to get everything back into a DataTable
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(List<SqlParameter> sqlParameters, string connStr, string storedProcName)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcName;
sqlCmd.CommandTimeout = 5000;
foreach (var sqlParam in sqlParameters)
{
sqlCmd.Parameters.Add(sqlParam);
}
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
sqlParameters.Clear();
return dt;
}
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(string connStr, string query)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = query;
sqlCmd.CommandTimeout = 5000;
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
return dt;
}
hopefully this is pretty self explanatory to you, however pass in a list of SQL Parameters, connection string, and the stored procedure name, or use the second one where you pass in the inline SQL and the connection string.
I think you are missing ' in the query. Try this...
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE '" +txtSearchJob.Text+ "' OR [Manufacturer] LIKE '" +txtSearchJob.Text+ "')";

How to insert value from gridview into database

I have two tables in a SQL Server database. I select from table ADMS and I need to insert master table by gridview but I dont know how to insert with gridview. Please help. I've tried for many days and I did not pass yet
protected void Button3_Click1(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ADMS_Machining where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
else
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Machining_Master where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
String strConnString, strSQL;
strConnString = "Server=kane-pc;UID=sa;PASSWORD=1234;Database=Machining;Max Pool Size=400;Connect Timeout=600;";
//here
conn.ConnectionString = conn;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strSQL;
}
You can extract values from a grid view depending on what you have placed in the cells...
string value = this.GridView2.Rows[0].Cells[0].Text;
You can also track the selected row event, and get specific controls like the following...
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string someValueTakenFromLabel = (GridView2.SelectedRow.FindControl("lblAnyLabelHere") as Label).Text;
// .... do something with value here
}
I suggest you go through some tutorials though to get the hang of how to use GridView.
http://www.asp.net/web-forms/videos/building-20-applications/lesson-8-working-with-the-gridview-and-formview
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28v=vs.110%29.aspx
You have to first read data from cells and then insert them into database using SqlCommand.
Assuming that you have M_ID and M_NAME columns in your Machining_Master table you can insert values to database as below:
//Assuming that your id column is first column and name is second column
//get value of id and name
int mId = Convert.ToInt32(GridView2.SelectedRow.Cells[0].Text);
string mName = GridView2.SelectedRow.Cells[1].Text;
string connectionStrng = "your connection string";
string insertSql = "INSERT INTO Machining_Master (M_ID, M_NAME) VALUES (#mId, #mName)";
using (SqlConnection conn = new SqlConnection(connectionStrng))
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
try
{
cmd.Parameters.Add(new SqlParameter("mId", mId));
cmd.Parameters.Add(new SqlParameter("mName", mName));
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
//Close connection
conn.Close();
}
}
}

Categories

Resources