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);
}
Related
I'd like to integrate an autocheck that prevent user to forget to save changes with a textbox 'Do you want to save change' Yes-No
If yes - > save
if no - > returns
Here's my code without the checking
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
OleDbConnection conn;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
conn = new
OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data
Source=" + #Application.StartupPath + "\\Database1.mdb");
fill_lb();
}
private void fill_lb()
{
listBox1.Items.Clear();
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [table1] ORDER BY firstn";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
listBox1.Items.Add(dr["firstn"].ToString());
}
conn.Close();
}
private void listBox1_SelectedIndexChanged(object sender,
EventArgs e)
{
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [table1] WHERE firstn='" +
listBox1.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
textBox_fn.Text = dr["firstn"].ToString();
textBox_ln.Text = dr["lastn"].ToString();
}
conn.Close();
}
private void button_savenew_Click(object sender, EventArgs e)
{
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO [table1] ([firstn],[lastn])
values ([#firstn],[#lastn])";
cmd.Parameters.AddWithValue("#firstn", textBox_fn.Text);
cmd.Parameters.AddWithValue("#lastn", textBox_ln.Text);
cmd.ExecuteNonQuery();
fill_lb();
conn.Close();
}
private void button_modify_Click(object sender, EventArgs e)
{
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "UPDATE [Table1] SET [firstn]=[#firstn],
[lastn]=[#lastn] WHERE firstn = '" +
listBox1.SelectedItem.ToString() + "'";
cmd.Parameters.AddWithValue("#firstn", textBox_fn.Text);
cmd.Parameters.AddWithValue("#lastn", textBox_ln.Text);
cmd.ExecuteNonQuery();
fill_lb();
conn.Close();
}
private void button_new_Click(object sender, EventArgs e)
{
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
}
}
}
What I've done with no success :
Bool modified = false
private void textBox_fn_TextChanged(object sender, EventArgs e)
{
modified = true;
}
private void textBox_ln_TextChanged(object sender, EventArgs e)
{
modified = true;
}
private void listBox1_SelectedIndexChanged(object sender,
EventArgs e)
{
if (modified.Equals(true))
{
DialogResult dialogr = MessageBox.Show("Do you want to
save change ?","", MessageBoxButtons.YesNo);
switch (dialogr)
{
case DialogResult.Yes:
button_savenew.PerformClick();
modifie = false;
break;
case DialogResult.No:
return;
}
}
modified = false;
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
}
This is not working because it ask to save everytime I click on listbox
What Can I do ?
I would look into using a MessageBox. It would greatly simplify what you are trying to do. Perform the check in the background, and if they didn't save do this:
string message = "Are you sure you don't want to save?";
string caption = "Error Detected in Input";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(message, "Are you Sure", buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
// Save file
}
if (result == System.Windows.Forms.DialogResult.No){
this.Close();
}
Remove the the associate code from listBox1_SelectedIndexChanged event and add to it the end of button_modify_Click. Try like:
private void Check()
{
if (modified.Equals(true))
{
DialogResult dialogr = MessageBox.Show("Do you want to
save change ?","", MessageBoxButtons.YesNo);
switch (dialogr)
{
case DialogResult.Yes:
button_savenew.PerformClick();
modifie = false;
break;
case DialogResult.No:
return;
}
}
modified = false;
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
}
private void button_modify_Click(object sender, EventArgs e)
{
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "UPDATE [Table1] SET [firstn]=[#firstn],
[lastn]=[#lastn] WHERE firstn = '" +
listBox1.SelectedItem.ToString() + "'";
cmd.Parameters.AddWithValue("#firstn", textBox_fn.Text);
cmd.Parameters.AddWithValue("#lastn", textBox_ln.Text);
cmd.ExecuteNonQuery();
fill_lb();
Check(); //<--added here
conn.Close();
}
Try resetting modified after DB update, at the end of button_modify_Click
I think I found the right way to do the job using the tag property.
first I add a new boolean that will check if I leave a textbox
bool left_txtbox = false; //when leaving textbox
then I add this code the the Leave property of textboxes
private void textBox_fn_Leave(object sender, EventArgs e)
{
name = listBox1.SelectedItem.ToString();
textBox_fn.Tag = textBox_fn.Text;
left_txtbox = true;
}
private void textBox_ln_Leave(object sender, EventArgs e)
{
name = listBox1.SelectedItem.ToString();
textBox_ln.Tag = textBox_ln.Text;
left_txtbox = true;
}
on listbox selected index change I add the check when leaving textbox
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (left_txtbox == true) Check(); // if txtbox has been left, do the check
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
if (conn.State != ConnectionState.Open) { conn.Close(); conn.Open(); }
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [table1] WHERE firstn='" + listBox1.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
textBox_fn.Text = dr["firstn"].ToString();
textBox_ln.Text = dr["lastn"].ToString();
}
conn.Close();
}
finally the check itself, it will compare the Tag with the value stored in DB
private void Check()
{
if (conn.State != ConnectionState.Open) { conn.Close(); conn.Open(); }
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [table1] WHERE firstn='" + name + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
try // ignore null values
{
if (textBox_fn.Tag.ToString() != dr["firstn"].ToString()) { modified = true; }
if (textBox_ln.Tag.ToString() != dr["lastn"].ToString()) { modified = true; }
}
catch { }
if (modified.Equals(true))
{
DialogResult dialogr = MessageBox.Show("Do you want to save change ? ", "", MessageBoxButtons.YesNo);
switch (dialogr)
{
case DialogResult.Yes:
button_savenew.PerformClick();
modified = false;
break;
case DialogResult.No:
modified = false;
return;
}
}
modified = false;
}
I think the code can be optimized
I click on edit button without sorting my column header in the DataGridView, this works fine, I can edit the row and values in a drop down fine.
However, when I sort the column and then hit edit - it allows me to edit the original DataGridView and not the sorted version.
I think its an issue binding the datagridview on the edit button as its not storing the sort order anywhere but can't seem to figure out how to save the sort session and apply it in the GetgvCaseListData() method.
The below code works fine before sorting, but breaks when the GridView is sorted and edit button is clicked:
protected void GetgvCaseListData()
{
string connectionstring = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection cn = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand("[dbo].cr_fe_list", cn);
cmd.Parameters.AddWithValue("#subteamno", SubTeam);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.CommandType = CommandType.StoredProcedure;
DataTable ds = new DataTable();
da.Fill(ds);
if (ds.Rows.Count > 0)
{
gvCaseList.DataSource = ds;
gvCaseList.DataBind();
ViewState["dirState"] = ds;
ViewState["sortdr"] = "Asc";
}
else
{
noresultsvalidation.Visible = true;
gvCaseList.DataSource = ds;
gvCaseList.DataBind();
ViewState["dirState"] = ds;
ViewState["sortdr"] = "Asc";
}
protected void gvCaseList_RowDataBound(object sender, GridViewRowEventArgs e)
{
MeasurementID = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "MeasurementID"));
string connectionstring = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection cn = new SqlConnection(connectionstring);
if (e.Row.Cells[10].Text == "OVERDUE")
{
e.Row.Cells[10].ForeColor = System.Drawing.Color.Red;
e.Row.Cells[10].Font.Bold = true;
}
if (e.Row.RowType == DataControlRowType.DataRow && ((e.Row.RowState & DataControlRowState.Edit) > 0))
{
cn.Open();
DropDownList DropDownList1 = (e.Row.FindControl("ddlException") as DropDownList);
TextBox tb1 = (e.Row.FindControl("ExceptionText") as TextBox);
SqlCommand cmd = new SqlCommand("[dbo].cr_fe_exception", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#SubTeamNo", SubTeam);
cmd.Parameters.AddWithValue("#MeasurementID", MeasurementID);
DataTable dt = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
a.Fill(dt);
}
cn.Close();
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "ExceptionDesc";
DropDownList1.DataValueField = "ExceptionID";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("--Select Exception--", "0"));
if (CurrentException != "")
{
DropDownList1.SelectedValue = DropDownList1.Items.FindByText(CurrentException).Value;
tb1.Enabled = true;
}
}
}
protected void gvCaseList_edit(object sender, GridViewEditEventArgs e)
{
Label label1 = (Label)gvCaseList.Rows[e.NewEditIndex].FindControl("Label1");
CurrentException = label1.Text;
gvCaseList.EditIndex = e.NewEditIndex;
GetgvCaseListData();
}
protected void gvCaseList_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtrslt = (DataTable)ViewState["dirState"];
if (dtrslt.Rows.Count > 0)
{
if (Convert.ToString(ViewState["sortdr"]) == "Asc")
{
dtrslt.DefaultView.Sort = e.SortExpression + " Desc";
ViewState["sortdr"] = "Desc";
}
else
{
dtrslt.DefaultView.Sort = e.SortExpression + " Asc";
ViewState["sortdr"] = "Asc";
}
gvCaseList.DataSource = dtrslt;
gvCaseList.DataBind();
}
}
I have a problem when click on submit button. the data still insert into database even though there is an invalid data.
public partial class surveyCreate : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
private string lblTextMessage;
protected void Page_Load(object sender, EventArgs e)
{
btnSubmitSurvey.Attributes.Add("onclick", "return PostPage();");
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
int i = 1;
foreach (string key in keys)
{
this.CreateTextBox("txtDynamic" + i);
i++;
}
if (!IsPostBack)
{
int a_unit = 0;
string username = (string)Session["Username"];
string query5 = "SELECT * FROM tblAdmin WHERE a_uname='" + username + "'";
con.Open();
SqlCommand cmd5 = new SqlCommand(query5, con);
SqlDataReader dr5 = cmd5.ExecuteReader();
if (dr5.Read())
{
a_unit = Convert.ToInt32(dr5["a_unit"]);
}
dr5.Close();
con.Close();
string queryA = "";
string queryB = "";
string queryC = "";
queryA = "SELECT * FROM tblUnit WHERE u_master = " + a_unit;
queryB = "SELECT * FROM tblProject ";
queryC = "SELECT * FROM tblSurveyTemplate where st_template = " + a_unit;
BindDropDownList(ddlunit, queryA, "u_name", "u_id", "SELECT UNIT");
//BindDropDownList(project, queryB, "pro_name", "pro_id", "SELECT PROJECT");
BindDropDownList(ddlTemplate, queryC, "st_name", "st_id", "SELECT TEMPLATE");
ddlproject.Enabled = false;
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
// string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
conn.Close();
}
}
ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
protected void unit_SelectedIndexChanged(Object sender, EventArgs e)
{
ddlproject.Enabled = true;
int u_id = int.Parse(ddlunit.SelectedItem.Value);
string query = "Select pro_id, pro_name from tblProject WHERE u_id=" + u_id;
BindDropDownList(ddlproject, query, "pro_name", "pro_id", "SELECT PROJECT");
}
protected void ddlTemplate_SelectedIndexChanged(Object sender, EventArgs e)
{
int st_id = int.Parse(ddlTemplate.SelectedItem.Value);
SqlDataSourceQuestions.SelectCommand = "SELECT sq_id, sq_question FROM tblSurveyQuestions WHERE st_id=" + st_id;
string query = "SELECT * FROM tblSurveyTemplate WHERE st_id=" + st_id;
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
LabelComment.Text = dr["st_comment"].ToString();
LabelIntro.Text = dr["st_intro"].ToString();
}
dr.Close();
con.Close();
if (st_id != 0)
PanelA.Visible = true;
else
PanelA.Visible = false;
}
/**
protected void project_SelectedIndexChanged(Object sender, EventArgs e)
{
project.Enabled = true;
project.Items.Clear();
project.Items.Insert(0, new ListItem("SELECT PROJECT", "0"));
int unitId = int.Parse(unit.SelectedItem.Value);
if (unitId > 0)
{
string query = string.Format("Select pro_id, pro_name from tblProject where pro_id = {0} ", unitId);
BindDropDownList(project, query, "pro_name", "pro_id", "SELECT PROJECT");
project.Enabled = true;
}
}
static int i = 0;
protected void btn_addp_Click(object sender, EventArgs e)
{
int j = 0;
i++;
for (j = 0; j < i; j++)
{
TextBox tb = new TextBox();
tb.Width = 350;
tb.ID = "MP" + j.ToString();
ph.Controls.Add(tb);
}
}
*/
protected void btn_addp_Click(object sender, EventArgs e)
{
int index = pnlTB.Controls.OfType<TextBox>().ToList().Count + 1;
this.CreateTextBox("txtDynamic" + index);
}
private void CreateTextBox(string id)
{
TextBox tb = new TextBox();
tb.ID = id;
tb.Width = 350;
pnlTB.Controls.Add(tb);
Literal lt = new Literal();
lt.Text = "<div style=height:3px ></div>";
pnlTB.Controls.Add(lt);
pnlTB.Controls.Add(new LiteralControl("<div style=height:3px ></div>"));
}
protected void GetTextBoxValues(object sender, EventArgs e)
{
}
//duplicate email
protected void cv_ServerValidate(object sender, ServerValidateEventArgs e)
{
//TextBox[] participant = { participant1, participant2, participant3 };
//if (participant1.Text == participant2.Text || participant2.Text == participant3.Text || participant1.Text == participant3.Text)
//{
// cvSubmit.ErrorMessage = "* Duplicate email! Please enter different email. ";
// cvSubmit.Focus();
// e.IsValid = false;
//}
}
here is the code for submit
protected void btnSubmitSurvey_Click(object sender, EventArgs e)
{
string a_id = "";
string username = (string)Session["Username"];
string query4 = "SELECT * FROM tblAdmin WHERE a_uname='" + username + "'";
con.Open();
SqlCommand cmd4 = new SqlCommand(query4, con);
SqlDataReader dr4 = cmd4.ExecuteReader();
if (dr4.Read())
{
a_id = dr4["a_id"].ToString();
}
dr4.Close();
con.Close();
if (Page.IsValid)
{
con.Open();
string query = "CreateSurvey";
string query1 = "ListParticipant";
int surveyID;
DateTime date_now = DateTime.Now;
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#sd_id", SqlDbType.Int, 0, "sd_id");
cmd.Parameters["#sd_id"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#sd_title", SqlDbType.NVarChar).Value = txtTitle.Text;
cmd.Parameters.Add("#sd_unit", SqlDbType.NVarChar).Value = ddlunit.SelectedValue;
cmd.Parameters.Add("#sd_project", SqlDbType.NVarChar).Value = ddlproject.SelectedValue;
cmd.Parameters.Add("#sd_year", SqlDbType.NVarChar).Value = txtYear.Text;
cmd.Parameters.Add("#st_id", SqlDbType.NVarChar).Value = ddlTemplate.SelectedValue;
cmd.Parameters.Add("#sd_datecreated", SqlDbType.DateTime).Value = date_now;
cmd.Parameters.Add("#sd_createdBy", SqlDbType.NVarChar).Value = a_id;
cmd.ExecuteNonQuery();
surveyID = (int)cmd.Parameters["#sd_id"].Value;
//validate email
bool email = Regex.IsMatch(participant.Text.Trim(), "\\w+([-+.']\\w+)*#\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
if (!email)
{
lbl2.Text = "Invalid email address";
return;
}
else
{
lbl2.Text = "";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#sp_email", SqlDbType.NVarChar).Value = participant.Text;
cmd1.Parameters.Add("#sd_id", SqlDbType.Int).Value = surveyID;
cmd1.ExecuteNonQuery();
}
foreach (TextBox textBox in pnlTB.Controls.OfType<TextBox>())
{
if (textBox.Text != "")
{
SqlCommand cmd2 = new SqlCommand(query1, con);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.Add("#sp_email", SqlDbType.NVarChar).Value = textBox.Text;
cmd2.Parameters.Add("#sd_id", SqlDbType.Int).Value = surveyID;
cmd2.ExecuteNonQuery();
}
}
string message = "Your survey details has been saved.";
string url = "surveyConfirm.aspx?surveyId=" + surveyID;
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += url;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
con.Close();
}
else
{
lbl2.Text = "Fill up the information required";
}
}
}
someone please help me to solve this problem. thank you
How to increase totaldownloads value in my database file code is given below
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataRow dr;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserId"] == null)
{
lblMessage.Visible = true;
GridView1.Visible = false;
//AppContent.Visible = false;
}
else
{
if (!Page.IsPostBack)
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
ArrayList myArrayList = ConvertDataSetToArrayList();
Literal objliteral = new Literal();
StringBuilder objSBuilder = new StringBuilder();
//Add some column to datatable display some products
dt.Columns.Add("appImg");
dt.Columns.Add("appName");
dt.Columns.Add("appLink");
dt.Columns.Add("appType");
dt.Columns.Add("TotalVisitors");
dt.Columns.Add("TotalDownloads");
dt.Columns.Add("RemainingVisitors");
// Display each item of ArrayList
foreach (Object row in myArrayList)
{
//Add rows with datatable and bind in the grid view
dr = dt.NewRow();
dr["appImg"] = ((DataRow)row)["AppImg"].ToString();
dr["appName"] = ((DataRow)row)["AppName"].ToString();
dr["appLink"] = ((DataRow)row)["AppLink"].ToString();
dr["appType"] = ((DataRow)row)["AppType"].ToString();
dr["TotalVisitors"] = "Plan Visitors: " + ((DataRow)row)["TotalVisitors"].ToString();
dr["TotalDownloads"] = "Downloaded: " + ((DataRow)row)["TotalDownloads"].ToString();
dr["RemainingVisitors"] = "Remaining Visitors: " + ((DataRow)row)["RemainingVisitors"].ToString();
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
public ArrayList ConvertDataSetToArrayList()
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
SqlCommand cmd = new SqlCommand();
if (Session["UserId"] != null && (Session["UserTypeId"] != null && Convert.ToInt32(Session["UserTypeId"]) != 2))
{
cmd.CommandText = "Select * from tblApp WHERE AppType = '" + Session["UserOSType"] + "' ORDER BY TotalVisitors";
}
else
{
cmd.CommandText = "Select * from tblApp ORDER BY TotalVisitors";
}
cmd.Connection = sqlcon;
sqlcon.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet dsApp = new DataSet();
da.Fill(dsApp, "tblApp");
ArrayList myArrayList = new ArrayList();
foreach (DataRow dtRow in dsApp.Tables[0].Rows)
{
myArrayList.Add(dtRow);
}
sqlcon.Close();
return myArrayList;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "download")
{
Button ib = (Button)e.CommandSource;
int index = Convert.ToInt32(ib.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Label l2 = (Label)row.FindControl("Label2");
Label lbTotallVisitors = (Label)row.FindControl("Label4");
Label lblTotalDownloads = (Label)row.FindControl("Label5");
Label lblRemainingVisitors = (Label)row.FindControl("Label6");
string updateSQL = "UPDATE tblUser SET DownloadedApps = '" + lbl + "', Amount = '" + Session["Amount"] + "', TotalAmount='" + Session["TotalAmount"] + "' WHERE Id= '" + Session["UserId"] + "'";
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString()))
{
using (SqlCommand updateCommand = new SqlCommand(updateSQL, sqlConn))
{
sqlConn.Open();
updateCommand.ExecuteNonQuery();
updateCommand.Connection.Close();
}
}
Response.Redirect(l2.Text);
}
}
UPDATE Table SET Column = Column + 1
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