I have an application in which I have an upload image page where I upload images and store those images in different folders under image folder and its path in a database. The flow of that goes like this:
user selects file from the system
user add description
user selects department from the drop-down list and according to that selection the image is stored in a different department's folder.
this is my uploadImage.cs page code:
In this page first we check that we have folder under Image/Department folder or not if not than we create folder and store image under that department else if already create that store image under that department
protected void btnSubmit_Click1(object sender, EventArgs e)
{
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["WebGallery"].ConnectionString;
string Description = tbImageName.Text.Trim();
string Priority = lblPriority.Text.Trim();
//Get Filename from fileupload control
string imgName = fileuploadimages.FileName.ToString();
//sets the image path
string imgPath = "Images/Departments/" + "" + ddlDepartment.SelectedValue + "/";
bool IsExists = System.IO.Directory.Exists(Server.MapPath(imgPath));
if (!IsExists)
System.IO.Directory.CreateDirectory(Server.MapPath(imgPath));
//then save it to the Folder
fileuploadimages.SaveAs(Server.MapPath(imgPath + imgName));
//Open the database connection
con.Open();
//Query to insert images name and Description into database
SqlCommand cmd = new SqlCommand("insert into Images(ImageName, Description, Path, Priority) values (#ImageName, #Description, #Path, #Priority)", con);
//Passing parameters to query
cmd.Parameters.AddWithValue("#ImageName", imgName);
cmd.Parameters.AddWithValue("#Description", Description);
cmd.Parameters.AddWithValue("#Path", imgPath + imgName);
cmd.Parameters.AddWithValue("#Priority", lblPriority.Text);
cmd.ExecuteNonQuery();
//Close dbconnection
con.Close();
tbImageName.Text = string.Empty;
}
In this page we create,edit,update and delete department. Now when user click on delete button i want to delete that folder so that all the image under that folder will also delete.
My departmentMaste.cs page code:
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Department_Master", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//int id = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
string id = gvDetails.DataKeys[e.RowIndex].Values["ID"].ToString();
TextBox txtDepartment = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtDepartment");
con.Open();
SqlCommand cmd = new SqlCommand("update Department_Master set DepartmentName='" + txtDepartment.Text + "'where ID=" + id, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = id + " Details Updated successfully";
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
string id = gvDetails.DataKeys[e.RowIndex].Values["ID"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Department_Master where ID=" + id, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Red;
lblresult.Text = id + " details deleted successfully";
}
}
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//getting username from particular row
string id = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ID"));
//identifying the control in gridview
ImageButton lnkbtnresult = (ImageButton)e.Row.FindControl("imgbtnDelete");
//raising javascript confirmationbox whenver user clicks on link button
if (lnkbtnresult != null)
{
lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + id + "')");
}
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtDepartment = (TextBox)gvDetails.FooterRow.FindControl("txtDepartment");
con.Open();
SqlCommand cmd =
new SqlCommand("insert into Department_Master values('" + txtDepartment.Text + "')", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Green;
lblresult.Text = txtDepartment.Text + " Details inserted successfully";
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = txtDepartment.Text + " Details not inserted";
}
}
}
i hope i am clear to you guys
How can I do that?
update your RowDeleting event.
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
string id = gvDetails.DataKeys[e.RowIndex].Values["ID"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Department_Master where id=" + id, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Table[0];
for (int i = 0; i < dt.rows.count; i++)
{
string imgPath = "Images/Departments/" + "" + dt.rows[i]["DepartmentName"] + "/";
bool IsExists = System.IO.Directory.Exists(Server.MapPath(imgPath));
if (IsExists)
System.IO.Directory.Delete(Server.MapPath(imgPath),true);
}
con.Close();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Department_Master where ID=" + id, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Red;
lblresult.Text = id + " details deleted successfully";
}
BindEmployeeDetails();
}
For Pop-up message,
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//getting username from particular row
string id = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ID"));
//identifying the control in gridview
ImageButton lnkbtnresult = (ImageButton)e.Row.FindControl("imgbtnDelete");
//raising javascript confirmationbox whenver user clicks on link button
if (lnkbtnresult != null)
{
lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + id + "');");
}
}
}
just make sure "ConfirmationBox" method is right to raise confirm window.
To Delete images from Images Table, you should have reference of Department_Master Table. like a Column named DepartmentID with foreign Key reference into Images table. even whenever you insert records into Images table, also insert respective DepartmentID, once you are done all these stuff, you can run delete command on Images table as
SqlCommand cmd = new SqlCommand("Delete from Images where DepartmentID="+id +"; delete from Department_Master where ID=" + id, con);
Add this code into aspx page
<script type="text/javascript">
function ConfirmationBox(id)
{
return confirm('Are you sure to delete department Id:'+ id +'?' );
}
</script>
Use GetFiles to get the files from directory and use GetParent to get directory from
the image.
string dir = Directory.GetParent(photoPathFromDB).FullName;
string[] files = Directory.GetFiles(dir);
foreach(string file in files)
//do stuff
Related
Basically, what I want to delete an entry form a dataviewtable which pulls data through from MySql. I thought this would be done fairly by effectively copying the modify code and substituting it for 'DELETE'. However, from the code below, you can clearly see that hasn't worked. I will copy most of my code for you:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HNR3NJB\\mysql;Initial Catalog=stock;Integrated Security=True");
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
con.Open();
sqlQuery = #"DELETE FROM [Products] WHERE [ProductID] = '" + textboxProductID.Text + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
}
else
{
MessageBox.Show("Record doesn't exist!", "ERROR:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Reading Data
LoadData();
}
So that's the delete button's code now for the add button and load data function
Add button:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//insert logic
con.Open();
if(textboxProductID.Text == "" || textboxProductName.Text == "")
{
MessageBox.Show("You have to enter either a product ID or product name", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
bool status = false;
if (comboboxStatus.SelectedIndex == 0)
{
status = true;
}
else
{
status = false;
}
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
sqlQuery = #"UPDATE [Products] SET [ProductName] = '" + textboxProductName.Text + "' ,[ProductStatus] = '" + status + "' WHERE [ProductID] = '" + textboxProductID.Text + "'";
}
else
{
sqlQuery = #"INSERT INTO [Stock].[dbo].[Products] ([ProductID],[ProductName],[ProductStatus]) VALUES
('" + textboxProductID.Text + "','" + textboxProductName.Text + "','" + status + "')";
}
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
textboxProductID.Clear();
textboxProductName.Clear();
LoadData();
}
}
LoadData function:
public void LoadData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//reading data from sql
SqlDataAdapter sda = new SqlDataAdapter("Select * From [stock].[dbo].[Products]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["ProductID"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["ProductName"].ToString();
if ((bool)item["ProductStatus"])
{
dataGridView1.Rows[n].Cells[2].Value = "Active";
}
else
{
dataGridView1.Rows[n].Cells[2].Value = "Deactive";
}
}
}
You're going to need the IfProductsExists method too:
private bool IfProductsExists(SqlConnection con, string productCode)
{
SqlDataAdapter sda = new SqlDataAdapter("Select 1 From [Products] WHERE [ProductID]='" + productCode + "'", con);
DataTable dt = new DataTable();
if (dt.Rows.Count > 0)
return true;
else
return false;
}
It's going to be an inventory system that's going to be used at work for the sale and inventory management of IT equipment.
I try to update data in grid view. When i press edit button in grid view row data will be fill in other page in relevant control and press update button data will be update.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditButton")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Response.Redirect("~/Home.aspx?Id=" + row.Cells[0].Text);
}
}
Destination page code
public partial class Home : System.Web.UI.Page
{
Property p = new Property();
int Id = 0;
protected void Page_Load(object sender, EventArgs e)
{
Id = Convert.ToInt32(Request.QueryString["Id"].ToString());
if (!IsPostBack)
{
BindTextBoxvalues();
}
}
private void BindTextBoxvalues()
{
string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("select * from tblUsers where Id=" + Id, con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
txtUsername.Text = dt.Rows[0][0].ToString();
txtEmail.Text = dt.Rows[0][1].ToString();
txtDob.Text = dt.Rows[0][2].ToString();
txtPass.Text = dt.Rows[0][3].ToString();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update tblUsers set UserName='" + txtUsername .Text + "',Email='" + txtEmail.Text + "',DOB=" + txtDob.Text + ",Password='" + txtPass.Text + "' where Id=" + Id, con);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
}
Response.Redirect("~/Admin/Home.aspx");
}
}
Error: Input string was not in a correct format.
protected void Page_Load(object sender, EventArgs e)
{
Id = Convert.ToInt32(Request.QueryString["Id"].ToString());
if (!IsPostBack)
{
I want it to show the selected value from the drop down list and show it on gridview. It is supposed to query from the database using Where to indicate the selected value to show. For example, I select james from the drop down list. It supposes to go to the database and query james row. After that the grid view is supposed to show only one value which james. But now I am having a problem where the grid view show every data that is available in the database.
public partial class Search_Engine : System.Web.UI.Page
{
#region Database
static string HostName = "localhost";
static string DatabaseName = "finalproject";
static string TableName = "truckinfo";
//static string TableBucket = "bucketbrigade";
static string UserName = "root";
static string Password = "";
//--- Used for access to database infomation-----
string ConnStr = "Data Source=" + HostName + ";" +
"Database=" + DatabaseName + ";" +
"User ID=" + UserName + ";" +
"Password=" + Password;
string Qry = "";
MySqlConnection Con;
MySqlCommand Cmd;
MySqlDataReader Rdr;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
using (Con = new MySqlConnection(ConnStr))
{
Con.Open();
using (Cmd = new MySqlCommand("SELECT * FROM truckinfo", Con))
{
using (Rdr = Cmd.ExecuteReader())
{
if (Rdr.HasRows)
{
DropDownList1.DataSource = Rdr;
DropDownList1.DataValueField = "truckplateno";
DropDownList1.DataTextField = "truckplateno";
DropDownList1.DataBind();
}
}
}
}
}
}
private void BindData()
{
DataTable dt = new DataTable();
try
{
MySqlConnection Con = new MySqlConnection(ConnStr);
Con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM " +
DatabaseName + "." + TableName , Con);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Con.Close();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Con = new MySqlConnection(ConnStr);
Con.Open();
try
{
String getquery;
// String a;
getquery = DropDownList1.Text;
TextBox1.Text = getquery;
// a = TextBox2.Text;
// TextBox1.Text = a;
Qry = #"SELECT * FROM finalproject.truckinfo WHERE truckplateno=" + "'" + getquery + "'" + ";";
Cmd = new MySqlCommand(Qry, Con);
Cmd.ExecuteNonQuery();
Con.Close();
BindData();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
You need to get the selected value using SelectedValue of dropdownlist and then query database using this value.
getquery = DropDownList1.SelectedValue;
Also you are using BindData method which will always select all data from database you need to seprate this method so only selected data is bind to gridview.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String getquery;
getquery = DropDownList1.Text;
MySqlConnection Con = new MySqlConnection(ConnStr);
Con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM finalproject.truckinfo WHERE truckplateno='" + getquery + "'", Con);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Con.Close();
}
You are calling ExecuteNonQuey function which is used to Insert or Update data in database so it will not return any data.
Also when using SqlDataAdapter you don't need to explicitly call
Open and Close function for opening and closing connection.
Change your DropDownlist_SelectedIndexChanged function to the following:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Con = new MySqlConnection(ConnStr);
DataTable dt = new DataTable();
try
{
Con.Open();
string getquery = DropDownList1.SelectedValue;
TextBox1.Text = getquery;
// a = TextBox2.Text;
// TextBox1.Text = a;
Qry = #"SELECT * FROM finalproject.truckinfo WHERE truckplateno=" + "'" + getquery + "'" + ";";
MySqlCommand ddlCMD = new MySqlCommand(Qry, Con);
MySqlDataAdapter msda = new MySqlDataAdapter(ddlCMD);
msda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally{
Con.Close();
}
}
I am trying to implement a button_click event in C# such that if the button is pressed, the gridview is filled with the query results but am getting the above error.
This is the code:
public partial class Pages_Managingpayment : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyServer"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
Load();
}
}
protected void Load() {
DataSet ds = new DataSet();
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No records on display";
}
protected void SearchButton_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from users", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
string passwords = GridView1.DataKeys[e.RowIndex].Value.ToString();
TextBox pass = (TextBox)GridView1.Rows[e.RowIndex].FindControl("Password");
TextBox usernames = (TextBox)GridView1.Rows[e.RowIndex].FindControl("username");
TextBox usertypes = (TextBox)GridView1.Rows[e.RowIndex].FindControl("usertype");
con.Open();
SqlCommand cmd = new SqlCommand("update users set User_Type='" + usertypes.Text + "',Username='" + usernames.Text + "' where password='" + passwords + "'", con);
cmd.ExecuteNonQuery();
con.Close();
//.ForeColor = Color.Green;
//lblresult.Text = username + " Details Updated successfully";
GridView1.EditIndex = -1;
BindEmployeeDetails();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindEmployeeDetails();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["UserId"].ToString());
string passwords = GridView1.DataKeys[e.RowIndex].Values["password"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from users where password='" + passwords + "'", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
// lblresult.ForeColor = Color.Red;
//lblresult.Text = username + " details deleted successfully";
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox usertypes = (TextBox)GridView1.FooterRow.FindControl("usertype");
TextBox usernames = (TextBox)GridView1.FooterRow.FindControl("username");
TextBox passwords = (TextBox)GridView1.FooterRow.FindControl("password");
con.Open();
SqlCommand cmd =
new SqlCommand(
"insert into users values('" + usertypes.Text + "','" +
usernames.Text + "','" + passwords.Text + "')", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
// lblresult.ForeColor = Color.Green;
//lblresult.Text = txtUsrname.Text + " Details inserted successfully";
}
else
{
//lblresult.ForeColor = Color.Red;
//lblresult.Text = txtUsrname.Text + " Details not inserted";
}
}
}
I guess here is an error in the code:
DataSet ds = new DataSet();
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
ds will not contain tables and therefore contain no Table[0]. It would be helpful though if you could break your code down to a few lines in which the error occurs.
In the Load() method you create a new DataSet and try to access it's non-existing table with the code ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());.
Try creating a new DataTable and adding it to the DataSet before binding it the GridView (Example Here).
And also, when you call the Load() method, make the condition if(!IsPostBack) as in:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Load();
}
}
Make sure you check the index before you use table or Row. I have modified your Load method and hope you can modify other places to correct the mistakes.
protected void Load() {
DataSet ds = new DataSet();
if(ds.Tables.Count == 0)
{
// Syntax might be wrong. I am trying to add new table if it is missing.
ds.Table.Add(new Table());
}
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No records on display";
}
I wanted to know if there was a way to select a row and delete on right click from grid view.
I have the delete statement but I just dont have how to select on right click.
I've seen a couple suggestions that say to use mousebuttons.right but that doesnt work for me and errors with the (mousebuttons does not exist in current context)
here is my current fill statement
protected void getGLDepts()
{
mpSearch.Focus();
string[] mpvalue = mpSearch.Text.Split('(',')');
string coa = "";
string map = "";
SqlConnection myconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Rollup2ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = myconn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "USP_GET_GL_BY_DEPT";
cmd.Parameters.Add("#DEPTCODE", SqlDbType.Int).Value = mpvalue[1].ToString();
foreach (ListItem item in mpcbl.Items)
{
if (item.Selected)
{
coa += "','" + item.Value;
}
}
if (coa != "") coa = coa.Substring(2, coa.Length - 2) + "'";
else coa = "''";
cmd.Parameters.Add("#COA", SqlDbType.VarChar).Value = coa;
foreach (ListItem item in exceptdefault.Items)
{
if (item.Selected)
{
map += "','" + item.Value;
}
}
if (map != "") map = map.Substring(2, map.Length - 2) + "'";
else coa = "''";
cmd.Parameters.Add("#MAP", SqlDbType.VarChar).Value = map;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
gvMapping.DataSource = ds;
gvMapping.DataBind();
lblGLDeptData.ForeColor = System.Drawing.Color.Black;
lblGLDeptData.Text = " " + ds.Tables[0].Rows.Count + " Cost Center/Funds are Mapped to this Department.";
}
else
{
gvMapping.DataSource = ds;
gvMapping.DataBind();
lblGLDeptData.ForeColor = System.Drawing.Color.Black;
lblGLDeptData.Text = " No Currently Mapped Cost Centers.";
}
}
catch (Exception ex)
{
lblGLDeptData.ForeColor = System.Drawing.Color.Red;
lblGLDeptData.Text = ex.Message;
}
finally
{
myconn.Close();
myconn.Dispose();
}
my select row statement
protected void gvSelect(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//e.Row.Cells[0].Style["display"] = "none";
e.Row.ToolTip = "Click to select row";
e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.gvMapping, "Select$" + e.Row.RowIndex);
}
}
and my delete statement
protected void delSysGLDepts(object sender, EventArgs e)
{
if (cbsys.Checked && !cbgl.Checked)
{
GridViewRow row = gvMapping.SelectedRow;
SqlConnection myconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Rollup2ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = myconn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "USP_DELETE_SYS_ROW";
cmd.Parameters.Add("#SYSID", SqlDbType.Int).Value = row.Cells[1].Text;
myconn.Open();
object count = cmd.ExecuteNonQuery();
myconn.Close();
myconn.Dispose();
getSysDepts();
Works well for me:
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onContextMenu ", ClientScript.GetPostBackEventReference(GridView1, "Select$" + e.Row.RowIndex.ToString()) + "; return false;");
}
}
protected override void Render(HtmlTextWriter writer)
{
for (int index = 0; index < GridView1.Rows.Count; index++)
{
ClientScript.RegisterForEventValidation(GridView1.UniqueID, "Select$" + index.ToString());
}
base.Render(writer);
}