在c#中使用gridview与sql server进行搜索,编辑和删除

时间:2014-03-04 14:30:26

标签: c# asp.net sql gridview

我正在使用Gridview按钮编辑和删除sql DB中的记录,我使用特定标准的问题(通过文本框和组合框搜索)然后我编辑结果这里是我使用的代码:

protected void Page_Load(object sender, EventArgs e)
{

    conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["zamzammembersConnectionString"].ConnectionString);

    if (!IsPostBack)
    {
     bind();

    }
    }

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{

    GridView1.EditIndex = e.NewEditIndex;
    bind();

}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{

    GridView1.EditIndex = -1;

    bind();

}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
    Label lbl = (Label)row.FindControl("lblid");
    TextBox textname = (TextBox)row.FindControl("textbox1");
    TextBox textmarks = (TextBox)row.FindControl("textbox2");
    GridView1.EditIndex = -1;
    conn.Open();
    SqlCommand cmd = new SqlCommand("update  emp set marks=" + textmarks.Text + " , name='" + textname.Text + "' where rowid=" + lbl.Text + "", conn);
    cmd.ExecuteNonQuery();
    conn.Close();
    bind();

}
public void bind()
{
    conn.Open();
    SqlCommand com = new SqlCommand("select zam_pcinfo.employe_name as Name , zam_location.locationname as Location from zam_pcinfo  inner join zam_location on zam_pcinfo.location_id = zam_location.locationId where zam_pcinfo.employe_name like @name or zam_location.locationname like @locationname;", conn);
    com.Parameters.AddWithValue("@name", SqlDbType.VarChar).Value = nametxt.Text;
    com.Parameters.AddWithValue("@locationname", SqlDbType.VarChar).Value = locationdrop.SelectedValue;
    SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
    GridView1.DataSource = ds.Tables[0];
    GridView1.DataBind();
    conn.Close();
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{

}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{

}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
    Label lbldeleteID = (Label)row.FindControl("lblid");
    conn.Open();
    SqlCommand cmd = new SqlCommand("delete  emp where rowid=" + lbldeleteID.Text + "", conn);
    cmd.ExecuteNonQuery();
    conn.Close();
    bind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    bind();

}

}

当我尝试将bind()方法中的相同代码设置为按钮时,它工作正常,但我无法对其进行编辑和删除。如何使用我搜索的数据在gridview中进行编辑和删除?

0 个答案:

没有答案