I have a SQL Database that contains a bit column and whenever a checkbox is clicked I want to update the bit column field with the current value.
All works great except the DataGridView doesn't update and I have to reload it to see the changes (checked/unchecked).
I tried with Refresh() and RefreshEdit() but it doesn't work.
private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
SqlConnection db = new SqlConnection(Properties.Settings.Default.BikesConn);
if (e.ColumnIndex == 1)
{
if (dgv.Rows[e.RowIndex].Cells["Selected"].Value.ToString() == "True")
{
SqlCommand cmd = new SqlCommand(string.Format("UPDATE {0} SET Selected='0' WHERE ID={1}", Properties.Settings.Default.Profile, dgv.SelectedRows[0].Cells[0].Value.ToString()), db);
db.Open();
cmd.ExecuteNonQuery();
db.Close();
//loadGridViewer(Properties.Settings.Default.Profile);
}
if (dgv.Rows[e.RowIndex].Cells["Selected"].Value.ToString() == "False")
{
SqlCommand cmd = new SqlCommand(string.Format("UPDATE {0} SET Selected='1' WHERE ID={1}", Properties.Settings.Default.Profile, dgv.SelectedRows[0].Cells[0].Value.ToString()), db);
db.Open();
cmd.ExecuteNonQuery();
db.Close();
//loadGridViewer(Properties.Settings.Default.Profile);
}
Solved by adding the following code:
dgv.Rows[e.RowIndex].Cells["Selected"].Value = !(bool)dgv.Rows[e.RowIndex].Cells["Selected"].Value;
Related
How To show Data Immediately In Data Grid View That is inserted Or Updated. I have to Re Start The Project To Show That Data.I Used Update() And Refresh() But not working for me
private void UpdateDebtbutton_Click(object sender, EventArgs e)
{
SqlConnection conn = ForConnection();
conn.Open();
using (conn)
{
if (paytextBox.Text != "")
{
SqlCommand cmd = new SqlCommand("spdebth", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#id", SqlDbType.Int).Value =customerIDTextBox.Text.ToString();
cmd.Parameters.Add("#text", SqlDbType.Int).Value = paytextBox.Text.ToString();
cmd.ExecuteNonQuery();
MessageBox.Show("Record updated");
spSelectAllCustomerDataGridView.Update();
spSelectAllCustomerDataGridView.Refresh();
conn.Close();
}
}
}
Refresh and Update methods are not used to refresh data, but re-paint WinForms control.
There are some ways of displaying data updated in DataGridView:
Use BindingList as data source, but this requires a object to implement INotifyPropertyChanged
Update row on DataGridView manually
Rebind DataSource
Below is example for third point:
private void UpdateDebt(int customerId, int debt)
{
var debts = (List<Debt>)spSelectAllCustomerDataGridView.DataSource;
var item = debts.First(x => x.Id == customerId);
item.Debt = debt;
spSelectAllCustomerDataGridView.DataSource = null;
spSelectAllCustomerDataGridView.DataSource = debts;
}
You have to rebind DataGridView to display changes.
Sorry guys to my english..
when i insert a record the same description with the existing record in datagridview but different quantity.. it creates a new row for the last record i inserted...
what i want is to ADD the quantity i inserted to the old record with the same description..
1. HERE'S THE IMAGE FOR YOU TO UNDERSTAND THE PROBLEM
2. THIS IS WHAT HAPPEN
The result should be QUANTITY = 25.. and also the totalcbm.. totalcbm = quantity * cbm
private void btnSave_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO Inventory(Quantity,Unit,ItemCode,ItemName,Cbm,TotalCbm)VALUES(#Quantity,#Unit,#ItemCode,#ItemName,#Cbm,#TotalCbm)";
cmd.Parameters.AddWithValue("#Quantity", tbQuantity.Text.ToString());
cmd.Parameters.AddWithValue("#Unit", tbUnit.Text.ToString());
cmd.Parameters.AddWithValue("#ItemCode", tbItemCode.Text.ToString());
cmd.Parameters.AddWithValue("#ItemName", tbItemName.Text.ToString());
cmd.Parameters.AddWithValue("#Cbm", tbCbm.Text.ToString());
cmd.Parameters.AddWithValue("#TotalCbm", tbTotalCbm.Text.ToString());
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
frmUserAE form1 = new frmUserAE();
AccountForm.LoadGrid();
this.Hide();
}
}
}
You are doing an INSERT statement, which will create a new row.
You should do an UPDATE statement, depending on what you think is your primary key (the description?).
I have a grid view. If I click the add button, an empty row is created. There is more than one empty row in the grid view. Now if I click the delete button on the selected row, all the empty rows are deleted. I want to delete the selected empty row only.
thank you..please help ..
delete code is here...
protected void gvEmployeeDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lblEmpID = (Label)gvEmployeeDetails.Rows[e.RowIndex].FindControl("lblEmpID");
conn.Open();
string cmdstr = "delete from EmployeeDetails where empid=#empid";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#empid", lblEmpID.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
add row code here.........
in add row i want alert message if the name textbox is empty
protected void gvEmployeeDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("ADD"))
{
TextBox txtAddEmpID = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddEmpID");
TextBox txtAddName = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddName");
TextBox txtAddDesignation = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddDesignation");
TextBox txtAddCity = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCity");
TextBox txtAddCountry = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCountry");
conn.Open();
string cmdstr = "insert into EmployeeDetails(empid,name,designation,city,country) values(#empid,#name,#designation,#city,#country)";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#empid", txtAddEmpID.Text);
cmd.Parameters.AddWithValue("#name", txtAddName.Text);
cmd.Parameters.AddWithValue("#designation", txtAddDesignation.Text);
cmd.Parameters.AddWithValue("#city", txtAddCity.Text);
cmd.Parameters.AddWithValue("#country", txtAddCountry.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
}
Can you change the "empid" column to be Identity? This is done from SQL management studio and will make your column to be unique and will auto increment the values in it. After that you will remove it from the Add method and the SQL will take care of it. This will fix your problem.
In SQL you must go the the EmployeeDetails table. Choose design from your options and then go the to empid column. On it you can open Column Properties and expand the "Identity Specifications". Then change "(Is Idetity)" to "Yes" and save the table. See the screenshot below:
Then your Add code should look like that:
protected void gvEmployeeDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("ADD"))
{
TextBox txtAddName = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddName");
if(string.IsNullOrEmpty(txtAddName.Text))
{
MessageBox.Show("Name is empty"); // or some logging, you decide
}
else
{
TextBox txtAddDesignation = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddDesignation");
TextBox txtAddCity = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCity");
TextBox txtAddCountry = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCountry");
conn.Open();
string cmdstr = "insert into EmployeeDetails(name,designation,city,country) values(#name,#designation,#city,#country)";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#name", txtAddName.Text);
cmd.Parameters.AddWithValue("#designation", txtAddDesignation.Text);
cmd.Parameters.AddWithValue("#city", txtAddCity.Text);
cmd.Parameters.AddWithValue("#country", txtAddCountry.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
}
}
also try this one also,
gvEmployeeDetails.DeleteRow(Row name/index);
try this code:
gvEmployeeDetails.AllowUserToAddRows = false;
It will Automatically delete Empty row.
I have a datagridview fro my application.I want to update the datagridview column value using SqlCommand, I have a code for that, but it is showing error. How could I do it?
Here is my update button code:
private void EDIT(object sender, EventArgs e)
{
foreach (DataGridViewRow row in datagrid.Rows)
{
if (datagrid.Rows.Count > 0)
{
int nRowIndex = datagrid.Rows.Count - 2;
if (datagrid.Rows[nRowIndex].Cells[0].Value != null)
{
con.Open();
SqlCommand cmd11 = new SqlCommand("update Purchasedetail set qty=#qty ,price=#price,tax=#tax,discount=#discount,total=#total where product_id=#product_id, product_name=#product_name", con);
cmd11.Parameters.AddWithValue("#product_id", row.Cells[0].Value);
cmd11.Parameters.AddWithValue("#product_name", row.Cells[1].Value);
cmd11.Parameters.AddWithValue("#qty", row.Cells[2].Value);
cmd11.Parameters.AddWithValue("#price", row.Cells[3].Value);
cmd11.Parameters.AddWithValue("#tax", row.Cells[4].Value);
cmd11.Parameters.AddWithValue("#discount", row.Cells[5].Value);
cmd11.Parameters.AddWithValue("#total", row.Cells[6].Value);
cmd11.ExecuteNonQuery();
MessageBox.Show("Updated Successfully", "OUTPUT", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
}
con.Close();
}
Problem 1: Youare not closing the SqlCommand object properly in a loop.
Solution 1: You need to close the SqlCommand object properly while executing in a loop.
You need to enclose it in the using block {}
using(SqlCommand cmd11 = new SqlCommand("update command"))
{
}
Problem 2: You are returning from the function after executing the first command so you are not actually executing the command for all rows(only for one row).is it intension to update only one row?
Solution 2: if your intension is to update only one row you need to remove the return statement
Problem 3: You are just displaying the Success Messagewithout even checking wether the update is successfull or not.
Solution 3: You need to ensure that wether all of the rows updated successfully or not before displaying the Success Message.
Complete Code:
private void EDIT(object sender, EventArgs e)
{
con.Open();
bool UpdateFailed = false;
foreach (DataGridViewRow row in datagrid.Rows)
{
if (datagrid.Rows.Count > 0)
{
int nRowIndex = datagrid.Rows.Count - 2;
if (datagrid.Rows[nRowIndex].Cells[0].Value != null)
{
using(SqlCommand cmd11 = new SqlCommand("update Purchasedetail set
qty=#qty ,price=#price,tax=#tax,discount=#discount,total=#total
where product_id=#product_id, product_name=#product_name", con))
{
cmd11.Parameters.AddWithValue("#product_id", row.Cells[0].Value);
cmd11.Parameters.AddWithValue("#product_name", row.Cells[1].Value);
cmd11.Parameters.AddWithValue("#qty", row.Cells[2].Value);
cmd11.Parameters.AddWithValue("#price", row.Cells[3].Value);
cmd11.Parameters.AddWithValue("#tax", row.Cells[4].Value);
cmd11.Parameters.AddWithValue("#discount", row.Cells[5].Value);
cmd11.Parameters.AddWithValue("#total", row.Cells[6].Value);
if(!Convert.ToInt32(cmd11.ExecuteNonQuery()) > 0)
UpdateFailed = true;
}
}
}
}
if(!UpdateFailed)
MessageBox.Show("Updated Successfully", "OUTPUT", MessageBoxButtons.OK,
MessageBoxIcon.Information);
con.Close();
}
i'm very new to programming and c#. here i'm having ArguementOutOfRangeException. i want to add a new data row to the datagridview every time when click the button. so i used a variable "i" to increase the value one by one and change the row value when i use "0" which means
dataGridView2.Rows[0].Cells[0].Value = textBox1.Text.ToString();
instead of "i" the first row fills but when use "1" which means
dataGridView2.Rows[1].Cells[0].Value = textBox1.Text.ToString();
the exception comes. what is the right way to do such a thing ?
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public SqlConnection conn;
public int i = 0;
private void Form2_Load(object sender, EventArgs e)
{
conn = new SqlConnection("Data Source=.\\SQLEXPRESS; Integrated Security=sspi; Initial Catalog=student");
conn.Open();
}
private void button1_Click(object sender, EventArgs e)
{
string Sqlstr = "insert into student(name, pw)values(#name,#pw)";
SqlCommand cmd = new SqlCommand(Sqlstr, conn);
cmd.Parameters.AddWithValue("#name", textBox1.Text);
cmd.Parameters.AddWithValue("#pw", textBox2.Text);
if (cmd.ExecuteNonQuery() > 0)
{
i++;
DataGridView dataGridView1 = new DataGridView();
dataGridView2.Rows[i].Cells[0].Value = textBox1.Text.ToString();
dataGridView2.Rows[i].Cells[1].Value = textBox2.Text.ToString();
}
label1.Text = Convert.ToString(i);
}
}
}
You don't have to define a new DataGridView each time on a button click, I believe you want to add a new row in your existing DataGridView after the insert in database. You can do:
if (cmd.ExecuteNonQuery() > 0)
{
DataGridViewRow row = (DataGridViewRow)dataGridView2.Rows[0].Clone();
row.Cells[0].Value = textBox1.Text.ToString();
row.Cells[1].Value = textBox2.Text.ToString();
dataGridView2.Rows.Add(row);
}
You have to add new rows before you try writing in them. Use dataGridView2.Rows.Add( something ), check out the Add method.