How to update all the 3 dropdownlist in update panel - c#

so i was doing this cascading dropdownlist control to get state,when country dropdown is changed and similarly ,get city on state change..so i was getting whole page refreshed ..so i tried update panel but only state was getting populated on country change but i was not able to change city for some reason..in current code now on state change i have kept city change ,but i want all dropdown to work in update panel i.e on selection of country ,state should be populated and on selection of state ,city should be populated..i am attaching the code
<div class="row">
<div class="medium-6 columns">
<div class="input-single valid">
<asp:DropDownList ID="ddlCountry" runat="server" TabIndex="13" AutoPostBack="true" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged"></asp:DropDownList>
<small class="error">Country is required.</small>
</div>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="medium-6 columns">
<div id="countrySubdivisionDiv" class="input-single">
<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlState_SelectedIndexChanged"></asp:DropDownList>
<small class="error">Region/State/Province is required.
</small>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="row">
<div class="medium-6 columns">
<div class="input-single">
<asp:UpdatePanel ID="fdf" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlCity" runat="server" maxlength="50"></asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
<small class="error">City is required.</small>
</div>
</div>
<div class="medium-6 columns">
<div class="input-single">
<asp:TextBox ID="txtPostalCode" runat="server" placeholder="Post Code" MaxLength="15" TabIndex="16"></asp:TextBox>
<small class="error">Postcode is required.</small>
</div>
</div>
</div>
</div>
The cs file for the same is.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateContinentsDropDownList();
}
lblCheckEmail.Visible = false;
}
private void PopulateContinentsDropDownList()
{
DataSet ds = Data.spGetCountries();
ddlCountry.DataSource = ds;
ddlCountry.DataTextField = "CountryName";
ddlCountry.DataValueField = "Country_Id";
ddlCountry.DataBind();
ListItem liCountry = new ListItem("Select Country");
ddlCountry.Items.Insert(0, liCountry);
ListItem liState = new ListItem("Select State");
ddlState.Items.Insert(0, liState);
ListItem liCity = new ListItem("Select City");
ddlCity.Items.Insert(0, liCity);
ListItem liCountryCode = new ListItem("Country Code");
ddlCountrycode.Items.Insert(0, liCountryCode);
ddlState.Enabled = false;
ddlCity.Enabled = false;
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCountry.SelectedValue == "")
{
ddlState.SelectedIndex = 0;
ddlCity.SelectedIndex = 0;
ddlState.Enabled = false;
ddlCity.Enabled = false;
ddlCountrycode.SelectedIndex = 0;
ddlCountrycode.Enabled = false;
}
else
{
ddlState.Enabled = true;
DataSet ds = Data.spGetStateByCountryId(Convert.ToInt32(ddlCountry.SelectedValue));
ddlState.DataSource = ds;
ddlState.DataTextField = "StateName";
ddlState.DataValueField = "State_Id";
ddlState.DataBind();
DataSet ds1 = Data.spGetCountrycode(Convert.ToInt32(ddlCountry.SelectedValue));
ddlCountrycode.DataSource = ds1;
ddlCountrycode.DataTextField = "CountryCode";
ddlCountrycode.DataValueField = "Country_Id";
ddlCountrycode.DataBind();
//ddlCity.SelectedIndex = 0;
//ddlCity.Enabled = false;
}
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlState.SelectedValue == "")
{
ddlCity.SelectedIndex = 0;
ddlCity.Enabled = false;
}
else
{
ddlCity.Enabled = true;
DataSet ds = Data.spGetCityByStateId(Convert.ToInt32(ddlState.SelectedValue));
ddlCity.DataSource = ds;
ddlCity.DataTextField = "CityName";
ddlCity.DataValueField = "City_Id";
ddlCity.DataBind();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
DataSet ds = Data.spCheckEmail(txtEmail.Text);
if (ds.Tables[0].Rows.Count > 0)
{
if (ds.Tables[0].Rows[0]["Email_Id"].ToString() == txtEmail.Text)
{
lblCheckEmail.Visible = true;
lblCheckEmail.Text = "Email id already exists , please enter another email id.";
}
else
{
lblCheckEmail.Text = "";
lblCheckEmail.Visible = false;
}
}
else
{
Data objpro = new Data();
string a = ddlYear.SelectedValue;
string b = ddlMonth.SelectedValue;
string c = ddlDate.SelectedValue;
string DateofBirth = ddlDate.SelectedValue + "/" + ddlMonth.SelectedValue + "/" + ddlYear.SelectedValue;
objpro.DOB = DateofBirth;
objpro.Email_Id = txtEmail.Text;
objpro.Password = txtPassword.Text;
objpro.Acc_Currency = ddlCurrency.SelectedValue;
objpro.FirstName = txtFirstName.Text;
objpro.LastName = txtLastName.Text;
objpro.Gender = ddlGender.SelectedValue;
objpro.Address1 = txtAddress1.Text;
objpro.Address2 = txtAddress2.Text;
objpro.Country = ddlCountry.SelectedItem.Text;
objpro.Region_State = ddlState.SelectedItem.Text;
objpro.City = ddlCity.SelectedItem.Text;
objpro.PostalCode = txtPostalCode.Text;
objpro.Phone_Extension = ddlCountrycode.SelectedValue;
objpro.PhoneNo = txtPhoneno.Text;
if (Request.QueryString["Account_Id"] != null)
{
ID = Request.QueryString["Account_Id"];
}
else
{
ID = "0";
}
objpro.Account_Id = Convert.ToInt32(ID);
int k = Data.CustomerInsert(objpro);
Random randno = new Random();
int cc = randno.Next(000000, 999999);
string Uniqueid = "U" + cc;
if (k != -1)
{
Data.spStoreUniqueId(k, Uniqueid);
}
Session["UniqueId"] = Uniqueid;
Session["Email"] = txtEmail.Text;
Page.ClientScript.RegisterStartupScript(Page.GetType(), "alert", "alert('Data Saved Successfully');window.location='JoininForm.aspx';", true);
Response.Redirect("Welcome.aspx");
}
}
protected void txtEmail_TextChanged(object sender, EventArgs e)
{
DataSet ds = Data.spCheckEmail(txtEmail.Text);
if (ds.Tables[0].Rows.Count > 0)
{
if (ds.Tables[0].Rows[0]["Email_Id"].ToString() == txtEmail.Text)
{
lblCheckEmail.Visible = true;
lblCheckEmail.Text = "Email id already exists , please enter another email id.";
}
}
}
also attaching the image for same.
Image containing the screen shot of country city and state
Thanking You guys for support

