Move to next Row in dataGridView - c#

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();
}

Related

How to do Automatic synchronize between database access and DatagridView in c#

in my program when i delete a record, it deleted from database access and from the DataGridView , but when i close the window and open it again the record appear again in DataGridView ,Although it deleted from database access ,Here is my code :
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
command.Connection = connection;
string query = " delete from Hoteldb where ID= " +textBox0.Text + "";
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Guest Checked Out succesfly");
BindGridView();
}
public void BindGridView()
{
string strSQL = "SELECT * FROM Hoteldb";
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
DataTable table = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(table);
dataGridView1.DataSource = table;
connection.Close();
}
Try this :
private void button1_Click(object sender, EventArgs e)
{
int RowsAffected = 0;
connection.Open();
string query = "DELETE FROM Hoteldb WHERE ID=#ID";
command = new OleDBCommand(query);
command.Connection = connection;
cmd.Parameters.Add(new OleDbParameter("#ID", OleDbType.WChar, 150, "ID"));
cmd.Parameters["#ID"].Value = textBox0.Text.Trim()
RowsAffected = command.ExecuteNonQuery();
if(RowsAffected > 0)
{
MessageBox.Show("Guest Checked Out succesfly");
BindGridView();
}
else
{
MessageBox.Show("There was nothing to be deleted");
}
}
public void BindGridView()
{
connection.Open();
string strSQL = "SELECT * FROM Hoteldb";
cmd = new OleDbCommand(strSQL);
cmd.Connection = connection;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Hoteldb");
dataGridView1.DataSource = ds.Tables["Hoteldb"].DefaultView
connection.Close();
}

Update Database using datagridview C#

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 ??

Updating Datagridview data using SQLite Database

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();

id getting inserted without selecting in c#.net

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

How do I refresh combobox item after selecting one item?

My Combobox contains the name of a waiter.
When I allot the table to the selected waiter its status become true but the combobox item doesn't change.
programming on page_load:---
private void frmTableAllotment_Load(object sender, EventArgs e)
{
dtTmPkr.Value = System.DateTime.Now;
cmd = new SqlCommand("Select name from waiterentry2 where status='false'", con);
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
cmbWaiter.Items.Add(dr["name"]);
}
dr.Close();
cmd = null;
con.Close();
}
coding on save button for waiter status= true on allot button:
private void btnAllocate_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("update waiterentry2 set status='true' where name=#name", con);
cmd.Parameters.AddWithValue("name", dgvDetails.Rows[i].Cells[0].Value);
cmd.ExecuteNonQuery();
con.Close();
}
Problem is after you change the database you haven't refresh or reload the combobox databinding.
I would re factor your code as below and call the load data method after database update.
private void frmTableAllotment_Load(object sender, EventArgs e)
{
dtTmPkr.Value = System.DateTime.Now;
LoadComboBox();
}
private void btnAllocate_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("update waiterentry2 set status='true' where name=#name", con);
cmd.Parameters.AddWithValue("name", dgvDetails.Rows[i].Cells[0].Value);
cmd.ExecuteNonQuery();
con.Close();
LoadComboBox();
}
private void LoadComboBox()
{
while(cmbWaiter.Items.Count >0)
cmbWaiter.Items.RemoveAt(0);
cmd = new SqlCommand("Select name from waiterentry2 where status='false'", con);
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
cmbWaiter.Items.Add(dr["name"]);
}
dr.Close();
cmd = null;
con.Close();
}
Try to call he code which you have written in form load after successful db operation in btnAllocate_Click event

Categories