How to use the GridView AutoGenerateDeletebutton - c#

I am using Visual Studio 2010 to develop an asp.net app using c#. I created an GridView table by the following
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="True"
EnableViewState="False" OnRowDeleting="DeleteRowButton_Click">
</asp:GridView>
But I do not know how to use the auto generated delete button in my c# code.
I search online, they always provide my code as
protected void DeleteRowButton_Click(Object sender, GridViewDeleteEventArgs e)
{
var PN = GridView1.DataKeys[e.RowIndex].Values["Part_Number"];
string PN = pn.ToString;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["XMLConnectionString"].ConnectionString);
// Create the command object
con.Open();
string str = "DELETE * FROM XML WHERE ([Part_Numbber] = " + PN + ")";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
Button1_Click(sender, e);
con.Close();
}
Thank you very much for anyone can tell me how to do it

For Delete any record from you should have any unique or Primary key. If you want to delete record using field "Part_Numbber" then this field data-type should be of either int or bigint in Database Table. Then Now put the following code to Delete.
protected void DeleteRowButton_Click(Object sender, GridViewDeleteEventArgs e)
{
int Part_Numbber= Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
SqlCommand cmd = new SqlCommand("DELETE FROM XML WHERE Part_Numbber=" + Part_Numbber+ "", con);
con.Open();
int temp = cmd.ExecuteNonQuery();
if (temp == 1)
{
lblMessage.Text = "Record deleted successfully";
}
con.Close();
FillGrid();
}
How this may help you.

Related

How to pass data between ASP.net, sql server and c#

