我使用以下代码删除和编辑gridview中的一些值,但是当我单击删除时,它显示错误:
Object reference not set to an instance of an object. in line 48 i.e. con.open();
请帮我解决它。当我单击编辑并在显示的 txtboxes 中插入值然后单击更新时,它显示另一个错误:
Specified argument was out of the range of valid values. in the line 74 of my code i.e.
EmailID = (TextBox)GridView1.Rows[e.RowIndex].Cells[7].FindControl("EmailID");
我使用的代码是-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Admin_viewSalesmanDetails : System.Web.UI.Page
{
SqlConnection con;
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
using (SqlConnection con = new SqlConnection(strConnection))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select * from salesman_details";
cmd.Connection = con;
SqlDataSource1.DataBind();
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label EmpID = new Label();
EmpID = (Label)GridView1.Rows[e.RowIndex].Cells[2].FindControl("EmpID");
cmd = new SqlCommand("delete from salesman_setails where EmpID=" + EmpID.Text + "", con);
con.Open();
int k = cmd.ExecuteNonQuery();
con.Close();
if (k == 1)
{
Response.Write("<script>alert('Employee Deleted Successfully')</script>");
BindGrid();
}
else
{
Response.Write("<script>alert('Error Occured While Deleting')</script>");
BindGrid();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label EmpID = new Label();
TextBox PhnNo = new TextBox();
TextBox EmailID = new TextBox();
EmpID = (Label)GridView1.Rows[e.RowIndex].Cells[2].FindControl("EmpID");
PhnNo = (TextBox)GridView1.Rows[e.RowIndex].Cells[5].FindControl("PhnNo");
EmailID = (TextBox)GridView1.Rows[e.RowIndex].Cells[7].FindControl("EmailID");
cmd = new SqlCommand("update salesman_details set PhnNo='" + PhnNo.Text + "', EmailID='" + EmailID.Text + "' where EmpID=" + EmpID.Text + "", con);
con.Open();
int k = cmd.ExecuteNonQuery();
con.Close();
if (k == 1)
{
Response.Write("<script>alert('Employee Updated Successfully')</script>");
GridView1.EditIndex = -1;
BindGrid();
}
else
{
Response.Write("<script>alert('Error Occured While Updating')</script>");
BindGrid();
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}
}