Sunday, May 31, 2009

Delete multifile entry from gridview

AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
ShowFooter="true">






OnClick="btnDelete_Click"
OnClientClick="return DeleteConfirmation();"/>


HeaderText="ID"
SortExpression="ID" />
HeaderText="Title"
SortExpression="Title" />
HeaderText="Director"
SortExpression="Director" />
HeaderText="Date"
SortExpression="date" />
HeaderText="BoxOfficeTotal"
SortExpression="boxofficetotal" />







create your data source which can be sql , access whatever u want ..........

C# code


using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Specialized;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string strcon = "Data Source=.;Initial Catalog=pubs;Persist Security Info=True;User ID=sa;Password=sa";
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnDelete_Click(object sender, EventArgs e)
{
StringCollection idCollection = new StringCollection();
string strID = string.Empty;

//Loop through GridView rows to find checked rows
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)
GridView1.Rows[i].Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = GridView1.Rows[i].Cells[1].Text;
idCollection.Add(strID);
}
}
}

//Call the method to Delete records
DeleteMultipleRecords(idCollection);

// rebind the GridView
GridView1.DataBind();
}
private void DeleteMultipleRecords
(StringCollection idCollection)
{
//Create sql Connection and Sql Command
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand();
string IDs = "";

foreach (string id in idCollection)
{
IDs += id.ToString() + ",";
}
try
{
string strIDs =
IDs.Substring(0, IDs.LastIndexOf(","));
string strSql = "Delete from movie WHERE id in (" + strIDs + ")";
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
con.Close();
}
}
}



0 comments:

Post a Comment

plzz give the comment