I have 4 textboxes and a datagridview, I wrote this code to display the selected row in a texboxes
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
textBox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
textBox2.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
textBox3.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
textBox4.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
}
and I wrote this code to update the selected row
private void button5_Click_1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
conn.ConnectionString = (#"Data Source=Ali-pc\sqlexpress;Initial Catalog=StockDB;Integrated Security=True");
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Stock", conn);
DataTable dt = new DataTable();
sda.Fill(dt);
int selectedRow;
selectedRow = dataGridView1.SelectedRows[0].Index;
dataGridView1.Rows[selectedRow].SetValues(textBox1.Text, textBox2.Text, textBox3.Text, textBox3.Text);
MessageBox.Show(" Successfully Saved! ");
}
And the codes work correctly, but my question is how can I save the changes to database ??
Related
I'm building a C# Windows Forms database application. Data should be written in a text field and saved in a table using a button. My problem is that the data is not saved in the table.
I have built a list that should show the records of the table. When you click on the insert button, the text is displayed in the list, but it is not saved in the table.
My code:
private void insert_Click(object sender, EventArgs e)
{
string con_string = Properties.Settings.Default.DB1_ConnectionString;
SqlConnection con = new SqlConnection(con_string);
con.Open();
SqlCommand cmd = new SqlCommand("insert into tab_Musik values (#Titel,#Inerpret,#Genre)", con);
cmd.Parameters.AddWithValue("#Titel", int.Parse(txt_Titel.Text));
cmd.Parameters.AddWithValue("#Inerpret", txt_Interpret.Text);
cmd.Parameters.AddWithValue("#Genre", double.Parse(kmb_Genre.Text));
cmd.ExecuteNonQuery();
con.Close();
}
private void show[enter image description here][1]_Click(object sender, EventArgs e)
{
string con_string = Properties.Settings.Default.DB1_ConnectionString;
SqlConnection con = new SqlConnection(con_string);
con.Open();
SqlCommand cmd = new SqlCommand("select * from tab_Musik", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource=dt;
}
For the problem you described about clicking the insert button, the data cannot be saved to the table, you can try the following code:
private void btnAdd_Click(object sender, EventArgs e)
{
string con_string = "database connection string";
SqlConnection sqlConnection = new SqlConnection(con_string);
string myinsert = "insert into tab_Musik values (#Titel,#Inerpret)";
SqlCommand mycom = new SqlCommand(myinsert, sqlConnection);
mycom.Parameters.AddWithValue("#Titel", textBox1.Text);
mycom.Parameters.AddWithValue("#Inerpret", textBox2.Text);
sqlConnection.Open();
mycom.ExecuteNonQuery();
mycom.Clone();
mycom.Dispose();}
Show results:
I am trying to develop a form which will search the database for the entered name. save the selected row and then move to the next one. but when i search again it clears the previously saved row.
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataView DV = new DataView(datatable);
DV.RowFilter = string.Format("proName LIKE '%{0}%'", textBox1.Text);
dataGridView1.DataSource = DV;
}
private void Form1_Load(object sender, EventArgs e)
{
OleDbCommand command = new OleDbCommand("select * FROM productDetails",connection);
DataSet dataset = new DataSet();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Zimad\Desktop\project1.accdb";
connection.Open();
dataAdapter.SelectCommand = command;
dataAdapter.Fill(datatable);
dataGridView1.DataSource = datatable;
connection.Close();
nRow = dataGridView1.CurrentCell.RowIndex;
}
private void button1_Click(object sender, EventArgs e)
{
if (nRow < dataGridView1.RowCount)
{
dataGridView1.Rows[nRow].Selected = false;
dataGridView1.Rows[++nRow].Selected = true;
}
}
button1 is used to save the selected row.
#Fabio is right. What i did here is that i loaded the search results in a textbox and later loaded the information against the item in the dataGridView
private void textBox1_TextChanged(object sender, EventArgs e)
{
listBox1.Visible = true;
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * FROM ProductDetails";
OleDbDataReader reader = command.ExecuteReader();
listBox1.Items.Clear();
while (reader.Read())
{
if (reader["proName"].ToString().Contains(textBox1.Text))
{
listBox1.Items.Add(reader["proName"].ToString());
}
}
connection.Close();
}
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * FROM ProductDetails";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader["proName"].ToString().Contains(textBox1.Text))
{
dataGridView1.Rows.Add();
dataGridView1[0, 0].Value = reader["proName"].ToString();
}
}
connection.Close();
}
I'm having trouble updating data from a data grid view with the use of a button. The text is editable but the changes does not save to the SQLite database. any ideas?
private void ProjectsAdmin_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'seniorProjectsDataSet2.DataTable1' table. You can move, or remove it, as needed.
this.dataTable1TableAdapter.Fill(this.seniorProjectsDataSet2.DataTable1);
}
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1 || e.ColumnIndex != 3) //ignore header row and any column that doesnt have file name
return;
var filename = dataGridView1.CurrentCell.Value.ToString();
if (File.Exists(filename))
Process.Start(filename);
}
private void updateData_Click(object sender, EventArgs e)
{
SQLiteConnection conn = new SQLiteConnection();
dataGridView1.EndEdit();
dataTable1TableAdapter.Adapter.Update(seniorProjectsDataSet.Tables[0]);
for (int i = 0; i < seniorProjectsDataSet.Tables[0].Rows.Count; i++)
{
seniorProjectsDataSet.Tables[0].Rows[i].AcceptChanges();
}
}
}
}
I solved the problem without a Button. In the following code I´ll give you a example how the connection and the update works with a mysql-database (update in runtime):
CODE
DataTable dt = null;
DataGridView dgv1 = null;
If the form load you have to set your dt variable to a new datatable:
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
using (MySqlConnection conn = new MySqlConnection("datasource=localhost;port=3306;username=root;password=1234"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select *from try.data ;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
conn.Close();
}
dgv1 = new DataGridView();
dgv1.AllowUserToAddRows = false;
dgv1.CellEndEdit += new DataGridViewCellEventHandler(dgv_CellEndEdit);
dgv1.CellValidating += new DataGridViewCellValidatingEventHandler(dgv_CellValidating);
dgv1.Dock = DockStyle.Fill;
dgv1.DataSource = dt;
this.Controls.Add(dgv1);
}
You have to set two events: CellValidating
private void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
InitializeComponent();
if (e.ColumnIndex == 0)
{
dgv1.CancelEdit();
}
}
and the CellValidating Event:
private void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string id = dt.Rows[e.RowIndex]["Eid"] + "";
string col = dt.Columns[e.ColumnIndex].ColumnName;
string data = dgv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value + "";
string sql = string.Format("UPDATE `try`.`data` SET `{0}` = '{1}' WHERE Eid = {2};", col, data, id);
using (MySqlConnection conn = new MySqlConnection("datasource=localhost;port=3306;username=root;password=1234"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
This aktually works with MySql but in Sql are "Equal" components like the SqlConnection or the SqlCommand... I hope this solve you problem. Have a nice day!
using System.Data.SQLite;
SQLiteConnection con = new SQLiteConnection("Data Source=C:\\Cogs\\bin\\Release\\db\\my_database_file.db");
SQLiteCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from [my_table]";
con.Open();
cmd.ExecuteNonQuery();
DataTable dta = new DataTable();
SQLiteDataAdapter dataadp = new SQLiteDataAdapter(cmd);
dataadp.Fill(dta);
dataGridView1.DataSource = dta;
con.Close();
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
In the first class i have a combobox and i am fetching its value from database and i have shown "Select Project Name" on page load in combobox.I want to insert its value only when user selects option from dropdown and insert nothing if user did not choose any option.
Now the problem is that the first name in the dropdown gets inserted on button click.without choosing any option.I want that if user did not choose any name value from dropdown nothing should get inserted.
can anyone help me..?
Assuming that datatype of ID column is int:
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
//begin adding line
DataRow row = table.NewRow();
row["project_name"] = "Select Project Name";
row["ID"] = 0;
table.Rows.InsertAt(row, 0);
//end adding line
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
if(combo_status.SelectedValue == 0)
{
return; //do nothing if user didn't select anything in combobox, you can change this line of code with whatever process you want
}
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
Hope this will help you
Hello sir i wanna search the data using checkbox aur checkboxlist like if i select two checkbox then i wanna to get the data of both the checkbox id's this code is giving me only one data at a time. please give me a demo code for this type of query.
private void checkboxlistbind()
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\FlagBits\\Documents\\Visual Studio 2010\\WebSites\\checkboxlist\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True");
con.Open();
string query = "select * from student where id='" + CheckBox1.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
}
private void checkboxlistbind2()
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\FlagBits\\Documents\\Visual Studio 2010\\WebSites\\checkboxlist\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True");
con.Open();
string query = "select * from student where id='" + CheckBox2.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
checkboxlistbind();
}
}
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox2.Checked == true)
{
checkboxlistbind();
checkboxlistbind2();
}
You need to iterate through your checkboxlist and test the selected value for each item and build a string containing each of your options.
string queryparam = '';
for (int i=0; i<checkboxlist1.Items.Count; i++) {
if (checkboxlist1.Items[i].Selected)
{ queryparam += (queryparam.Length = 0) ? "id = " + checkboxlist1.Items[i].Text : " or id = " checkboxlist1.Items[i].Text }
}
This should give you an idea to start with.