Clicking HyperLink causes Update Panel to perform Full PostBack? - c#

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>

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.

Biding Radiobutton to gridview & again insert binded values to database

I am working on a project I bound the Radiobutton to grid view it works and fetch the data to GridView properly now again I want to insert the values of checked and unchecked of RadioButton to database, but doesn't work properly it pass all RadioButton as false.
for clarifying the bellow is it code.
from before I am thankful for your answer.
Code Behind
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;
namespace Online_Examination_System
{
public partial class FormAnswers : System.Web.UI.Page
{
int count;
ClassCommon obj = new ClassCommon();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
count = 1;
}
DataTable dt = new DataTable();
dt = obj.GetData("select Question from tblQuestions where QId='" + count + "'");
gvQuestions.DataSource = dt;
gvQuestions.DataBind();
DataTable dt2 = new DataTable();
dt2 = obj.GetData("select Answer from tblAnswers where QId='" + count + "'");
gvAnswers.DataSource = dt2;
gvAnswers.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
count = 1;
if (ViewState["view"] != null)
{
count = Convert.ToInt16(ViewState["view"]);
}
ViewState["view"] = count + 1;
DataTable dt = new DataTable();
dt = obj.GetData("select Question from tblQuestions where QId='" + ViewState["view"] + "'");
gvQuestions.DataSource = dt;
gvQuestions.DataBind();
DataTable dt2 = new DataTable();
dt2 = obj.GetData("select Answer from tblAnswers where QId='" + ViewState["view"] + "'");
gvAnswers.DataSource = dt2;
gvAnswers.DataBind();
if (!IsPostBack)
{
for (int i = 1; i < gvAnswers.Rows.Count; i++)
{
int V;
RadioButton rBtnAnswer = gvAnswers.Rows[i].FindControl("rbtnSelect") as RadioButton;
if (rBtnAnswer.Checked)
{
V = 1;
}
else
{
V = 0;
}
Label txtAnswered = gvAnswers.Rows[i].FindControl("lblAnswer") as Label;
obj.ExeQuery("insert into tblResult values('" + V + "','" + txtAnswered.Text + "',Null,NULL,NULL,Null)");
}
}
}
HTML
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="FormAnswers.aspx.cs" Inherits="Online_Examination_System.FormAnswers" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript">
function SelectRadioButton(radio) {
var rdBtn = document.getElementById(radio.id);
var rdBtnList = document.getElementsByTagName("input");
for (i = 0; i < rdBtnList.length; i++) {
if (rdBtnList[i].type == "radio" && rdBtnList[i].id != rdBtn.id) {
rdBtnList[i].checked = false;
}
}
}
</script>
<title></title>
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="auto-style1">
<tr>
<td class="auto-style1">
<asp:GridView ID="gvQuestions" runat="server" GridLines="None">
</asp:GridView>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td> </td>
</tr>
<tr>
<td class="auto-style1">
<asp:GridView ID="gvAnswers" runat="server" GridLines="None" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:RadioButton ID="rbtnSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Answer">
<ItemTemplate>
<asp:Label ID="lblAnswer" runat="server" Text='<%# Bind("Answer") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1">
<asp:Button ID="btnSave" runat="server" Text="Next" OnClick="btnSave_Click" />
</td>
<td> </td>
</tr>
</table>
</div>
</form>
</body>
</html>
The code below will never get executed, since it inside the !IsPostBack condition.
for (int i = 1; i < gvAnswers.Rows.Count; i++)
{
int V;
RadioButton rBtnAnswer = gvAnswers.Rows[i].FindControl("rbtnSelect") as RadioButton;
if (rBtnAnswer.Checked)
{
V = 1;
}
else
{
V = 0;
}
Label txtAnswered = gvAnswers.Rows[i].FindControl("lblAnswer") as Label;
obj.ExeQuery("insert into tblResult values('" + V + "','" + txtAnswered.Text + "',Null,NULL,NULL,Null)");
}
All you need to do is to remove the !IsPostBack condition.
For more details check out this.

How to display questions and options(as a radiobuttonlist) in datalist

