click event inside a click event is not firing - c#

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.

Related

How to update all the 3 dropdownlist in update panel

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>

Creating dynamic DIV in asp .net c#

I am creating DIVs dynamically which will fetch data from my sql table(from each row) and will show it in DIVs. What problem I am facing is, it only shows the last row of my sql table in a div form
Here is the html
<div ID = "containerDiv" class="container" runat = "server">
<div ID = "columnDiv" class="col-md-3 col-sm-4" runat = "server">
<div ID = "textDiv" class="text" runat="server">
</div>
</div>
</div>
and here is the cs code
static int count = 0;
protected void Page_Load(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM tblProducts"))
{
cmd.Connection = con;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
columnDiv.ID = "columnDiv" + count;
textDiv.ID = "textDiv" + count;
string name = rdr["prod_name"].ToString();
string price = rdr["prod_price"].ToString();
textDiv.InnerHtml = name + " " + price;
columnDiv.Controls.Add(textDiv);
containerDiv.Controls.Add(columnDiv);
count++;
}
}
}
}
Try using a Repeater, like this (here's the MSDN):
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div ID="containerDiv" class="container" runat = "server">
<div ID="columnDiv" class="col-md-3 col-sm-4" runat = "server">
<div ID="textDiv" class="text" runat="server">
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
And supply a DataSource in the code behind on the server, and add '<%# Eval("ColumnName") %>' expressions in the markup where appropriate.
The standard approach is to use a GridView:
https://msdn.microsoft.com/en-us/library/aa479342.aspx

not able to read from dynamic text box created in a gridview

i am new to dotnet and am just trying out to add a row of text boxes for a grid view DYNAMICALLY.
On load of the page the grid view will be loaded with data as read only.
on clicking edit button, 2nd row will be loaded with text boxes. i succeeded till here. now on entering some data on these text boxes am not able to read the value back in my c# code.
here is my code snippet. can anyone please help me in this.
ASP code:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="justGrid._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<br />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
<asp:TextBox ID="TextBox1" runat="server" Width="170px"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="edit" />
<br />
<br />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="save" />
<br />
</asp:Content>
C# code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
staticTable();
}
bindGrid();
}
protected void staticTable()
{
string[] NamesArray = new string[] { "RAM", "SAM", "TOM", "JERRY" };
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt = ds.Tables.Add();
dt.Columns.Add("Names", typeof(string));
for (int j = 1; j <= 5; j++)
{
dt.Columns.Add("" + j, typeof(string));
}
foreach (string l in NamesArray)
{
dt.Rows.Add(l);
}
dt.Rows[0][1] = "S";
dt.Rows[0][2] = "P";
dt.Rows[0][5] = "P";
dt.Rows[1][2] = "S";
dt.Rows[1][4] = "P";
dt.Rows[2][3] = "S";
dt.Rows[3][1] = "U";
dt.Rows[3][5] = "P";
ViewState["CurrentTable"] = dt;
GridView1.DataSource = ds;
// GridView1.DataBind();
}
protected void bindGrid()
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int k = 1; k <= 5; k++)
{
TextBox tb1 = new TextBox();
tb1.Attributes.Add("runat", "server");
tb1.Width = 15;
tb1.ID = "TBID" + k;
tb1.Text = GridView1.Rows[1].Cells[k].Text.Trim().Replace(" ", string.Empty);
GridView1.Rows[1].Cells[k].Controls.Add(tb1);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox box1 = (TextBox)GridView1.Rows[1].Cells[1].FindControl("TBID1");
TextBox1.Text = box1.Text;
}
}
Note: for testing purpose alone..am trying to display the 2nd row 1st column value in textbox.
foreach (GridViewRow row in GridView1.Rows)
{
TextBox box1 = row.FindControl("TBID") as TextBox;
if (box1 != null)
{
string value = box1.Text;
}
}

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>

Grabbing values of genered ListBox ASP Controls inside ListView On PostBack

