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;
}
}
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 written a user control an editable GridView. Here is the code of the control in design (file: editableGridView.ascx)
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="editableGridView.ascx.cs" Inherits="WebApplication1.EditableGridView" %>
<asp:GridView ID="EditableGrid" runat="server" Width="500px" Height="500px" AllowSorting="True"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
OnRowEditing="EditableGrid_RowEditing"
OnRowCancelingEdit="EditableGrid_RowCancelingEdit"
OnRowUpdating="EditableGrid_RowUpdating"
OnRowDeleting="EditableGrid_RowDeleting"
></asp:GridView>
And here is the code behind: (File: editableGridView.ascx.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
namespace WebApplication1
{
public partial class EditableGridView : System.Web.UI.UserControl
{
public string connstr { get; set; }
public string tablename { get; set; }
public string selectcmd { get; set; }
private List<EdField> fields;
private SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
}
public void InitGrid(string theconnstr, string tablename)
{
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (!rd.HasRows) return;
fields = new List<EdField>();
for (int i =0; i < rd.FieldCount; i++)
{
fields.Add(new EdField(rd.GetName(i), rd.GetDataTypeName(i)));
}
}
}
}
public void Bind()
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = selectcmd;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
EditableGrid.DataSource = dt;
EditableGrid.DataBind();
EditableGrid.Visible = true;
}
}
}
con.Close();
}
protected void EditableGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
EditableGrid.EditIndex = e.NewEditIndex;
Bind();
}
protected void EditableGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
EditableGrid.EditIndex = -1;
Bind();
}
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)EditableGrid.Rows[e.RowIndex];
List<TextBox> tbs = new List<TextBox>();
for (int i = 1; i < fields.Count; i++)
{
tbs.Add((TextBox)row.FindControl("textbox" + i.ToString()));
}
EditableGrid.EditIndex = -1;
String sql = "UPDATE " + tablename + "SET " ;
for (int i = 1; i < fields.Count; i++)
{
sql += fields[i].Name;
sql += " = ";
sql += ProperFormatField(fields[i].DataTypeName, tbs[i].Text);
if (i < fields.Count - 1)
{
sql += " , ";
}
}
Label lbl = (Label)row.FindControl("lblid");
sql += " WHERE " + fields[0].Name + " = " + lbl.Text;
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
Bind();
}
protected void EditableGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)EditableGrid.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("lblid");
String sql = "DELETE " + tablename;
sql += " WHERE " + fields[0].Name + " = " + lbl.Text;
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
Bind();
/* */
}
private String ProperFormatField(String dtf, String s)
{
if (
(dtf == "CHAR") ||
(dtf == "VARCHAR") ||
(dtf == "NVARCHAR") ||
(dtf == "NCHAR") ||
(dtf == "DATE") ||
(dtf == "DATETIME") ||
(dtf == "DATETIME2")
)
{
return "'" + s + "'";
}
else
return s;
}
}
public class EdField
{
private String myName;
private String myDataTypeName;
public String Name
{
get { return myName; }
set { myName = value; }
}
public String DataTypeName
{
get { return myDataTypeName; }
set { myDataTypeName = value; }
}
public EdField(String theName, String theDataTypename)
{
myName = theName;
myDataTypeName = theDataTypename.ToUpper();
}
}
}
Now in my page where I want to place my control I write:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %>
<%# Register TagPrefix="mygrids" TagName="EditableGridView" Src="editableGridView.ascx"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<mygrids:EditableGridView ID="edgv1"></mygrids:EditableGridView>
</div>
</form>
</body>
</html>
But there is a green marking under EditableGridView and the hint says: "the element EditableGridView is not known. The problem could be to a compilation error of the site or the file web.config is missing"
Any Help or idea Here?
this is my offer.aspx inherits from masterpage
' />
my .cs file
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
offerlistbind();
}
}
public void offerlistbind()
{
db1.strCommand = " select Offer.OfferID, Offer.OfferName,Offer.Amount,Offer.FromDate,Offer.ToDate,Offer.Description,bm_package.PackageName,bm_country.Country from Offer inner join bm_package on Offer.PackageID=bm_package.PackageID inner join bm_country on Offer.CountryID=bm_country.CountryID";
offerlistnew.DataSource = db1.DataSet();
offerlistnew.DataBind();
}
if i click the button instead of firing item command event item dataBound event is working
protected void offerlistnew_ItemCommand1(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "subscribe")
{
int ofid = Convert.ToInt32(e.CommandArgument);
Response.Redirect("http://ecom.bom.tv/default.aspx?Offer=" + ofid + "");
}
}
Please use Hyperlink in place of button. If you use asp button then first it will do post back then it will redirect to another page. But using hyperlink you can directly redirect to another page. You can also increase the performance using this.
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='http://ecom.bom.tv/default.aspx?Offer=<%# Eval("OfferID") %>'
Text="Subscribe"></asp:HyperLink>
OR
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "http://ecom.bom.tv/default.aspx?Offer=" + Eval("OfferID") %>'
Text="Subscribe"></asp:HyperLink>
Let me know if any concern.
use e.commandname in link button
if (e.CommandName == "sel")
{
//Code conn.Open();
int lblintid = Convert.ToInt32(e.CommandArgument.ToString());
string cmd2 = "UPDATE productsTs set recurrent=recurrent+30,biduser='" + HiddenField2.Value + "' where ID = " + e.CommandArgument + "";
SqlCommand x2 = new SqlCommand(cmd2, conn);
x2.ExecuteNonQuery();
conn.Close();
}else if(e.CommandName == "min")
{
//Code conn.Open();
int lblintid = Convert.ToInt32(e.CommandArgument.ToString());
string cmd2 = "UPDATE productsTs set recurrent=recurrent-30,biduser='" + HiddenField2.Value + "' where ID = " + e.CommandArgument + "";
SqlCommand x2 = new SqlCommand(cmd2, conn);
x2.ExecuteNonQuery();
conn.Close();
}
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();
}
}
Ok I am using the code below in file called autocomplete.asmx (web service file) my main question is do I need to create a different web service for every field I want my auto complete to work for? IE maybe I would like to have the Company Name pulled out instead of country, but another time maybe name, now I know this just involves changing the select statement but How could I go about doing this so that depending on what field it is, it knows what select statement to use?
Thanks
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
public string[] GetCountriesList(string prefixText)
{
DataSet dtst = new DataSet();
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
string strSql = "SELECT CountryName FROM Tbl_ooo WHERE CountryName LIKE '" + prefixText + "%' ";
SqlCommand sqlComd = new SqlCommand(strSql, sqlCon);
sqlCon.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlComd;
sqlAdpt.Fill(dtst);
string[] cntName = new string[dtst.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow rdr in dtst.Tables[0].Rows)
{
cntName.SetValue(rdr["CountryName"].ToString(), i);
i++;
}
}
catch { }
finally
{
sqlCon.Close();
}
return cntName;
}
}
Yes, you can use same webservice webmethod to populate country and company.
For that you want to use ContextKey property in ajax AutoCompleteExtender control
Below is the sample Code
Markup :
Search
<asp:TextBox ID="txtSearch" CssClass="textBlackBold" runat="server" Width="350px"></asp:TextBox>
<asp:DropDownList ID="ddlType" runat="server" AutoPostBack="True" onselectedindexchanged="ddlType_SelectedIndexChanged">
<asp:ListItem Value="0">Country</asp:ListItem>
<asp:ListItem Value="1">Companies</asp:ListItem>
</asp:DropDownList>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
EnableCaching="true" ContextKey="Products" UseContextKey="true"
TargetControlID="txtSearch" MinimumPrefixLength="1"
ServiceMethod="GetInfo" ServicePath="~/WebService.asmx" >
</asp:AutoCompleteExtender>
Code Behind C# Code :
protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
{
string strContextKey = "";
if(ddlType.SelectedValue.ToString() == "0")
strContextKey = "Country";
else
strContextKey = "Companies";
AutoCompleteExtender1.ContextKey = ddlType.SelectedItem.Text;
}
WebService Code :
[WebMethod]
public string[] GetInfo(string prefixText, string contextKey)
{
DataSet dtst = new DataSet();
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
string strSql = "";
if (contextKey == "Country")
{
strSql = "SELECT CountryName FROM Tbl_ooo WHERE CountryName LIKE '" + prefixText + "%' ";
}
else if(contextKey == "Companies")
{
strSql = //Other SQL Query
}
SqlCommand sqlComd = new SqlCommand(strSql, sqlCon);
sqlCon.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlComd;
sqlAdpt.Fill(dtst);
string[] cntName = new string[dtst.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow rdr in dtst.Tables[0].Rows)
{
cntName.SetValue(rdr[0].ToString(),i);
i++;
}
}
catch { }
finally
{
sqlCon.Close();
}
return cntName;
}