Unable to get the cell value in rowdeleting event in grid view - c#

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,

Related

C#: How would I change the contents of a drop down list upon the change of another?

I am new to C# and am trying to learn how I would be able to change the contents of one drop down list upon the change of another? My current attempt as shown below was unsuccessful, so any advice or help would be appreciated.
protected void drpDwnSchool_TextChanged(object sender, EventArgs e)
{
drpDwnTeacher.Items.Clear();
string selectedSchool = drpDwnSchool.SelectedValue.ToString();
String sqlQueryTeacher = "SELECT * FROM Teacher WHERE SchoolName = '" + selectedSchool + "'";
SqlConnection sqlConnect = new SqlConnection(WebConfigurationManager.ConnectionStrings["Lab1"].ToString());
SqlCommand sqlCommand1 = new SqlCommand();
sqlCommand1.Connection = sqlConnect;
sqlCommand1.CommandType = CommandType.Text;
sqlCommand1.CommandText = sqlQueryTeacher;
sqlConnect.Open();
SqlDataReader queryResultsTeacher = sqlCommand1.ExecuteReader();
while (queryResultsTeacher.Read())
{
string LastName = queryResultsTeacher["LastName"].ToString();
drpDwnTeacher.Items.Add(queryResultsTeacher["LastName"].ToString());
}
sqlConnect.Close();
}
Is it not populating the second list? if so try the "SelectedIndexChanged" event instead of text changed.
Ok, a few issues.
So, on page load, we assume you load up the first drop down.
if (IsPostBack == false)
{
// first time page load schools
LoadSchools();
}
And our code to load the combo box:
public void LoadSchools()
{
string strSQL = "SELECT SchoolName FROM tblSchools ORDER BY SchoolName";
this.DropDownSchools.DataSource = Myrst(strSQL);
this.DropDownSchools.DataBind();
}
So, on the page load, the above fills out the dropdown (combo) with the list of Schools.
Now, when you select a School?
Well, first, you need to set auto-past back for the school combo box.
Now, when a School is selected, you can now display teachers.
I would use the selected index changed, not the text change like you have.
So, that code would look like:
protected void DropDownSchools_SelectedIndexChanged(object sender, EventArgs e)
{
string strSQL;
strSQL = "SELECT Teacher from Teachers WHERE School = '" +
DropDownSchools.SelectedValue + "' ORDER BY Teacher";
DropDownTeachers.DataSource = MyRst(strSQL);
DropDownTeachers.databind();
}
And since for every sql query you have to write for the next 10 years, and create the cmd object, the connect object and the datatable object? Well, lets save some fingers, and you can use a public routine placed in your app_code or where ever you are placing your global wide code. That routine would look like:
public DataTable Myrst(string strSQL, string strCon = "")
{
// this also allows one to pass custom connection string
// - if not passed, then default
if (strCon == "") {
strCon =
ConfigurationManager.ConnectionStrings("WebEasy.My.MySettings.Test3").ConnectionString;
}
SqlConnection mycon = new SqlConnection(strCon);
SqlDataAdapter oReader = new SqlDataAdapter();
DataTable rstData = new DataTable();
oReader.SelectCommand = new SqlCommand(strSQL, mycon);
try
{
oReader.Fill(rstData);
return rstData;
}
catch
{
return null;
}
}
My c# is a bit weak but the above should work.
However, we should be using parameters for this. While dropdowns are not really direct user input, as a future habit, the above code should be using parameters and not string concatenation for the sql.
What works well is to modify the above MyRst to take a sql command object in place of a string, but the above is a good start as to how you can get this type of code to work.
I think the simplest way will be to set the Dropdownlist DataTextField from the HTML source as follows
<asp:DropDownList ID="DropDownList1" DataTextField="YourFieldNameHere" runat="server" />
And also make sure that AutoPostBack is set to true on the Dropdownlist you intend to use for populating the second Dropdownlist.
While on codebehind, bind the Dropdownlist to database as below
protected void drpDwnSchool_TextChanged(object sender, EventArgs e)
{
string selectedSchool = drpDwnSchool.SelectedValue.ToString();
String sqlQueryTeacher = "SELECT * FROM Teacher WHERE SchoolName = '" + selectedSchool + "'";
SqlConnection sqlConnect = new SqlConnection(WebConfigurationManager.ConnectionStrings["Lab1"].ToString());
SqlCommand sqlCommand1 = new SqlCommand();
sqlCommand1.Connection = sqlConnect;
sqlCommand1.CommandType = CommandType.Text;
sqlCommand1.CommandText = sqlQueryTeacher;
sqlConnect.Open();
SqlDataReader queryResultsTeacher = sqlCommand1.ExecuteReader();
if(queryResultsTeacher.HasRows){
DropDownList1.DataSource = queryResultsTeacher;
DropDownList1.DataBind();
}
sqlConnect.Close();
}

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 add validations on the textboxes in edit/update data mode?

i have a add product function. after adding those, it will then be viewed. along with the view function is a delete and update link. it works perfectly fine. When i click on the update, textboxes are visible for editing. again, it works fine. but what i want to do is to add validations to it. like if the value should only contain a number, then it will restrict any characters to that update. here is my code behind:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
//TextBox txtname=(TextBox)gr.cell[].control[];
TextBox textName = (TextBox)row.Cells[0].Controls[0];
TextBox textDesc = (TextBox)row.Cells[1].Controls[0];
TextBox textQuantity = (TextBox)row.Cells[3].Controls[0];
TextBox textProductPrice = (TextBox)row.Cells[4].Controls[0];
//TextBox textadd = (TextBox)row.FindControl("txtadd");
//TextBox textc = (TextBox)row.FindControl("txtc");
GridView1.EditIndex = -1;
conn.Open();
//SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
SqlCommand cmd = new SqlCommand("update Products set ProductName='" + textName.Text + "',ProductDescription='" + textDesc.Text + "',ProductQuantity='" + textQuantity.Text + "',ProductPrice ='" + textProductPrice.Text + "'where ProductID='" + userid + "'", conn);
cmd.ExecuteNonQuery();
conn.Close();
gvbind();
//GridView1.DataBind();
}
any ideas on what can i do to add validations. the reason for this is that when i try to input for example "abc" to the
TextBox textQuantity = (TextBox)row.Cells[3].Controls[0];
it gives me an error that it cannot be converted. please help. thanks!
You have to find control on each of the gridview row
Below is an example
TextBox textQuantity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtBoxId");
if (string.IsNullOrEmpty(textQuantity .Text))
{
//Validation failed
return;
}

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.

How to use the GridView AutoGenerateDeletebutton

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.

Categories

Resources