So I've got this:
<asp:ListView runat="server" ID="lvAttributes" DataKeyNames="attribute_id" OnItemDataBound="lvAttributes_ItemDataBound">
<ItemTemplate>
<label class="title">product <%# Eval("name") %></label>
<asp:ListBox DataTextField="value" DataValueField="tag_id" CssClass="chzn-select"
runat="server" ID="lbAttributeTags"></asp:ListBox>
<br />
</ItemTemplate>
<LayoutTemplate>
<div id="itemPlaceholder" runat="server"></div>
</LayoutTemplate>
</asp:ListView>
Now on post back I'd like to get each individual lbAttributeTags selected value. But as you know there might be a single ListBox generated or 100. So how should I approach a solution for this for the many potential possibilities?
Thanks in advance.
Here you have the code to fetch the selected item from the ListBox inside the list view control
asp.net
<form id="form1" runat="server">
<div>
</div>
<asp:ListView runat="server" ID="lvAttributes" DataKeyNames="attribute_id" OnItemDataBound="lvAttributes_ItemDataBound">
<ItemTemplate>
<label class="title">product <%# Eval("name") %></label>
<asp:ListBox DataTextField="value" DataValueField="tag_id" CssClass="chzn-select"
runat="server" ID="lbAttributeTags"></asp:ListBox>
<asp:Button ID="btnInsideLV" runat="server" Text="Inside LV Click" OnCommand="btnInsideLV_Click" CommandArgument='<%# Container.DataItemIndex + 1 %>' /><br />
</ItemTemplate>
<LayoutTemplate>
<div id="itemPlaceholder" runat="server"></div>
</LayoutTemplate>
</asp:ListView>
<asp:Button ID="btnSample" runat="server" Text="Click" OnClick="btnSample_Click" />
<asp:Label ID="lblDisplay" runat="server" />
<asp:Label ID="lblSelectedRowValue" runat="server" />
</form>
c#:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class stackoverflow_12761515 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("name");
dt.Columns.Add("attribute_id");
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["attribute_id"] = i + 1;
dr["name"] = "item " + i + 1;
dt.Rows.Add(dr);
}
lvAttributes.DataSource = dt;
lvAttributes.DataBind();
//BindListBox();
}
}
private void BindListBox(ListBox lb)
{
DataTable dt = new DataTable();
dt.Columns.Add("value");
dt.Columns.Add("tag_id");
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["tag_id"] = i + 1;
dr["value"] = "value " + i + 1;
dt.Rows.Add(dr);
}
//ListBox lb = (ListBox)lvAttributes.FindControl("lbAttributeTags");
lb.DataSource = dt;
lb.DataTextField = "value";
lb.DataValueField = "tag_id";
lb.DataBind();
}
protected void lvAttributes_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListBox lb = (ListBox)e.Item.FindControl("lbAttributeTags");
BindListBox(lb);
}
protected void btnSample_Click(object sender, EventArgs e)
{
lblDisplay.Text = string.Empty;
for (int i = 0; i < lvAttributes.Items.Count; i++)
{
ListBox lb = (ListBox)lvAttributes.Items[i].FindControl("lbAttributeTags");
if (lb.SelectedIndex != -1)
{
lblDisplay.Text += lb.SelectedItem.Text + "\n";
}
}
}
protected void btnInsideLV_Click(object sender, CommandEventArgs e)
{
int selectedRow = Convert.ToInt32(e.CommandArgument.ToString());
ListBox lbCurrent = (ListBox)lvAttributes.Items[selectedRow - 1].FindControl("lbAttributeTags");
if (lbCurrent.SelectedIndex != -1)
{
lblSelectedRowValue.Text = "Row selected is : " + selectedRow + " and list item is : " + lbCurrent.SelectedItem.Text;
}
else
{
lblSelectedRowValue.Text = "no item selected";
}
}
}
The 2 button click events have the code which you required. Please let me know if you need anything else.

Categories