try below code. replace your update panel with below update panel
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="medium-6 columns">
<div id="countrySubdivisionDiv" class="input-single">
<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlState_SelectedIndexChanged"></asp:DropDownList>
<small class="error">Region/State/Province is required.
</small>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlCountry" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdatePanel ID="fdf" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlCity" runat="server" maxlength="50"> </asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlState" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>

Related

click event inside a click event is not firing

the problem is that I have created a click event of link button category_Click and inside this click event I have created multiple dynamic controls and I created a click event of an image button Image_Click and now the issue is that the Category_Click event is firing but the Image_Click event is not firing. please help me.
aspx page code:-
<%# Page Title="" Language="C#" MasterPageFile="~/Homepage.Master" AutoEventWireup="true" CodeBehind="Categories.aspx.cs" Inherits="WebApplication1.Categories" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<link rel="Stylesheet" href="Genre.css" />
<link rel="Stylesheet" href="genre_content.css" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="categories" runat="server">
<asp:Panel ID="Panel2" runat="server"></asp:Panel>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="main" runat="server">
<asp:Panel ID="Panel1" runat="server">
<h2><asp:Label ID="Label1" class="h2" runat ="server" ></asp:Label></h2><br/>
</asp:Panel>
<asp:Panel ID="Panel3" runat="server">
<div class="data">
<div class="image">
<asp:Image ID="Image1" runat="server" Cssclass="Img" />
</div>
<div class="description">
<asp:Label ID="Name" runat="server" class="name"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="(Paperback)"></asp:Label>
<div class="cos-shipping">
<div class="cos">
Rs.<asp:Label ID="cost" runat="server" CssClass="co" ></asp:Label>
</div>
<div class="shipping">
<p>Available</p>
<p>Ships within <b>4-6 Business Days</b></p>
<p>Rs.39 shipping in India per item and low cost Worldwide.</p>
</div>
</div>
<asp:Button ID="Button1" runat="server" Text="Buy Now" class="atc"/>
</div>
</div>
<div class="details">
<h2>Book Details</h2>
<asp:Label ID="about" runat="server" CssClass="about" ></asp:Label>
<p>Author: <asp:Label ID="author" runat="server" ></asp:Label> </p>
<p>ISBN: <asp:Label ID="isbn" runat="server" ></asp:Label> </p>
<p>Pubisher: <asp:Label ID="publisher" runat="server" ></asp:Label> </p>
<p>No of pages: <asp:Label ID="nop" runat="server" ></asp:Label> </p>
<p>Language: <asp:Label ID="language" runat="server" ></asp:Label> </p>
<p>Weight: <asp:Label ID="weight" runat="server" ></asp:Label> </p>
<p>Available For :<asp:Label ID="available" runat="server" ></asp:Label> </p>
</div>
</asp:Panel>
</asp:Content>
aspx.cs page code:-
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.SqlClient;
using System.Configuration;
using System.Web.UI.HtmlControls;
namespace WebApplication1
{
public partial class Categories : System.Web.UI.Page
{
private string ide, SQL, SQL2, label;
private int num, i, num2, j;
private ImageButton image;
private LinkButton bookname;
private Label money;
private Label id;
private Button wishlist;
private LinkButton category;
private static DataSet ds, ds2;
private static SqlDataAdapter da, da2;
private static HtmlGenericControl Book;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
Panel3.Visible = false;
con2.Open();
SQL2 = "Select distinct Book_category from Book_List";
da2 = new SqlDataAdapter(SQL2, con2);
ds2 = new DataSet();
DataTable dt2 = new DataTable();
da2.Fill(ds2);
num2 = ds2.Tables[0].Rows.Count;
HtmlGenericControl header = new HtmlGenericControl("div");
header.Attributes.Add("class", "header");
Panel2.Controls.Add(header);
for (j = 0; j < num2; j++)
{
category = new LinkButton();
category.Text = ds2.Tables[0].Rows[j]["Book_category"].ToString();
category.Attributes.Add("runat", "server");
category.Attributes.Add("CausesValidation", "false");
category.Click += new EventHandler(Category_Click);
header.Controls.Add(category);
}
}
protected void Category_Click(object sender, EventArgs e)
{
label = ((LinkButton)sender).Text;
Label1.Text = label;
con.Open();
SQL = "Select * from Book_List where Book_category='" + label + "'";
da = new SqlDataAdapter(SQL, con);
ds = new DataSet();
da.Fill(ds);
num = ds.Tables[0].Rows.Count;
//creating div element and putting all the elements ina div called books
Book = new HtmlGenericControl("div");
Book.Attributes.Add("class", "books");
Panel1.Controls.Add(Book);
for (i = 0; i < num; i++)
{
//creating div element
HtmlGenericControl myDiv = new HtmlGenericControl("div");
myDiv.Attributes.Add("class", "myDiv");
//creating image button
image = new ImageButton();
image.ImageUrl = ds.Tables[0].Rows[i]["Book_image"].ToString();
image.CssClass = "Img";
image.Attributes.Add("runat", "server");
//image.UseSubmitBehaviour = false;
image.Attributes.Add("CausesValidation", "false");
//image.Attributes.Add("OnClick", "image_Click");
//image.OnClientClick = Panel3;
image.Click += new ImageClickEventHandler(Image_Click);
//creating div inside myDiv
HtmlGenericControl content = new HtmlGenericControl("div");
content.Attributes.Add("class", "content");
//creating a label to display id
id = new Label();
id.CssClass = "id";
id.Text = ds.Tables[0].Rows[i]["Book_id"].ToString();
id.Attributes.Add("runat", "server");
//id.Click += new ImageClickEventHandler(id_Click);
//creating a label for displaying name of the book
bookname = new LinkButton();
bookname.CssClass = "name";
bookname.Text = ds.Tables[0].Rows[i]["Book_name"].ToString();
bookname.Attributes.Add("runat", "server");
//bookname.Click += new EventHandler(bookname_Click);
//creating a label for displaying cost of the book
money = new Label();
money.CssClass = "cost";
money.Text = "<br/> Rs " + ds.Tables[0].Rows[i]["Book_cost"].ToString();
money.Attributes.Add("runat", "server");
//creating a button to add the book to the wishlist
wishlist = new Button();
wishlist.Attributes.Add("runat", "server");
wishlist.CssClass = "wishlist";
wishlist.Text = "ADD TO WISHLIST";
Book.Controls.Add(myDiv);
myDiv.Controls.Add(image);
myDiv.Controls.Add(content);
content.Controls.Add(id);
content.Controls.Add(bookname);
content.Controls.Add(money);
content.Controls.Add(wishlist);
}
}
protected void Image_Click(object sender, ImageClickEventArgs e)
{
Panel3.Visible = true;
Panel2.Visible = false;
//ImageButton image = sender as ImageButton;
//Response.Redirect("genre_content.aspx");
ide = ((ImageButton)sender).ImageUrl;
for (i = 0; i < num; i++)
{
if (ide == ds.Tables[0].Rows[i]["Book_image"].ToString())
{
Session["name"] = ds.Tables[0].Rows[i]["Book_name"].ToString();
Session["image"] = ds.Tables[0].Rows[i]["Book_image"].ToString();
Session["cost"] = ds.Tables[0].Rows[i]["Book_cost"].ToString();
Session["isbn"] = ds.Tables[0].Rows[i]["Book_isbn_no"].ToString();
Session["weight"] = ds.Tables[0].Rows[i]["Book_weight"].ToString();
Session["author"] = ds.Tables[0].Rows[i]["Book_author"].ToString();
Session["about"] = ds.Tables[0].Rows[i]["Book_about"].ToString();
Session["publisher"] = ds.Tables[0].Rows[i]["Book_publisher"].ToString();
Session["nop"] = ds.Tables[0].Rows[i]["No_of_pages"].ToString();
Session["language"] = ds.Tables[0].Rows[i]["Book_language"].ToString();
Session["available"] = ds.Tables[0].Rows[i]["Available_for"].ToString();
}
}
Image1.ImageUrl = Session["image"].ToString();
Name.Text = Session["name"].ToString();
about.Text = Session["about"].ToString();
cost.Text = Session["cost"].ToString();
author.Text = Session["author"].ToString();
isbn.Text = Session["isbn"].ToString();
publisher.Text = Session["publisher"].ToString();
nop.Text = Session["nop"].ToString();
language.Text = Session["language"].ToString();
weight.Text = Session["weight"].ToString();
available.Text = Session["available"].ToString();
}
}
}
Your problem is that you dynamicly add the button to your form. If the postback then comes back, your page has no idea about the button because it gets created in your page_load.
You should look into using a gridview or simular control for keeping lists.

