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.
Related
protected void gv_pedidos_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int idPedido = Convert.ToInt32(gv_pedidos.DataKeys[e.RowIndex].Values["idPedido"].ToString());
SqlConnection con = new SqlConnection(#"Server=localhost\SQLEXPRESS;Database=Kirchesch;Trusted_Connection=True;");
SqlCommand com = new SqlCommand(#"DELETE FROM pedidosFeitos WHERE idPedido = #idPedido", con);
com.Parameters.AddWithValue("#idPedido", idPedido);
con.Open();
com.ExecuteNonQuery();
con.Close();
preencheGrid();
}
This is the back-end of my code, the error I'm getting is on the variable idPedido, the third line.
Just use Convert.ToInt32(e.RowIndex);
The datakey is selected for the operation from the selected row index
You can get idPedido like this in RowDeleting event:
int idPedido = int.Parse(gv_pedidos.Rows[e.RowIndex].FindControl("idPedido").toString());
I'm trying to delete all the rows of a particular Aperture (of Bussiness) whenever the user clicks the button (which is a Save button), so to then insert the data to save. The code is the following:
private void button2_Click(object sender, EventArgs e)
{
SQLiteCommand cmdDel = new SQLiteCommand();
cmdDel = SQLconnect.CreateCommand();
cmdDel.CommandText = "DELETE FROM GridTable WHERE Aperturas=#combo";
cmdDel.Parameters.AddWithValue("#combo", combo1.Text);
cmdDel.ExecuteNonQuery();
DataTable dt = (DataTable)grid1.DataSource;
string sql = "INSERT INTO GridTable (Aperturas, Ventas, Proveedores, EAE, EAM) VALUES (#aperturas,#ventas,#proveedores,#eae,#eam)";
foreach (DataRow r in dt.Rows)
{
SQLiteCommand cmd = new SQLiteCommand();
cmd = SQLconnect.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#aperturas", combo1.Text);
cmd.Parameters.AddWithValue("#ventas", r["Ventas"]);
cmd.Parameters.AddWithValue("#proveedores", r["Proveedores"]);
cmd.Parameters.AddWithValue("#eae", r["Egreso Axel Efectivo"]);
cmd.Parameters.AddWithValue("#eam", r["Egreso Axel Mercaderia"]);
cmd.ExecuteNonQuery();
}
}
the problem is that the delete function does not seem to do anything, when i load the data back it appears duplicated, as if it was inserted for a second time (which it was, but not to end up showing like that)
Thank you in advance.
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 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;
I am trying to delete the row in the grid view. For that one i am writing code in the rowdeleting event like below.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string UserId;
SqlTransaction tran;
using (con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["EMASFBAConnectionString"].ConnectionString;
cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
tran = con.BeginTransaction();
TableCell cell = GridView1.Rows[e.RowIndex].Cells[1];
string username = cell.Text;
cmd.Transaction = tran;
cmd.CommandText = "Delete from aspnet_Users where UserName='" + username + "'";
UserId = cmd.ExecuteScalar().ToString();
if (UserId.Length!=0)
{
//delete user from membership table.
errorLabel.Text = "User is ready to delete";
}
tran.Commit();
con.Close();
}
}
when i debug the cell value is coming as empty. What i did the mistake here?
This grid view has edit and delete button in front of the each row.
I tried with Cells[0],Cells[2] but giving the empty values only. Can any one give me the solution?
hi define datakeys in the gridview and use this method
string UserID = GridView1.DataKeys[e.RowIndex].Value.ToString();
and then based on this ID delete the row.
cmd.CommandText = "Delete from aspnet_Users where UserID=" + UserID;
after that call your databind method to bind the gridview with updated records
for datakeynames please use this
<asp:gridview datakeynames="UserID"
runat="server">
Finally got the answer. If i try to get the values as Table cells it is not giving proper values. So i tried like this,
GridViewRow row = GridView1.Rows[e.RowIndex];
Label usernamelable = (Label)row.FindControl("lblUserNameValue");
string username = usernamelable.Text;
This works fine for me. I am referring the label control inside the gridview and getting the value.
try the following code:
var empId = Convert.ToInt32(this.gvDetails.DataKeys[e.RowIndex].Values["EmpId"].ToString());
protected void NPNGridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = NPNGridView1.SelectedRow;
TextBox1.Text = gvr.Cells[1].Text;
}
it's working, before u run the solution, please once test this Cells[1] indexes,