I have some dynamically generated checklist-items. When user deletes them, confirmation box should appear. How can i do that ?
protected void btndelete_Click(object sender, EventArgs e)
{
try
{
string conn = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
con.Open();
check:
if (CheckBoxList1.SelectedItem != null)
{
foreach (ListItem l in CheckBoxList1.Items)
{
if (l.Selected)
{
SqlCommand cmd = new SqlCommand("Drop Table " + l, con);
cmd.ExecuteNonQuery();
Label4.ForeColor = Color.Red;
Label4.Text = " PaperSet Deleted successfully";
CheckBoxList1.Items.Remove(l);
papersetlist.Items.Remove(l);
Psetlist.Items.Remove(l);
goto check;
}
}
}
con.Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is delete button event code.
You just need to write something like this
<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete"
OnClientClick="return confirm('Are you certain you want to delete this item?');">
</asp:LinkButton>
Related
I have a Add to Cart button that show different text and enabled/disabled based on the stock left and if it is within the cart of the user.
asp:Button CssClass="btn btn-outline-dark mt-auto" ID="Button1" runat="server" CommandArgument='<%# Eval("prod_id") %>' Text='<%# Convert.ToInt32(Eval("prod_quantity")) > 0 ? Convert.ToInt32(Eval("is_in_cart")) < 1 ? "Add To Cart" : "Already in Cart" : "Sold out" %>' Enabled='<%# Convert.ToInt32(Eval("prod_quantity")) > 0 ? Convert.ToInt32(Eval("is_in_cart")) < 1 ? true : false : false %>' OnClick="Button1_Click" />
And this is my code behind to perform all the relevant SQL operations to update the database.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String id = Session["id"].ToString();
string test = Convert.ToString(Page.FindControl("HiddenField1"));
string strCon = ConfigurationManager.ConnectionStrings["WebConfigConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strCon))
{
string strHome = "SELECT p.prod_id, p.prod_name, p.prod_desc, p.prod_quantity, p.prod_price, p.prod_photo, COUNT(c.prod_id) AS is_in_cart FROM product p LEFT OUTER JOIN cart_item c ON p.prod_id = c.prod_id WHERE c.id = '" + id + "' OR c.id IS NULL GROUP BY p.prod_id, p.prod_name, p.prod_desc, p.prod_price, p.prod_photo, p.prod_quantity;";
using (SqlCommand cmdHome = new SqlCommand(strHome, con))
{
con.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdHome.ExecuteReader());
RepeaterHome.DataSource = rstData;
RepeaterHome.DataBind();
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
int prodId = Convert.ToInt32(btn.CommandArgument);
String id = Session["id"].ToString();
string strCon = ConfigurationManager.ConnectionStrings["WebConfigConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strCon))
{
string strCart = "INSERT INTO CART_ITEM (id, prod_id, quantity) values (#id, #prod_id, #quantity)";
using (SqlCommand cmdCart = new SqlCommand(strCart, con))
{
try
{
con.Open();
cmdCart.Parameters.AddWithValue("#id", id);
cmdCart.Parameters.AddWithValue("#prod_id", prodId);
cmdCart.Parameters.AddWithValue("#quantity", 1);
SqlDataReader dtrCart = cmdCart.ExecuteReader();
dtrCart.Close();
con.Close();
} catch (SqlException)
{
Response.Write("<script>alert('Item already in cart!')</script>");
}
}
}
Response.Redirect("home.aspx");
}
However, when I first click the button, the database is updated but the web page will not be updated, and by second click it shows the changes of the first click therefore it is delayed. A refresh or a "Response.Redirect("xxx.aspx") as I've attempted above is the only way I've found to solve my problem right now, any idea?
I have a function(PopulateStudents) that populates a dropdownlist with results from a database. This function is called on two different occasions: When a query string with id is provided, and in an onselectedindexchanged event. Basically, if an ID is provided from the URL, then get a database record of a student's ID, which contains semesterID and courseID. Then, all DDLs are populated based on the studentID.
If there is no ID in the URL, the user selects a semester from a DDL. Then the course DDL is populated based on the semester ID selected in the semester DDL. Then, the student DDL is populated based on the selected course.
The problem is that the PopulateStudent function works fine when no ID is provided in the query string and the user has to select the semester and then course. When the ID is provded in the query string, the PopulateStudents function does not work. The function throws an error that says Invalid attempt to call FieldCount when reader is closed. What is wrong with my code?
Here is the aspx.cs file:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
GetStudentScores(Convert.ToInt32(Request.QueryString["id"]));
string connString;
connString = RetrieveConnectionString();
SqlConnection conn = new SqlConnection(connString);
try
{
using (conn)
{
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.GetEnrolleeDetails", conn);
cmd.Parameters.Add("#enrollmentID", System.Data.SqlDbType.Int);
cmd.Parameters["#enrollmentID"].Value = Convert.ToInt32(Request.QueryString["id"]);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
int semesterID = Convert.ToInt32(reader["semesterId"]);
int courseID = Convert.ToInt32(reader["courseId"]);
PopulateCourses(semesterID);
PopulateStudents(courseID);
DDSemester.SelectedValue = Convert.ToString(semesterID);
DDCourse.SelectedValue = Convert.ToString(courseID);
DDStudent.SelectedValue = Request.QueryString["ID"];
}
}
catch (Exception err)
{
lblStatus.Text = err.Message;
}
finally
{
conn.Close();
conn.Dispose();
}
}
}
}
protected void DDCourse_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
PopulateStudents(Convert.ToInt32(DDCourse.SelectedValue));
}
}
protected void DDStudent_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
GetStudentScores(Convert.ToInt32(DDStudent.SelectedValue));
}
}
protected void DDSemester_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
PopulateCourses(Convert.ToInt32(DDSemester.SelectedValue));
}
}
private void PopulateCourses(int semesterID)
{
string connString;
connString = RetrieveConnectionString();
SqlConnection conn = new SqlConnection(connString);
try
{
using (conn)
{
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.GetSemesterCourses", conn);
cmd.Parameters.Add("#semesterID", System.Data.SqlDbType.Int);
cmd.Parameters["#semesterID"].Value = semesterID;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
DDCourse.DataSource = cmd.ExecuteReader();
DDCourse.DataTextField = "courseName";
DDCourse.DataValueField = "courseId";
DDCourse.DataBind();
}
}
catch (Exception err)
{
lblStatus.Text = err.Message;
}
finally
{
conn.Close();
conn.Dispose();
}
}
private void PopulateStudents(int courseID)
{
string connString;
connString = RetrieveConnectionString();
SqlConnection conn = new SqlConnection(connString);
try
{
using (conn)
{
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.CourseEnrollment", conn);
cmd.Parameters.Add("#courseId", System.Data.SqlDbType.Int);
cmd.Parameters["#courseId"].Value = courseID;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
DDStudent.DataSource = cmd.ExecuteReader();
DDStudent.DataTextField = "fullName";
DDStudent.DataValueField = "enrollmentId";
this.DataBind();
}
}
catch (Exception err)
{
lblStatus.Text = err.Message;
}
finally
{
conn.Close();
conn.Dispose();
}
}
Here is the asp:
<asp:Label ID="Label1" runat="server" Text="Semester:"></asp:Label>
<asp:DropDownList ID="DDSemester" runat="server" AutoPostBack="True" AppendDataBoundItems="true" DataSourceID="SqlDataSource1" DataTextField="semesterName" DataValueField="semesterId" OnSelectedIndexChanged="DDSemester_SelectedIndexChanged">
<asp:ListItem Text="Select a Semester"></asp:ListItem>
</asp:DropDownList><br />
<asp:Label ID="Label15" runat="server" Text="Course:"></asp:Label>
<asp:DropDownList ID="DDCourse" runat="server" AutoPostBack="True" AppendDataBoundItems="true" OnSelectedIndexChanged="DDCourse_SelectedIndexChanged">
<asp:ListItem Text="Select a Course"></asp:ListItem>
</asp:DropDownList><br />
<asp:Label ID="Label16" runat="server" Text="Student"></asp:Label>
<asp:DropDownList ID="DDStudent" runat="server" AutoPostBack="true" AppendDataBoundItems="true" OnSelectedIndexChanged="DDStudent_SelectedIndexChanged">
<asp:ListItem Text="Select a Student"></asp:ListItem>
</asp:DropDownList><br />
Thanks for your time.
There was actually one difference between the PopulateCourses and PopulateStudents functions that I didn't notice. In courses, I used DDCourse.DataBind() and in students I used this.DataBind().
In the populatestudents function, changing this.DataBind() to DDStudent.DataBind() fixed my problem.
I have a link button as follow
<asp:LinkButton ID="LinkButtonSearchClient" PostBackUrl="~/UI/clients.aspx" runat="server">Recherche </asp:LinkButton>
i want get a query string from it
<asp:LinkButton ID="LinkButtonSearchClient" PostBackUrl="~/UI/clients.aspx?id=12" runat="server">Recherche </asp:LinkButton>
and the id value comes from the source code
public string ID
{
get { return ViewState["id"]; }
}
To get the value on page load (in the backend .cs file) :
protected void Page_Load(object sender, EventArgs e)
{
var id = Request.QueryString["id"];
if (id != null)
{
// use id
}
}
Or you might want to put the id into the link (in the html) :
<asp:LinkButton ID="LinkButtonSearchClient" runat="server"
NavigateUrl='<%# String.Format("~/UI/clients.aspx?id={0}", Eval("ID"))%>'
Text='Recherche'></asp:LinkButton>
You probably do not need a postback, look here : PostbackUrl vs NavigateUrl
Try this,
public string ID
{
get { Request.QueryString["id"]; }
}
Edit : In your page load set your postback url like this, access postbackurl in server side
LinkButtonSearchClient.PostBackUrl = "~/UI/clients.aspx?id=" + this.ID;
See my following example :
in design as follow
<asp:HyperLink ID="HLink" runat="server"
NavigateUrl='<%#"Mobiles_Details.aspx?ID=" + Eval("ID") %>' Text='<%#
Bind("Name") %>' Height="70px" Width="200px" Font-Bold="true" Font-
Size="10pt" Font-Names="Times New Roman" />
In coding the class Mobiles_Details is:
public partial class Mobiles_Details : System.Web.UI.Page
{
public string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
Session["UserID"] = "100";
//int ID = 102;
int ID = Convert.ToInt32(Request.QueryString["ID"].ToString());
Session["Product_ID"] = ID;
if (Session["UserID"] == null || Session["UserID"].ToString() == string.Empty)
{
Response.Redirect("Login.aspx", false);
}
else
{
if (ID != null)
{
DataTable dt = Load_Items_ID(Convert.ToInt32(Session["UserID"].ToString()), ID);
lbl_Name.Text = dt.Rows[0]["Name"].ToString();
lbl_Price.Text = dt.Rows[0]["Price"].ToString();
lbl_Details.Text = dt.Rows[0]["Details"].ToString();
img_Product.ImageUrl = dt.Rows[0]["image"].ToString();
}
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('An Error has been occured ');" + ex.ToString(), true);
}
}
}
public DataTable Load_Items_ID(int UserID, int ID)
{
DataTable Returned_Value = new DataTable();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Products where UserID= " + UserID + " and Status='False' and ID =" + ID))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(Returned_Value);
}
}
}
}
return Returned_Value;
}
}
I am searching and posting a lot in this issue,but could not get the satisfactory answer.I wanted to make sure that whenever I am making a call to server the value of Textbox should be the one which is the most updated one.
But when I am making the call to server the old value of the textbox persists.I know it is something to do with the postback,but I am not getting the exact way to get the updated value of textbox in my .cs file.
Please tell me what are the necessary steps that I should take to always get the latest value of the textbox.
Here is my code which is not working:
protected void Page_Load(object sender, EventArgs e)
{
int contentID = Convert.ToInt32(Request.QueryString["contentid"]);
if (contentID != 0)
{
if (!this.IsPostBack)
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text="Inside not PostBack";
}
else
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text="Inside PostBack";
}
}
else
Response.Write("Invalid URL for article");
}
public void getContentBody(int contentID)
{
try
{
//////////////Opening the connection///////////////
mycon.Open();
string str = "select content from content where contentID='" + contentID + "'";
//Response.Write(str);
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = str;
dr = command1.ExecuteReader();
if (dr.Read())
{
content = dr[0].ToString();
}
}
catch (Exception ex)
{
Response.Write("Exception reading data" + ex);
}
finally
{
dr.Close();
mycon.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//string textboxvalue = Request.Form[TextBox1.UniqueID];
mycon.Open();
string query = "update content set content='" +TextBox1.Text + "' where contentID= '"+contentID +"'";
msg_lbl.Text = query;
try
{
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = query;
command1.ExecuteNonQuery();
msg_lbl.Text = "text" + TextBox1.Text;
}
catch (Exception ex)
{
msg_lbl.Text = "Exception in saving data" + ex;
}
finally
{
mycon.Close();
}
}
Here is my aspx page code:
<asp:TextBox ID="TextBox1" runat="server" Height="500px"
TextMode="MultiLine" Width="90%" AutoPostBack="True"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Delete post" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Save changes" />
<asp:Button ID="Button3" runat="server" Text="Cancel" />
</p>
Please also tell me the reason why it is not working and how I can make it work.
Thanks,
Amandeep
According to the ASP.NET's life cycle, Page_Load executes before Button2_Click, so you have to show your updated text in the Button2_Click:
protected void Page_Load(object sender, EventArgs e)
{
contentID = Convert.ToInt32(Request.QueryString["contentid"]);
if (contentID != 0)
{
if (!this.IsPostBack)
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text = "Inside not PostBack";
}
}
else
Response.Write("Invalid URL for article");
}
public void getContentBody(int contentID)
{
try
{
//////////////Opening the connection///////////////
mycon.Open();
string str = "select content from content where contentID='" + contentID + "'";
//Response.Write(str);
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = str;
dr = command1.ExecuteReader();
if (dr.Read())
{
content = dr[0].ToString();
}
}
catch (Exception ex)
{
Response.Write("Exception reading data" + ex);
}
finally
{
dr.Close();
mycon.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//string textboxvalue = Request.Form[TextBox1.UniqueID];
mycon.Open();
string query = "update content set content='" + TextBox1.Text + "' where contentID= '" + contentID + "'";
msg_lbl.Text = query;
try
{
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = query;
command1.ExecuteNonQuery();
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text = "text" + TextBox1.Text;
}
catch (Exception ex)
{
msg_lbl.Text = "Exception in saving data" + ex;
}
finally
{
mycon.Close();
}
}
Please inspect my C# code below and let me know where I am going wrong. Here is what I am experiencing:
1.) If I empty the SendReport column in SQL Server and load the page, the second row of the SendReport automatically gets populated with a 1.
2.) I can place a checkmark, click the button and the SendReport values successfully populate in SQL Server. However, if I uncheck any of them and click the button, none of the values change from 1 to 0. Please help!
$<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
<br />
<asp:Button ID="Button1" runat="server" Text="Save Changes" OnClick="Button1_Click" />
<br />
BACKPAGE:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindCheckBoxList();
}
}
// Setting up the ConnectionString
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["IPdataConnectionString"].ConnectionString;
}
// Binding the CheckBoxList with Data
private void BindCheckBoxList()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT Partner, ID, SendReport FROM Rorts";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
CheckBoxList1.DataSource = dt;
CheckBoxList1.DataTextField = "Partner"; // the items to be displayed in the list items
CheckBoxList1.DataValueField = "SendReport"; // the id of the items displayed
CheckBoxList1.DataBind();
//Setting the Selected Items in the ChecBoxList based from the value in the database
//to do this, lets iterate to each items in the list
for (int i = 0; i < dt.Rows.Count; i++)
{
if (!string.IsNullOrEmpty(dt.Rows[i]["SendReport"].ToString()))
{
CheckBoxList1.Items[i].Selected = Convert.ToBoolean(dt.Rows[i]["SendReport"]);
}
}
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
// Creating the Method for Saving the CheckBoxList Selected Items to the database
private void Update(string name, bool SendReport)
{
SqlConnection connection = new SqlConnection(GetConnectionString());
SqlCommand cmd;
string sqlStatement = string.Empty;
try
{
// open the Sql connection
connection.Open();
sqlStatement = "UPDATE Rorts SET SendReport = #SendReport WHERE Partner = #Partner";
cmd = new SqlCommand(sqlStatement, connection);
cmd.Parameters.AddWithValue("#Partner", name);
cmd.Parameters.AddWithValue("#SendReport", SendReport);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert/Update Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
// close the Sql Connection
connection.Close();
}
}
// Calling the Method for Saving the state of CheckBoxList selected items
protected void Button1_Click(object sender, EventArgs e)
{
string PartnerName = string.Empty;
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
PartnerName = CheckBoxList1.Items[i].Text;
Update(PartnerName, CheckBoxList1.Items[i].Selected);
}
}
//ReBind the List to retain the selected items on postbacks
BindCheckBoxList();
}
It looks like the issue is due to the if block below from the Button1 click event handler. The result is that only the check boxes that are checked have the values persisted to the database.
if (CheckBoxList1.Items[i].Selected)
{
PartnerName = CheckBoxList1.Items[i].Text;
Update(PartnerName, CheckBoxList1.Items[i].Selected);
}
You can just remove the if statement and persist all of the values or add logic to only persist those that have changed.