Textbox value doesn't change on button click event in asp.net C#

I'm stuck with a problem where i can't get the values of any control not just textboxes in button click event so here is the scenario, You can skip it and just can look into my button click event
Page product is performing 2 operations
Create
Update
When a user clicks Edit on GridView in updpage It will redirects it to Product Page to update, Same page is performing Create product operation too, So when I receive QueryString value I'll update the product table and when I won't so I just perform Create operation.
Now I'm stuck when there is no QueryString value so textboxes are updating with a new values but when there is, so they don't give me a new value.
Here is my code
On pageLoad Event I'm filling text boxes with there respective values
where there is an update operation
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["update"] !=null)
{
if (!Page.IsPostBack)
{
bindcategories();
bindachievments();
bindbrands();
}
int id = int.Parse(Request.QueryString["update"]);
string query = "SELECT * FROM ProductView WHERE id = " + id.ToString();
DataTable dtupd = new DataTable();
dtupd = param.All_data(query);
string name = "",available="",category="",brand="",achievement="",image="";
decimal price=0;
int unit = 0;
foreach (DataRow row in dtupd.Rows)
{
name = row.Field<string>("product_name");
price = row.Field<decimal>("price");
unit = row.Field<int>("unit");
image = row.Field<string>("product_image");
available = row.Field<string>("available");
category = row.Field<string>("category_name");
brand = row.Field<string>("brand_name");
achievement = row.Field<string>("achievement");
}
txt_name.Text = name;
txt_price.Text = price.ToString();
txt_unit.Text = unit.ToString();
product_image.ImageUrl = "../" + image;
dd_available.ClearSelection();
dd_available.SelectedValue = available;
dd_category.ClearSelection();
dd_category.Items.FindByText(category).Selected = true;
dd_brand.ClearSelection();
dd_brand.Items.FindByText(brand).Selected = true;
dd_achievment.ClearSelection();
dd_achievment.Items.FindByText(achievement).Selected = true;
btn_Insert.Text = "Update Product";
}
else
{
if (!Page.IsPostBack)
{
bindcategories();
bindbrands();
bindachievments();
}
if (!FileUpload1.HasFile)
{
product_image.ImageUrl = "../assets/images/products/default.png";
}
}
}
Button event code
protected void btn_Insert_Click(object sender, EventArgs e)
{
getpicture();
SqlCommand cmd;
string pathimage ="";
if (pathimage == "")
{
pathimage = product_image.ImageUrl;
}
else
{
pathimage = ViewState["pathimage"].ToString();
}
if (Request.QueryString["update"] != null)
{
int id = int.Parse(Request.QueryString["update"]);
string query = "UPDATE Products SET product_name=#PRODUCTNAME,price=#PRIZE,unit=#UNIT,product_image=#IMAGE,available=#AVAILABLE,product_category=#CATEGORY,product_brand=#BRAND,product_achv=#ACHIV WHERE id = #ID";
cmd = new SqlCommand(query);
txt_name.Text = "";
cmd.Parameters.Add("#PRODUCTNAME", txt_name.Text);
cmd.Parameters.Add("#PRIZE", txt_price.Text);
cmd.Parameters.Add("#UNIT", txt_unit.Text);
cmd.Parameters.Add("#IMAGE", pathimage);
cmd.Parameters.Add("#AVAILABLE", dd_available.SelectedItem.ToString());
cmd.Parameters.Add("#CATEGORY", dd_category.SelectedValue);
cmd.Parameters.Add("#BRAND", dd_brand.SelectedValue);
cmd.Parameters.Add("#ACHIV", dd_achievment.SelectedValue);
cmd.Parameters.Add("#ID", id);
param.InsertUpdateData(cmd);
}
else
{
string query = "INSERT INTO Products(product_name,price,unit,product_image,available,product_category,product_brand,product_achv) VALUES(#PRODUCTNAME,#PRIZE,#UNIT,#IMAGE,#AVAILABLE,#CATEGORY,#BRAND,#ACHIV)";
cmd = new SqlCommand(query);
cmd.Parameters.Add("#PRODUCTNAME", txt_name.Text);
cmd.Parameters.Add("#PRIZE", txt_price.Text);
cmd.Parameters.Add("#UNIT", txt_unit.Text);
cmd.Parameters.Add("#IMAGE", pathimage);
cmd.Parameters.Add("#AVAILABLE", dd_available.SelectedItem.ToString());
cmd.Parameters.Add("#CATEGORY", dd_category.SelectedValue);
cmd.Parameters.Add("#BRAND", dd_brand.SelectedValue);
cmd.Parameters.Add("#ACHIV", dd_achievment.SelectedValue);
param.InsertUpdateData(cmd);
}
}
It is getpicture function used in btn_submit
private void getpicture()
{
try
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string root = Server.MapPath("~");
string path = root + "assets\\images\\products\\";
FileUpload1.SaveAs(path + FileName);
ViewState["pathimage"] = "/assets/images/products/" + FileName;
this.product_image.ImageUrl = "../assets/images/products/upload.png";
}
else
{
Response.Write("Select an Image");
}
}
catch (Exception ex)
{
Response.Write("Select an Image");
}
}
Providing Data access layer Insert Update Data code too
public Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["OnlineStoreConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
System.Web.HttpContext.Current.Response.Write("Succed");
return true;
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.ToString());
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
Server Controls
<div class="row">
<div class="col-md-6">
<asp:TextBox ID="txt_name" runat="server" CssClass="form-control" placeholder="Product Name"></asp:TextBox>
<br />
<asp:TextBox ID="txt_price" runat="server" CssClass="form-control" placeholder="Product Price"></asp:TextBox>
<br />
<asp:TextBox ID="txt_unit" runat="server" CssClass="form-control" placeholder="Product Unit"></asp:TextBox>
<br />
<asp:DropDownList ID="dd_available" runat="server" CssClass="form-control">
<asp:ListItem>Is Product Available</asp:ListItem>
<asp:ListItem>Available</asp:ListItem>
<asp:ListItem>Not Avaliable</asp:ListItem>
</asp:DropDownList>
<br />
<asp:DropDownList ID="dd_category" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
<asp:DropDownList ID="dd_brand" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
<asp:DropDownList ID="dd_achievment" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
</div>
<div class="col-md-2"></div>
<div class="col-md-4">
<asp:Image ID="product_image" runat="server" style="height:231px;width:225px;" CssClass="form-control" />
<asp:FileUpload ID="FileUpload1" runat="server" onchange = "show_image(this);" />
</div>
</div>
<br />
<div class="row">
<div class="col-md-3 col-md-offset-6">
<asp:Button ID="btn_Insert" runat="server" Text="Create Product" CssClass="btn btn-primary btn-lg" OnClick="btn_Insert_Click" />
</div>
</div>
Before Clicking update button
Before clicking update button
After I updated text box values respectively and when click button Upload None of my server control value changes. Here it is
Watching local variable
But in case of Creating Product it works
Saad, i think the error is in the page_load event. If in your querystring the update param is not null, then you are always replacing the textboxes with the data of your DB.
Your code should be like this
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["update"] !=null)
{
if (!Page.IsPostBack)
{
bindcategories();
bindachievments();
bindbrands();
int id = int.Parse(Request.QueryString["update"]);
string query = "SELECT * FROM ProductView WHERE id = " + id.ToString();
DataTable dtupd = new DataTable();
dtupd = param.All_data(query);
string name = "",available="",category="",brand="",achievement="",image="";
decimal price=0;
int unit = 0;
foreach (DataRow row in dtupd.Rows)
{
name = row.Field<string>("product_name");
price = row.Field<decimal>("price");
unit = row.Field<int>("unit");
image = row.Field<string>("product_image");
available = row.Field<string>("available");
category = row.Field<string>("category_name");
brand = row.Field<string>("brand_name");
achievement = row.Field<string>("achievement");
}
txt_name.Text = name;
txt_price.Text = price.ToString();
txt_unit.Text = unit.ToString();
product_image.ImageUrl = "../" + image;
dd_available.ClearSelection();
dd_available.SelectedValue = available;
dd_category.ClearSelection();
dd_category.Items.FindByText(category).Selected = true;
dd_brand.ClearSelection();
dd_brand.Items.FindByText(brand).Selected = true;
dd_achievment.ClearSelection();
dd_achievment.Items.FindByText(achievement).Selected = true;
btn_Insert.Text = "Update Product";
}
}
else
{
if (!Page.IsPostBack)
{
bindcategories();
bindbrands();
bindachievments();
}
if (!FileUpload1.HasFile)
{
product_image.ImageUrl = "../assets/images/products/default.png";
}
}
}
Hope it helps...