I am developing an application (Quiz Engine) in Asp.Net with C#. I have a database table (Q_ID,Question,option1,option2,option3,answer).
What I want is, to retrieve these data and display to the user as Question and Answer and enable the user to select with the Radio button. My problem is that how I can display this Question and options in radiobuttonlist.
my asp page is
<asp:DataList ID="DataList2" runat="server" RepeatDirection="Vertical">
<ItemTemplate>
<br />
<table class="auto-style1">
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Question") %>'></asp:Label>
</td>
<td>
<asp:RadioButtonList ID="RadioButtonList2" runat="server">
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
and my cod behind is like
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
DataTable dt = new DataTable();
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
MySqlDataAdapter adp = new MySqlDataAdapter("select LO_id,Q_Id,level,Question,option1,option2 from quiz WHERE LO_id='LO111'", cn);
adp.Fill(dt);
}
if (dt.Rows.Count > 0)
{
DataList2.DataSource = dt;
DataList2.DataBind();
}
foreach (DataListItem dli in DataList2.Items)
{
RadioButtonList RadioButtonList2 = (RadioButtonList)DataList2.FindControl("RadioButtonList2");
//RadioButtonList2.Items.Clear();
RadioButtonList2.Items.Insert(0, new ListItem("option1".ToString(), "option1".ToString()));
RadioButtonList2.Items.Insert(1, new ListItem("option2".ToString(), "option2".ToString()));
}
}

displaying read more option when user enters large amount of data in richtextbox