I'm trying to develop a web site that receives data from SQL server, then show info on listbox and textbox, and when user select an option then insert data to a table in the database.
My ASP.NET controls are:
<asp:ListBox ID="ListBox1" ClientIDMode="static" runat="server"></asp:ListBox>
<asp:Button ID="btnInsert" runat="server" Text="Start" OnClick="btnInsert_Click" />
I need the data loaded to a listbox, but not sure how to do directly. To retrieve the info and see if its working I did this:
protected void Page_Load(object sender, EventArgs e){
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
GridView2.DataSource= reader;
GridView2.DataBind();
con.Close();
var nProject = GridView2.Rows.Count;
for (int b = 0; b < nProject ; b++)
{
ListBox1.Items.Add(GridView2.Rows[b].Cells[0].Text);
}
}
Then I tried to set the selected info to a textbox, but nothing happens (because I managed to insert data from textbox to a SQL Server INSERT) :
protected void ListBox1_OnSelectedIndexChanged(object sender, System.EventArgs e)
{
TextBox2.Text = ListBox1.SelectedValue;
Response.Write("ListBox selectedIndexChanged");
}
The info is send back to the database with a button click:
protected void btnInsert_Click(object sender, EventArgs e)
{
var IP = "111.111.11";
txtStatus.Text = "Start";
txtProject.Text = "PR-02";
var indice = 0;
// This always returns "0"
if (ListBox1.SelectedItem != null)
{
indice = ListBox1.SelectedIndex;
}
txtProject.Text = indice.ToString();
// Sql INSERT works fine, but only with info manually created. I can't get the real info to work
SqlConnection con = new SqlConnection("****");
SqlCommand cmd = new SqlCommand(#"INSERT INTO [dbo].[table3]
([project]
,[user_task]
,[status]
,[ip]
,[location])
VALUES
('" + txtProject.Text + "', '" + txtUser.Text + "', '" + txtStatus.Text + "', '" + txtIP.Text + "', '" + txtLocation.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
The Page_Load is one of the first events to run every time there is a call to the server, this means that it runs before the btnInsert_Click event.
This means that you are repopulating the ListBox1 before checking the SelectedItem, this is why it always returns "0"
You have to consider this and use something like
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack || Page.IsCallback) return;
(...)
}
It is hard to understand what you want to do, but I think the ListBox1_OnSelectedIndexChanged is useless if you correct the Page_Load event.
Side notes:
You should really start by putting using statements where you can (on SqlConnection and SqlCommand)
Watch out for Sql Injections, may be a simple test program, but you should NEVER, EVER do this: #"INSERT INTO (...) VALUES ('" + txtProject.Text + "'"
use parameters instead:
using(SqlConnection con = new SqlConnection("****"))
using(SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[table3] ([project]) values (#project)", con))
{
cmd.Parameters.AddWithValue("#project", txtProject.Text);
}
It seems you are using .Net Framework with aspx pages, you should really consider using newer technologies (.net core).

How to make it work? C# GridView Delete Line

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

how to avoid two empty rows at single click in gridview

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.

Populating TextBox based on ComBox, Insert into Database through TextBox

I'm having troubles populating TextBoxes based on a ComboBox, Also insertion code won't work.
What should happen is, By selecting a customer from ComboBox, The details gets displayed on Text Boxes, And i can also add a customer to the ComboBox through the TextBoxes, Also there is a DataGridView displaying related info from another table based on my ComboBox selection but that's not the problem now.
Note:
I switched to Visual Studio 2012 recently, I'm assuming that's not a problem.
ComboBox exception:
An exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in System.Data.SqlServerCe.dll but was not handled in user code.
Save button exception:
Input string was not in a correct format.
About the save button, The CustomerID is an Auto increment number, So i should be able to leave it's TextBox blank but it doesn't work when i do.
Table Structure:
Customers
CustomerID [int] [PK] [AutoNumber]
Name [nvarchar]
Phone1 [int]
Phone2 [int]
Address [nvarchar]
Notes [ntext]
Code:
private void FillCombo()
{
string code = "SELECT CustomerID, Name FROM Customers";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
cBox1.DataSource = ds.Tables[0];
cBox1.DisplayMember = "Name";
cBox1.ValueMember = "CustomerID";
}
private void frmMain_Load(object sender, EventArgs e)
{
clsMain.con.Open();
FillCombo();
}
private void cBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string code = "SELECT * FROM Customers WHERE CustomerID='" + cBox1.Text + "'";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, clsMain.con);
SqlCeCommandBuilder cmd = new SqlCeCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds);
if (cBox1.SelectedIndex > 0)
{
txt1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
txt2.Text = ds.Tables[0].Rows[0]["Name"].ToString();
txt3.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
txt4.Text = ds.Tables[0].Rows[0]["Phone2"].ToString();
txt5.Text = ds.Tables[0].Rows[0]["Address"].ToString();
txt6.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
}
}
private void stripSave_Click(object sender, EventArgs e)
{
string code = "INSERT INTO Customers VALUES (#CustomerID, #Name, #Phone1, #Phone2, #Address, #Notes)";
SqlCeCommand cmd = new SqlCeCommand(code, clsMain.con);
cmd.Parameters.AddWithValue("#CustomerID", (txt1.Text); //Tried Parse and Convert.
cmd.Parameters.AddWithValue("#Name", txt2.Text);
cmd.Parameters.AddWithValue("#Phone1", txt3.Text);
cmd.Parameters.AddWithValue("#Phone2", txt4.Text);
cmd.Parameters.AddWithValue("#Address", txt5.Text);
cmd.Parameters.AddWithValue("#Notes", txt6.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
Sorry if it's a long code, But i thought it would be easier to spot the problems this way.
It seems like CustomerID is integral value, So you need to change
cmd.Parameters.AddWithValue("#CustomerID", txt1.Text);
to
cmd.Parameters.AddWithValue("#CustomerID", Int32.Parse(txt1.Text));
as per PhoenixReborn
if CustomerID is an auto increment, why are you trying to save it to the database? Kind of defeats the purpose.
then you need to edit your query to
string code = "INSERT INTO Customers(name, phone1, phone2, address, notes) VALUES (#Name, #Phone1, #Phone2, #Address, #Notes)";
SqlCeCommand cmd = new SqlCeCommand(code, clsMain.con);
cmd.Parameters.AddWithValue("#Name", txt2.Text);
cmd.Parameters.AddWithValue("#Phone1", txt3.Text);
cmd.Parameters.AddWithValue("#Phone2", txt4.Text);
cmd.Parameters.AddWithValue("#Address", txt5.Text);
cmd.Parameters.AddWithValue("#Notes", txt6.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
Try this instead:
private void stripSave_Click(object sender, EventArgs e)
{
int id;
string code;
SqlCeCommand cmd;
/*
If textbox is empty or input is not integer, then take the next id from table.
Otherwise, id is set to input value.
*/
if (txt1.Text == String.Empty || !int.TryParse(txt1.Text, out id))
{
/*
Selects max id + 1
If the table is empty, the result will be null
and coalesce will return 0 for the first id number
*/
code = "SELECT COALESCE((SELECT MAX(CustomerID) + 1 FROM Customers), 0);";
cmd = new SqlCeCommand(code, clsMain.con);
id = (int)cmd.ExecuteScalar();
}
code = "INSERT INTO Customers VALUES (#CustomerID, #Name, #Phone1, #Phone2, #Address, #Notes);";
cmd = new SqlCeCommand(code, clsMain.con);
cmd.Parameters.AddWithValue("#CustomerID", id);
cmd.Parameters.AddWithValue("#Name", txt2.Text);
cmd.Parameters.AddWithValue("#Phone1", txt3.Text);
cmd.Parameters.AddWithValue("#Phone2", txt4.Text);
cmd.Parameters.AddWithValue("#Address", txt5.Text);
cmd.Parameters.AddWithValue("#Notes", txt6.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
By the way, an important note about your code: Prefer to connect to database everytime you execute a query and close it afterwards. What I mean is that instead of keeping connection open for all the execution time, use something like this:
try
{
clsMain.con.Open();
cmd.ExecuteNonQuery();
clsMain.con.Close();
}
catch (Exception ex)
{
if (clsMain.con.State != ConnectionState.Closed)
clsMain.con.Close();
MessageBox.Show(ex.Message);
}

Unable to get the cell value in rowdeleting event in grid view

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,

Categories

Resources