Dropdownlist not showing correct selected value in ASP.NET Repeater Web application

I have a few ASP.NET Repeaters that have drop down lists in them and they all need to be populated with the correct information and then display the selected value for each data row it is displaying. In one repeater (CompanyRepeater), the correct selected value is chosen. In another repeater (SoldRepeater), the correct selected value is NOT chosen. So the drop down list in CompanyRepeater does work but the one in SoldRepeater does not work. The code is the same for both repeaters and I cannot figure out why the second one is not working. Both drop down lists populate with the correct information but the second repeater does not display the correct selected value. Please help me figure out why the correct selected value is not being selected. Below is my code. Please let me know if there is anymore information needed to help me. Any help is much appreciated. First is my front end code.
<asp:Repeater ID="CompanyRepeater" runat="server" OnItemDataBound="CompanyRepeater_ItemDataBound" OnItemCommand="CompanyRepeater_ItemCommand">
<ItemTemplate>
<table>
<tr>
<td colspan="3" style="text-align: center;">
<h3 style="font-weight: bold;">Company</h3>
</td>
</tr>
<tr>
<td>Event Date:
<br />
<asp:TextBox ID="txtDate" runat="server" Text='<%#Eval("Date") %>'></asp:TextBox>
<asp:Label ID="lblCompID" runat="server" Text='<%#Eval("CompID") %>' Visible="false"></asp:Label>
</td>
<td rowspan="2">Notes:
<br />
<asp:TextBox ID="txtNotes" TextMode="MultiLine" Height="100px" Text='<%#Eval("Notes") %>' runat="server"></asp:TextBox>
</td>
<td>OldName
<br />
<asp:TextBox ID="txtOldNameChange" Text='<%#Eval("OldName") %>' runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Country:
<asp:DropDownList ID="ddlCountry" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged"></asp:DropDownList>
<br /> State:
<asp:DropDownList ID="ddlState" runat="server"></asp:DropDownList>
</td>
<td>New Name
<br />
<asp:TextBox ID="txtNewNameChange" runat="server" Text='<%#Eval("NewName") %>'></asp:TextBox>
</td>
<td rowspan="3" style="width: 50px; float: right;">
<asp:Button ID="btnUpdateName" runat="server" Text="Update" CommandName="Update" />
<br />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?')" CommandName="Delete" CommandArgument='<%#Eval("CompID") %>' />
</td>
</tr>
</table>
</ItemTemplate>
<SeparatorTemplate>
<p> </p>
<br />
</SeparatorTemplate>
</asp:Repeater>
<hr />
<asp:Repeater ID="SoldRepeater" runat="server" OnItemDataBound="SoldRepeater_ItemDataBound" OnItemCommand="SoldRepeater_ItemCommand">
<ItemTemplate>
<table>
<tr>
<td colspan="3" style="text-align: center;">
<h3 style="font-weight: bold;">Sold Event</h3>
</td>
</tr>
<tr>
<td>Event Date:
<br />
<asp:TextBox ID="txtSoldDate" runat="server" Text='<%#Eval("EventDate") %>'></asp:TextBox>
<asp:Label ID="lblCompID" runat="server" Text='<%#Eval("CompID") %>' Visible="false"></asp:Label>
</td>
<td rowspan="2">Notes:
<br />
<asp:TextBox ID="txtSoldNotes" TextMode="MultiLine" Height="100px" Text='<%#Eval("Notes") %>' runat="server"></asp:TextBox>
</td>
<td>Sold to Company
<br />
<asp:TextBox ID="txtSoldTo" Text='<%#Eval("SoldToCompany") %>' runat="server"></asp:TextBox>
<br /> Sold to Type
<asp:DropDownList ID="ddlSoldTo" runat="server"></asp:DropDownList>
</td>
<td rowspan="2">
<asp:Button ID="btnUpdate" runat="server" Text="Update" CommandName="Update" CommandArgument='<%#Eval("CompID") %>' />
<br />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?')" CommandName="Delete" CommandArgument='<%#Eval("CompID") %>' />
</td>
</tr>
</table>
</ItemTemplate>
<SeparatorTemplate>
<p> </p>
<br />
</SeparatorTemplate>
</asp:Repeater>
This is my backend code
protected void Page_Load(object sender, EventArgs e)
{
_cID = Convert.ToInt32(Request.QueryString["CompID"]);
if (!Page.IsPostBack)
{
PopulateCompanyRepeater();
PopulateSoldEvent();
}
}
private void PopulateCompanyRepeater()
{
DALAccessData a = new DALAccessData(connString);
_listInfo = a.GetCompInfo(_cID);
CompanyRepeater.DataSource = _listInfo;
CompanyRepeater.DataBind();
}
private void PopulateSoldEvent()
{
DALSectionAccessData a = new DALSectionAccessData(connString);
_listEvents = a.GetSoldEvents(_cID);
SoldRepeater.DataSource = _listEvents;
SoldRepeater.DataBind();
}
protected void CompanyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddl = (DropDownList)e.Item.FindControl("ddlCountry");
DropDownList ddl2 = (DropDownList)e.Item.FindControl("ddlState");
Corp co = (Corp)e.Item.DataItem;
Corp st = (Corp)e.Item.DataItem;
SqlDataAdapter sda;
DataSet ds = new DataSet();
try
{
using(cn = new SqlConnection(connString))
{
string s = "SELECT DISTINCT a.Country_ID, a.CountryName FROM States c INNER JOIN Countries a ON a.Country_ID = c.Country_ID";
cn.Open();
sda = new SqlDataAdapter(s, cn);
sda.Fill(ds);
ddl.DataSource = ds.Tables[0];
ddl.DataTextField = "CountryName";
ddl.DataValueField = "Country_ID";
ddl.DataBind();
cn.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
for (int i = 0; i < ddl.Items.Count; i++)
{
if (co.Country_ID == Convert.ToInt32(ddl.Items[i].Value))
{
ddl.Items[i].Selected = true;
}
else
{
ddl.Items[i].Selected = false;
}
}
try
{
using(cn = new SqlConnection(connString))
{
string s = "SELECT DISTINCT StateName, StateID FROM States WHERE Country_ID = " + ddl.SelectedValue;
cn.Open();
sda = new SqlDataAdapter(s, cn);
sda.Fill(ds);
ddl2.DataSource = ds.Tables[0];
ddl2.DataTextField = "StateName";
ddl2.DataValueField = "StateID";
ddl2.DataBind();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
for (int i = 0; i < ddl2.Items.Count; i++)
{
if (!String.IsNullOrEmpty(ddl2.Items[i].Value))
{
if (st.StateID == Convert.ToInt32(ddl2.Items[i].Value))
{
ddl2.Items[i].Selected = true;
}
else
{
ddl2.Items[i].Selected = false;
}
}
}
}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)CompanyRepeater.Items[0].FindControl("ddlCountry");
DropDownList ddl2 = (DropDownList)CompanyRepeater.Items[0].FindControl("ddlState");
ddl2.Items.Clear();
using(SqlConnection conn = new SqlConnection(connString))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT StateName, StateID FROM States WHERE Country_ID = " + ddl.SelectedValue;
cmd.Connection = conn;
conn.Open();
using(SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem _listStates = new ListItem();
_listStates.Text = sdr["StateName"].ToString();
_listStates.Value = sdr["StateID"].ToString();
ddl2.Items.Add(_listStates);
}
}
}
}
ddl2.AppendDataBoundItems = true;
ddl2.Items.Insert(0, new ListItem("Select a State", "-1"));
ddl2.SelectedIndex = -1;
}
protected void SoldRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddl = (DropDownList)e.Item.FindControl("ddlSoldTo");
int x = ((CorpEvents)e.Item.DataItem).SoldToTypeID;
//Corp x = (Corp)e.Item.DataItem;
SqlDataAdapter sda;
DataSet ds = new DataSet();
try
{
using(cn = new SqlConnection(connString))
{
string s = "SELECT SoldToTypeID, SoldToTypeName FROM SoldToType";
cn.Open();
sda = new SqlDataAdapter(s, cn);
sda.Fill(ds);
ddl.DataSource = ds.Tables[0];
ddl.DataTextField = "SoldToTypeName";
ddl.DataValueField = "SoldToTypeID";
ddl.DataBind();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
for (int i = 0; i < ddl.Items.Count; i++)
{
if (x == Convert.ToInt32(ddl.Items[i].Value))
{
ddl.Items[i].Selected = true;
//i = 9;
}
else
{
ddl.Items[i].Selected = false;
}
}
}
}
My data access layer code
public List <Corp> GetCompInfo(int a)
{
List <Corp> _listInfo = new List <Corp> ();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
//create the connection and command objects
SqlConnection connection = new SqlConnection(_dbConnection);
SqlCommand command = new SqlCommand();
//populate the command object
command.Connection = connection;
command.CommandText = "SELECT a.CompID, CONVERT(varchar(10), a.Date, 120) AS Date, a.Notes, b.StateID, b.OldName, b.NewName, c.Country_ID FROM NameChange b INNER JOIN CompanyInfo a ON a.CompID = b.CompID INNER JOIN States c ON c.StateID = b.StateID WHERE a.CompID = " + a;
using(connection)
{
using(command)
{
connection.Open();
ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, new string[] {
"MyTable"
});
dt = ds.Tables["MyTable"];
}
}
foreach(DataRow row in dt.Rows)
{
Corp e = new Corp();
e.CompID = Convert.ToInt32(row["CompID"].ToString());
e.NewName = row["NewName"].ToString();
e.OldName = row["OldName"].ToString();
e.StateID = Convert.ToInt32(row["StateID"].ToString());
e.Notes = row["Notes"].ToString();
e.CountryID = Convert.ToInt32(row["Country_ID"].ToString());
e.Date = Convert.ToDateTime(row["Date"].ToString());
e.Date.ToShortDateString();
_listInfo.Add(e);
}
return _listInfo;
}
public List <Corp> GetSoldEvents(int a)
{
List <Corp> _listInfo = new List <Corp> ();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
//create the connection and command objects
SqlConnection connection = new SqlConnection(_dbConnection);
SqlCommand command = new SqlCommand();
//populate the command object
command.Connection = connection;
command.CommandText = "SELECT a.CompID, a.Notes, a.Date, b.SoldToCompany, c.SoldToTypeName, c.SoldToTypeID FROM CompanyInfo a INNER JOIN SoldEvent b ON a.CompID = b.CompID INNER JOIN SoldToType c ON b.SoldToTypeID = c.SoldToTypeID WHERE a.CompID = " + a;
using(connection)
{
using(command)
{
connection.Open();
ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, new string[] {
"MyTable"
});
dt = ds.Tables["MyTable"];
}
}
foreach(DataRow row in dt.Rows)
{
Corp e = new Corp();
e.CompID = Convert.ToInt32(row["CompID"].ToString());
e.SoldToCompany = row["SoldToCompany"].ToString();
e.SoldToTypeName = row["SoldToTypeName"].ToString();
e.SoldToTypeID = Convert.ToInt32(row["SoldToTypeID"].ToString());
e.Notes = row["Notes"].ToString();
e.EventDate = Convert.ToDateTime(row["Date"].ToString());
e.EventDate.ToShortDateString();
_listInfo.Add(e);
}
return _listInfo;
}
IMHO, your method of setting the selected value is rather cumbersome. This entire section of code:
for (int i = 0; i < ddl.Items.Count; i++)
{
if (x == Convert.ToInt32(ddl.Items[i].Value))
{
ddl.Items[i].Selected = true;
//i = 9;
}
else
{
ddl.Items[i].Selected = false;
}
}
Can be replaced with a single line:
ddl.SelectedValue = x.ToString();
In addition, once you do find the matching value you continue to loop on the items, rather than exiting out of the loop.
Try these changes, they may solve the problem for you.
A few other items that I noticed:
The code to retrieve the SoldToType is called for each item in the
repeater. I would suggest retrieving this data once and referencing
it for each item, rather than going to the db each time.
Your SQL code is wide open to SQL injection. Use parameterized queries, like so:
cmd.CommandText = "SELECT StateName, StateID FROM States WHERE Country_ID = #CountryID";
...
cmd.Parameters.AddWithValue("CountryID", ddl.SelectedValue);

