Biding Radiobutton to gridview & again insert binded values to database - c#

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.

Related

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>

Gridview with multiple dropdown list with add row & delete button in asp.net

Iam new to asp.net can anyone help me on this.
I want to make a dynamic grid in asp.net which have 5 drop down list binding from database
and on selection of first dropdownvalue second dropdown bind.and it has also add row & delete
row button.
<asp:UpdatePanel runat="server"><ContentTemplate>
<asp:GridView ID="grvparameterdetail" runat="server"
ShowFooter="True" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333"
GridLines="None" OnRowDeleting="grvparameterDetails_RowDeleting"
>
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="SNo" />
<asp:TemplateField HeaderText="Company">
<ItemTemplate>
<asp:DropDownList DataSource='<%# bindcompany1() %>' DataTextField="Comp_Name" DataValueField="Comp_Code" ID="drpcompany" runat="server" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="drpcompany_indexedchanged">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Center">
<ItemTemplate>
<asp:DropDownList DataSource='<%# bindunit1() %>' DataTextField="center" DataValueField="Pub_cent_Code" ID="drpcenter" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Publ.Type">
<ItemTemplate>
<asp:DropDownList DataSource='<%# bindptype1() %>' DataTextField="pubname" DataValueField="pubtypecode" ID="drppubtype" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Publication">
<ItemTemplate>
<asp:DropDownList ID="drppub" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edition">
<ItemTemplate>
<asp:DropDownList ID="drppubed" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server"
Text="Add New Row" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
aspx.cs code
if (!Page.IsPostBack)
{
FirstGridViewRow();
}
private void FirstGridViewRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Col1", typeof(string)));
dt.Columns.Add(new DataColumn("Col2", typeof(string)));
dt.Columns.Add(new DataColumn("Col3", typeof(string)));
dt.Columns.Add(new DataColumn("Col4", typeof(string)));
dt.Columns.Add(new DataColumn("Col5", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
//dr["Col2"] = string.Empty;
//dr["Col3"] = string.Empty;
//dr["Col4"] = string.Empty;
//dr["Col5"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
grvparameterdetail.DataSource = dt;
grvparameterdetail.DataBind();
}
private void AddNewRow()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
for (int i = 1; i <= dtCurrentTable.Rows.Count - 1; i++)
{
DropDownList Drpcompany =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[1].FindControl("drpcompany");
DropDownList drpcenter =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[2].FindControl("drpcenter");
DropDownList drppubtype =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[3].FindControl("drppubtype");
DropDownList Drppublication =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[4].FindControl("drppub");
DropDownList Drpedition =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[5].FindControl("drppubed");
//drCurrentRow = dtCurrentTable.NewRow();
//drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i]["Col1"] = Drpcompany.SelectedValue;
dtCurrentTable.Rows[i]["Col2"] = drpcenter.SelectedValue;
dtCurrentTable.Rows[i]["Col3"] = drppubtype.SelectedValue;
dtCurrentTable.Rows[i]["Col4"] = Drppublication.SelectedIndex;
dtCurrentTable.Rows[i]["Col5"] = Drpedition.SelectedValue;
rowIndex++;
}
//dtCurrentTable.Rows.Add(drCurrentRow);
//ViewState["CurrentTable"] = dtCurrentTable;
grvparameterdetail.DataSource = dtCurrentTable;
grvparameterdetail.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList Drpcompany =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[1].FindControl("drpcompany");
DropDownList drpcenter =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[2].FindControl("drpcenter");
DropDownList drppubtype =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[3].FindControl("drppubtype");
DropDownList Drppublication =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[4].FindControl("drppub");
DropDownList Drpedition =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[5].FindControl("drppubed");
Drpcompany.SelectedValue = dt.Rows[i]["Col1"].ToString();
drpcenter.SelectedValue = dt.Rows[i]["Col2"].ToString();
drppubtype.SelectedValue = dt.Rows[i]["Col3"].ToString();
Drppublication.SelectedValue = dt.Rows[i]["Col4"].ToString();
Drpedition.SelectedValue = dt.Rows[i]["Col5"].ToString();
rowIndex++;
}
}
}
}
protected void grvparameterDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SetRowData();
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
int rowIndex = Convert.ToInt32(e.RowIndex);
if (dt.Rows.Count > 1)
{
dt.Rows.Remove(dt.Rows[rowIndex]);
drCurrentRow = dt.NewRow();
ViewState["CurrentTable"] = dt;
grvparameterdetail.DataSource = dt;
grvparameterdetail.DataBind();
for (int i = 0; i < grvparameterdetail.Rows.Count - 1; i++)
{
grvparameterdetail.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
}
SetPreviousData();
}
}
}
private void SetRowData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
DropDownList Drpcompany =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[1].FindControl("drpcompany");
DropDownList drpcenter =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[2].FindControl("drpcenter");
DropDownList drppubtype =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[3].FindControl("drppubtype");
DropDownList Drppublication =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[4].FindControl("drppub");
DropDownList Drpedition =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[5].FindControl("drppubed");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Col1"] = Drpcompany.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col2"] = drpcenter.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col3"] = drppubtype.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col4"] = Drppublication.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col5"] = Drpedition.SelectedValue;
rowIndex++;
}
ViewState["CurrentTable"] = dtCurrentTable;
//grvStudentDetails.DataSource = dtCurrentTable;
//grvStudentDetails.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//SetPreviousData();
}
protected void drpcompany_indexedchanged(object sender, EventArgs e)
{
//what to write here
}
Thanks in advance.
I have made a sample code , it wil be easy to get an idea how to start ur task..
i have done harcoded data.. instead of hardcoding use the data from db..
chk the comments ...
Page 1 : aspx file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery.js.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>Last Name</td>
<td>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Speciality</td>
<td>
<asp:DropDownList ID="ddlSpeciality" runat="server">
<asp:ListItem Text="" />
<asp:ListItem Text="aaa" />
<asp:ListItem Text="bbb" />
<asp:ListItem Text="ccc" />
</asp:DropDownList></td>
</tr>
<tr>
<td>Location</td>
<td>
<asp:DropDownList ID="ddlLocation" runat="server">
<asp:ListItem Text="" />
<asp:ListItem Text="bangalore" />
<asp:ListItem Text="chennai" />
<asp:ListItem Text="hyderabad" />
</asp:DropDownList></td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" /></td>
</tr>
</table>
</form>
</body>
</html>
Page 1: cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSearch_Click(object sender, EventArgs e)
{
string lastName = txtLastName.Text.Trim();
string speciality = ddlSpeciality.Text;
string location = ddlLocation.Text;
Response.Redirect(string.Format("page2.aspx?lastname={0}&speciality={1}&location={2}",lastName ,speciality , location));
}
}
}
Page 2: aspx file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="page2.aspx.cs" Inherits="WebApplication1.test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvdata" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkID" OnClick="LinkButton1_Click" Text="Details" runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Page 2: cs file
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) { }
else
{
string lastname = Request.QueryString["lastname"];
string speciality = Request.QueryString["speciality"];
string location = Request.QueryString["location"];
string query = lastname.Length == 0 ? "" : "lastname ='" + lastname + "' and";
query += speciality.Length == 0 ? "" : "speciality ='" + speciality + "' and";
query += location.Length == 0 ? "" : "location ='" + location + "' ";
query = query.Trim().TrimStart(new char[] { 'a', 'n', 'd' }).TrimEnd(new char[] { 'a', 'n', 'd' });
query = "select * from tablename where " +( query.Length == 0 ? "1=1" : query);
// use this query to get data from sql database
// use shld get the data from db
// for example, i have hardcoded the datatable with some values
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("lastname", typeof(string));
dt.Columns.Add("speciality", typeof(string));
dt.Columns.Add("location", typeof(string));
dt.Rows.Add(1, "karthik", "aaa", "bangalore");
dt.Rows.Add(2, "parthip", "aaa", "chennai");
dt.Rows.Add(3, "krishna", "aaa", "hyderabad");
gvdata.DataSource = dt;
gvdata.DataBind();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
string id = ((sender as LinkButton).Parent.Parent as GridViewRow).Cells[1].Text;
Response.Redirect("page3.aspx?id=" + id);
}
}
}
Page 3: aspx file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="page3.aspx.cs" Inherits="WebApplication1.page3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div runat="server" id="divcontent">
</div>
</form>
</body>
</html>
Page 3: cs file
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class page3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) { }
else
{
string id = Request.QueryString["id"];
// use this id to fetch the data from db to get the details.
// get the data from db..
// i have hardcoded
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("lastname", typeof(string));
dt.Columns.Add("speciality", typeof(string));
dt.Columns.Add("location", typeof(string));
dt.Rows.Add(1, "karthik", "aaa", "bangalore");
Table tbl = new Table() { CellPadding=1 , CellSpacing=2 , BorderColor = System.Drawing.Color.Red, BorderWidth=1 };
foreach (DataColumn col in dt.Columns)
{
TableRow tr = new TableRow() { BorderWidth=1 , BorderColor = System.Drawing.Color.Red };
tr.Cells.Add( new TableCell () { BorderWidth=1 , BorderColor = System.Drawing.Color.Red ,Text = col.ColumnName});
tr.Cells.Add( new TableCell () { BorderWidth=1 , BorderColor = System.Drawing.Color.Red ,Text = dt.Rows[0][col].ToString()});
tbl.Rows.Add(tr);
}
divcontent.Controls.Add(tbl);
}
}
}
}

