Mihir
Mihir

Reputation: 8734

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?

Upvotes: 2

Views: 12189

Answers (4)

Lohini priyanka
Lohini priyanka

Reputation: 1

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,

Upvotes: 0

Mihir
Mihir

Reputation: 8734

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.

Upvotes: 3

Shafqat Masood
Shafqat Masood

Reputation: 2570

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

Upvotes: 3

user2289490
user2289490

Reputation: 747

try the following code:

var empId = Convert.ToInt32(this.gvDetails.DataKeys[e.RowIndex].Values["EmpId"].ToString());

Upvotes: 1

Related Questions