Show Table when SelectedValue of DropDownList is true C#

I want to show a table when a SelectedValue of my DropDownList ddlKlasse is true. I'm using asp.net empty web forms with a masterpage.
The idea is:
when ddlKlasse.SelectedValue = "2" table tblDubbelTwee must be shown
when ddlKlasse.SelectedValue = "5" table tblVierMet must be shown
when ddlKlasse.SelectedValue = "9" table tblAchtMet must be shown
I get the values in my dropdownlist from my database.
The code I have now is:
In my Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
BindDropDownListKlasse();
BindDropDownListVereniging();
if (!Page.IsPostBack)
{
tblDubbelTwee.Visible = false;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
}
}
For binding the dropdown:
private void BindDropDownListKlasse()
{
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "SELECT DISTINCT AantalDeelnemers, Naam FROM Klasse;";
com.Connection = conn;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
ddlKlasse.DataSource = dt;
ddlKlasse.DataValueField = "AantalDeelnemers";
ddlKlasse.DataTextField = "Naam";
ddlKlasse.DataBind();
conn.Close();
//Adding "Kies de klasse" optie in dropdownlist voor validatie
ddlKlasse.Items.Insert(0, new ListItem("Kies de klasse", "0"));
}
}
}
catch
{
}
}
For showing the tables:
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
ListItem selectedListItemDubbelTwee = ddlKlasse.Items.FindByValue("2");
if (selectedListItemDubbelTwee != null)
{
selectedListItemDubbelTwee.Selected = true;
tblDubbelTwee.Visible = true;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
};
ListItem selectedListItemVierMet = ddlKlasse.Items.FindByValue("5");
if (selectedListItemVierMet != null)
{
selectedListItemVierMet.Selected = true;
tblVierMet.Visible = true;
tblDubbelTwee.Visible = false;
tblAchtMet.Visible = false;
};
ListItem selectedListItemAchtMet = ddlKlasse.Items.FindByValue("9");
if (selectedListItemAchtMet != null)
{
selectedListItemAchtMet.Selected = true;
tblAchtMet.Visible = true;
tblDubbelTwee.Visible = false;
tblVierMet.Visible = false;
};
}
My DropDownList:
<div class="form-inline">
<div class="form-group">
<asp:DropDownList ID="ddlKlasse" class="form-control" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlKlasse_SelectedIndexChanged"></asp:DropDownList>
</div>
</div>
One of my tables:
<asp:Table ID="tblDubbelTwee" runat="server" class="table">
<asp:TableHeaderRow>
<asp:TableHeaderCell>Naam</asp:TableHeaderCell>
<asp:TableHeaderCell>Email</asp:TableHeaderCell>
<asp:TableHeaderCell>Lidmaatschapsnr</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtNaam" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtEmail" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtLidmaatschapsnr" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtNaam2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtEmail2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtLidmaatschapsnr2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
But when I run my project and select a field in my DropDownList it gives the error: System.Web.HttpException: Selecting multiple items in a DropDownList is not allowed.
Can you please help me to solve this problem?
Your current handler for DDL index change is doing something very different from what you have described. It basically checks if the list item exists in the ddl list (no matter selected or not) and then tries to select it. Since all of 3 items exist, you are effectively trying to select 3 items, which is not allowed.
What you might be looking for is a switch by selected value:
switch (ddlKlasse.SelectValue)
{
case "2":
tblDubbelTwee.Visible = true;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
break;
case "5": //similar here
case "9": //similar here
default:
// exception or something
}
refere this code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindgrid();
}
}
void bindgrid()
{
con.Open();
SqlCommand cmd = new SqlCommand("select DISTINCT Class from addmitionform1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlclass.DataSource = ds;
ddlclass.DataTextField = "Class";
ddlclass.DataValueField = "Class";
ddlclass.DataBind();
ddlclass.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
string id = (ddlclass.SelectedValue.ToString());
con.Close();
SqlDataAdapter da1 = new SqlDataAdapter("Select id,FirstName from addmitionform1 where Class= '" + id + "'", con);
//SqlDataAdapter da1 = new SqlDataAdapter("Select * from addmitionform1 ", con);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
GridView1.DataSource = ds1;
GridView1.DataBind();
}
First move BindDropDownListKlasse() and BindDropDownListVereniging() inside if (!IsPostBack), as HarveySpecter suggested.
And change ddlKlasse_SelectedIndexChanged() to:
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
bool showDubbelTwee = false, showVierMet = false, showAchtMet = false;
switch (ddlKlasse.SelectedValue)
{
case "2":
showDubbelTwee = true;
break;
case "5":
showVierMet = true;
break;
case "9":
showAchtMet = true;
break;
}
tblAchtMet.Visible = showVierMet;
tblDubbelTwee.Visible = showDubbelTwee;
tblVierMet.Visible = showVierMet;
}
What you are doing now in ddlKlasse_SelectedIndexChanged() is check for each value if it's present in the dropdown, and if present select it and show the respective table.
Instead, you need to check which value is selected and show the respective table.