I have a richtextbox and a gridview.
When I enter the data into the richtextbox, it should be displayed in a gridview and saved in database.
Now my requirement is that, if i am entering a paragraph or a large amount of data I should display a "readmore" button, that when clicked, display the complete data.
<%# Register Assembly="FreeTextBox" Namespace="FreeTextBoxControls" TagPrefix="FTB" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Richtextbox Sample</title>
<script type="text/javascript">
function validate() {
var doc = document.getElementById('FreeTextBox1');
if (doc.value.length == 0) {
alert('Please Enter data in Richtextbox');
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<FTB:FreeTextBox ID="FreeTextBox1" runat="server">
</FTB:FreeTextBox>
</td>
<td valign="top">
<asp:GridView runat="server" ID="gvdetails" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="RichtextBoxData">
<ItemTemplate>
<asp:Label ID="lbltxt" runat="server" Text='<%#Bind("RichtextData") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
<asp:Button ID="btnSubmit" runat="server" OnClientClick="return validate()"
Text="Submit" onclick="btnSubmit_Click" />
<br />
<asp:Label ID="lbltxt" runat="server"/>
</form>
</body>
</html>
c# code-
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindGridview();
}
protected void BindGridview()
{
con.Open();
SqlCommand cmd = new SqlCommand("select RichTextData from RichTextBoxData", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdetails.DataSource = ds;
gvdetails.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into RichTextBoxData(RichTextData) values(#Richtextbox)", con);
cmd.Parameters.AddWithValue("#Richtextbox", FreeTextBox1.Text);
cmd.ExecuteNonQuery();
con.Close();
FreeTextBox1.Text = "";
BindGridview();
}
first in your select query add id of your text(your primary key of table RichTextBoxData)
and in gridview make it,s visible =false like this
<asp:TemplateField HeaderText="id" InsertVisible="False" Visible="False">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
and then
protected void gvdetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lb =e.Row.FindControl("lbltxt") as Label;
if (lb.Text.Length > 15)//any length u want
{
DataRow drv = ((DataRowView)e.Row.DataItem).Row;
int tempID = Convert.ToInt32(drv["id"].ToString());
HyperLink hp = new HyperLink();
hp.Text = "read more";
hp.NavigateUrl = "~/mydetails.aspx?id=" + tempID;
e.Row.Cells[1].Controls.Add(hp);
lb.Text = lb.Text.Substring(0, 15);
}
}
}
and on page_load of mydetails.aspx make
query to select RichTextData where id=request.querystring["id"]

Dynamically give Id to textbox (Server side control) in asp:Repeater

In my <asp:Repeater></asp:Repeater> - There is one hidden field, textbox and button.
When data will be bound, then hidden filed will get User Id like below code
<asp:HiddenField ID="hide" Value='<%#Eval("UserId")%>' runat="server"/>
and ItemDataBound event will be called and in this function, i am getting value from hidden field and concatenating that value as a Id in text box. like below code
TextBox txt = (TextBox)e.Item.FindControl("txtReplyArea");
HiddenField hf = (HiddenField)e.Item.FindControl("hide");//1
txt.ID = "txtReplyArea" + hf.Value;//txtReplyArea1
Suppose only one record comes from database and their UserId is 1. Then textbox Id should be "textReplyArea1". From now, all are correct.
I am not sure, it's correct way to giving dynamic Id to repeater control but i think, it's correct.
Problem -
When i click on button and i get a items from repeater and textbox from Id by finding control from repeater then it shows null.
int areaId = int.Parse((sender as Button).CommandArgument);//1
string id="txtReplyArea"+areaId;//txtReplyArea1
foreach (RepeaterItem item in repeaterBlog.Items)
{
TextBox tb = item.FindControl(id) as TextBox;//tb = null
}
Code of aspx page
<%# Page Title="Messages" Language="C#" MasterPageFile="~/Menu.master" AutoEventWireup="true" CodeFile="Messages.aspx.cs" Inherits="Messages" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div style="width:70%;">
<asp:Repeater ID="repeaterBlog" runat="server" OnItemDataBound="repeaterBlog_ItemDataBound">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr >
<td>
<asp:HiddenField ID="hide" Value='<%#Eval("UserId")%>' runat="server"/>
<asp:TextBox ID="txtReplyArea" runat="server" TextMode="Multiline" Columns="70" Rows="8" Visible="false"></asp:TextBox>
</td>
</tr>
<tr>
<td style="margin-left:47%;">
<asp:Button ID="btnReply" runat="server" Text="Reply" OnClick="btnReplyClicked" AutoPostBack="True" CommandArgument='<%#Eval("UserId")%>'/>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</asp:Content>
Code of aspx.cs
SqlCommand cmd;
SqlDataReader sdr;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
String cs = ConfigurationManager.ConnectionStrings["myWebsite"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
cmd = new SqlCommand("select * from ContactMessage", con);
con.Open();
sdr = cmd.ExecuteReader();
repeaterBlog.DataSource = sdr;
repeaterBlog.DataBind();
con.Close();
}
}
}
public void repeaterBlog_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
TextBox txt = (TextBox)e.Item.FindControl("txtReplyArea");
HiddenField hf = (HiddenField)e.Item.FindControl("hide");
txt.ID = "txtReplyArea" + hf.Value;
}
}
protected void btnReplyClicked(object sender, EventArgs e)
{
int areaId = int.Parse((sender as Button).CommandArgument);
string id="txtReplyArea"+areaId;
foreach (RepeaterItem item in repeaterBlog.Items)
{
TextBox tb = item.FindControl(id) as TextBox;
}
}
}
This worked for me. Notice that I removed EnableViewState from the repeater and added OnItemDatabound event.
<asp:Repeater ID="repeaterBlog" runat="server" OnItemDataBound="repeaterBlog_ItemDataBound">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:HiddenField ID="hide" Value='<%#Eval("UserId")%>' runat="server" />
<asp:TextBox ID="txtReplyArea" runat="server" TextMode="Multiline" Columns="70" Rows="8"
Visible="false"></asp:TextBox>
</td>
</tr>
<tr>
<td style="margin-left: 47%;">
<asp:Button ID="btnReply" runat="server" Text="Reply" OnClick="btnReplyClicked" AutoPostBack="True"
CommandArgument='<%#Eval("UserId")%>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId");
DataRow dr = dt.NewRow();
dr[0] = 34;
dt.Rows.Add(dr);
repeaterBlog.DataSource = dt;
repeaterBlog.DataBind();
}
public void repeaterBlog_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
TextBox txt = (TextBox)e.Item.FindControl("txtReplyArea");
HiddenField hf = (HiddenField)e.Item.FindControl("hide");
txt.ID = "txtReplyArea" + hf.Value;
}
}
protected void btnReplyClicked(object sender, EventArgs e)
{
int areaId = int.Parse((sender as Button).CommandArgument);
string id = "txtReplyArea" + areaId;
foreach (RepeaterItem item in repeaterBlog.Items)
{
TextBox tb = item.FindControl(id) as TextBox;
}
}
You can try like this
<asp:TextBox ID='<%# "txtReplyArea" + Convert.ToString(Eval("UserId")%>)' runat="server" TextMode="Multiline" Columns="70" Rows="8" Visible="false"></asp:TextBox>

Categories