Adding 'rolling numbers' for repeater control, Paging asp.net c#

I am using repeater control and showing paging '<< Previous next >>' it is working fine.
But i want to show links (rolling numbers) in between like below:
Previous << 1 2 3 4 5 next >>
have a look this picture for idea.
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table border="1" style="border-color: #336699;" cellspacing="0">
<tr style="background-color:#336699; color:White;">
<td>Product ID</td>
<td>Product Name</td>
<td>Unit Price</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("ProductID") %></td>
<td><%# Eval("ProductName") %></td>
<td><%# Eval("UnitPrice") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<div> <table width="500px" border="0" cellspacing="5" cellpadding="5">
<tr>
<td width="25%"> <asp:Label ID="Label2" runat="server" />
</td>
<td width="25%"><asp:HyperLink ID="linkPrev" runat="server">« Previous</asp:HyperLink>
</td>
<td width="25%"><asp:HyperLink ID="linkNext" runat="server">Next »</asp:HyperLink></td>
<td width="25%"><asp:Label ID="Label1" runat="server" /> </td>
</tr>
</table> </div>
c#
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from Products", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();
con.Close();
DataTable table = new DataTable();
da.Fill(table);
PagedDataSource pds = new PagedDataSource();
pds.DataSource = table.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 10;
int currentPage;
if (Request.QueryString["page"] != null)
{
currentPage = Int32.Parse(Request.QueryString["page"]);
}
else
{
currentPage = 1;
}
pds.CurrentPageIndex = currentPage - 1;
Label1.Text = "Page " + currentPage + " of " + pds.PageCount;
Label2.Text = "Results" + pds.DataSourceCount;
if (!pds.IsFirstPage)
{
linkPrev.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage - 1);
}
if (pds.IsFirstPage)
{
linkPrev.Visible = false;
linkPrev.Style["display"] = "block";
}
if (!pds.IsLastPage)
{
linkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage + 1);
}
if (pds.IsLastPage)
{
linkNext.Visible = false;
linkPrev.Style["display"] = "block";
}
Repeater1.DataSource = pds;
Repeater1.DataBind();
}
}

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