Clicking HyperLink causes Update Panel to perform Full PostBack?

Update panel does a full post back when I am just trying to do a partial post back. I just want to be able to update the Repeater and not update the whole page when i click the hyperlinks previous page and next page .
protected void Page_Load(object sender, EventArgs e)
{
PagedDataSource objpd = new PagedDataSource();
string connStr = ConfigurationManager.ConnectionStrings["yafnet"].ConnectionString;
SqlConnection mySQLconnection = new SqlConnection(connStr);
if (mySQLconnection.State == ConnectionState.Closed)
{
mySQLconnection.Open();
}
SqlCommand mySqlSelect = new SqlCommand("SELECT * FROM [Comments]", mySQLconnection);
mySqlSelect.CommandType = CommandType.Text;
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlSelect);
DataTable table = new DataTable();
mySqlAdapter.Fill(table);
objpd.DataSource = table.DefaultView;
objpd.AllowPaging = true;
objpd.PageSize = 1;
int currentPage;
if (Request.QueryString["page"] != null)
{
currentPage = Int32.Parse(Request.QueryString["page"]);
}
else
{
currentPage = 1;
}
objpd.CurrentPageIndex = currentPage - 1;
// Label1.Text = "Page " + currentPage + " of " + pds.PageCount;
if (!objpd.IsFirstPage)
{
linkPrev.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage - 1);
}
if (!objpd.IsLastPage)
{
linkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage + 1);
}
Repeater1.DataSource = objpd;
Repeater1.DataBind();
}
This is my HTML
<div class="comment">
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table class="commentsx" cellspacing="0">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td class="name">
<div class="right">
<%# Eval("CommentUserName") %>
</div>
<div class="left">
<%# Eval("CommentDateTime") %>
</div>
</td>
</tr>
<tr>
<td>
<div class="mess">
<%# Eval("CommentMessage") %>
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:HyperLink ID="linkPrev" runat="server">Previous Page</asp:HyperLink>
<asp:HyperLink ID="linkNext" runat="server">Next Page</asp:HyperLink>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="DataBinding" />
</Triggers>
</asp:UpdatePanel>
</div>
Hyperlink controls don't do a postback at all, they evaluate to regular links that will do a GET, not a POST.
Since it seems you want something that looks like a link, but does a postback rather than a GET, what you need is a LinkButton. It looks like a link, but acts like a button and performs a postback.
Figure I would post an answer to my own question since I figure it out with help of Servy. Hyperlinks do a Get not a post that is why my previous code above was not working. So I rework my code to include the following.
I added Two buttons
Made Event Handlers for the Two buttons to create a POST
Here is my Code might help someone
public int CurrentPage
{
get
{
// look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
return 0; // default to showing the first page
else
return (int)o;
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
private void updateMessage()
{
PagedDataSource objpd = new PagedDataSource();
string connStr = ConfigurationManager.ConnectionStrings["yafnet"].ConnectionString;
SqlConnection mySQLconnection = new SqlConnection(connStr);
if (mySQLconnection.State == ConnectionState.Closed)
{
mySQLconnection.Open();
}
SqlCommand mySqlSelect = new SqlCommand("SELECT * FROM [Comments]", mySQLconnection);
mySqlSelect.CommandType = CommandType.Text;
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlSelect);
DataTable table = new DataTable();
mySqlAdapter.Fill(table);
objpd.DataSource = table.DefaultView;
objpd.AllowPaging = true;
objpd.PageSize = 1;
objpd.CurrentPageIndex = CurrentPage;
//disable pre or next buttons if necessary
cmdPrev.Enabled = !objpd.IsFirstPage;
cmdNext.Enabled = !objpd.IsLastPage;
Repeater1.DataSource = objpd;
Repeater1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
updateMessage();
}
protected void cmdPrev_Click(object sender, EventArgs e)
{
// Set viewstate variable to the previous page
CurrentPage -= 1;
// Reload control
updateMessage();
}
protected void cmdNext_Click(object sender, EventArgs e)
{
// Set viewstate variable to the next page
CurrentPage += 1;
// Reload control
updateMessage();
}
here is my html
<div class="comment">
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table class="commentsx" cellspacing="0">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td class="name">
<div class="right">
<%# Eval("CommentUserName") %>
</div>
<div class="left">
<%# Eval("CommentDateTime") %>
</div>
</td>
</tr>
<tr>
<td>
<div class="mess">
<%# Eval("CommentMessage") %>
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:button id="cmdPrev" runat="server" text=" << " onclick="cmdPrev_Click"></asp:button>
<asp:button id="cmdNext" runat="server" text=" >> " onclick="cmdNext_Click"></asp:button></td>
</ContentTemplate>
</asp:UpdatePanel>
</div>

Categories