Hide/show table in gridview on button click event - c#

I have project on recruitment.In this project, at one form I have a grid view which contains details of all vacancies. Along with this there is button. When user clicks on this button, available interview schedule for that particular vacancy will be visible in another grid below that row. What I did is I have placed grid view inside table and table is initially invisible. When user clicks on the image button, at that time I tried to find table from the grid view but it can not be found.
Here is the code of my .aspx page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<table class="formtTbl" width="100%">
<tr>
<td width="10%">
</td>
<td>
</td>
<td width="10%">
</td>
</tr>
<tr>
<td>
</td>
<td align="center" class="tdtitle">
Open vacancies
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:ImageButton ID="addVacancyBtn" runat="server"
ImageUrl="~/Resources/add.png" onclick="addVacancyBtn_Click" />
Add New Vacancy</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:GridView ID="VacancyGrid" runat="server" CssClass="mGrid"
AutoGenerateColumns="False" onrowcommand="VacancyGrid_RowCommand">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ScheduleBtn" runat="server"
ImageUrl="~/Resources/01.gif"
ToolTip="View Interview Schedule" Width="20px"
CommandName="View Schedule" CommandArgument="<%#((GridViewRow)Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="VacId" DataField="VacId" />
<asp:BoundField HeaderText="Title" DataField="VacTitle" />
<asp:BoundField HeaderText="Open" DataField="TotalOpening" />
<asp:BoundField HeaderText="Criteria" DataField="criteria" />
<asp:BoundField HeaderText="Key Skills" DataField="KeySkills" />
<asp:BoundField HeaderText="Exp" DataField="RequiredExperience" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="editBtn" runat="server"
ImageUrl="~/Resources/art-knife.png" Width="20px"
CommandName="Edit" CommandArgument="<%#((GridViewRow)Container).RowIndex %>"/>
</ItemTemplate>
<EditItemTemplate>
Edit
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="statusLbl" runat="server" Text="Label"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<table id="ScheduleTable" visible="false">
<tr id="abc" visible="false">
<td colspan="10">
<asp:GridView ID="scheduleGrid" runat="server" Visible="False"
AutoGenerateColumns="False" onrowcommand="scheduleGrid_RowCommand">
<Columns>
<asp:BoundField DataField="VacId" HeaderText="ID" />
<asp:BoundField DataField="VacTitle" HeaderText="Title" />
<asp:BoundField DataField="InterviewTime" HeaderText="Interview Date & Time" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="viewIntervieweesBtn" runat="server"
ImageUrl="~/Resources/document.png" ToolTip="View interiviewees" Width="20px"
CommandName="View Interviewees" CommandArgument="<%#((GridViewRow)Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="ScheduleNotifyLbl" runat="server" Visible="false"></asp:Label>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle CssClass="pgr" />
</asp:GridView>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td align="left">
<asp:Label ID="notificationLbl" runat="server" Font-Size="X-Large"
ForeColor="Red" Text="Label" Visible="False"></asp:Label>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</asp:Content>
//Here is the code for my .aspx.cs page
public partial class Department_VacancyList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable VacancyTable = null;
try
{
if (!IsPostBack)
{
if (Request.QueryString["status"] != null)
{
// strStatus = Request.QueryString["status"];
Session.Add("strStatus", Request.QueryString["status"]);
}
if (Session["OpResult"] != null)
{
notificationLbl.Visible = true;
if (Session["OpResult"].ToString() == "InsertSuceess")
notificationLbl.Text = "New Vacancy Has Been Created Successfully";
if (Session["OpResult"].ToString() == "InsertFail")
notificationLbl.Text = "An Error Occured While Creating New Vacancy..";
if (Session["OpResult"].ToString() == "EditSuccess")
notificationLbl.Text = "Your Changes Has Been Saved Successfully";
if (Session["OpResult"].ToString() == "EditFail")
notificationLbl.Text = "An Error Occured While Saving Changes...";
}
using (VacancyMasterClass VacMaster = new VacancyMasterClass())
{
if (Session["strStatus"].ToString() == "1")//All Vacancies
VacancyTable = VacMaster.getTable("and DeptId=1 and CompId=1");//Change Here.
else if (Session["strStatus"].ToString() == "2")//Open Vacancies
VacancyTable = VacMaster.getTable("and DeptId=1 and CompId=1 and Status=0");//Change Here.
else if (Session["strStatus"].ToString() == "3")//Closed Vacancies
VacancyTable = VacMaster.getTable("and DeptId=1 and CompId=1 and Status=1");//Change Here.
VacancyGrid.DataSource = VacancyTable;
VacancyGrid.DataBind();
VacancyGrid.ControlStyle.Width = 650;
VacancyGrid.Columns[0].ItemStyle.Width = 20;
VacancyGrid.Columns[1].ItemStyle.Width = 10;
VacancyGrid.Columns[2].ItemStyle.Width = 150;
VacancyGrid.Columns[3].ItemStyle.Width = 20;
VacancyGrid.Columns[4].ItemStyle.Width = 190;
VacancyGrid.Columns[5].ItemStyle.Width = 190;
VacancyGrid.Columns[6].ItemStyle.Width = 20;
VacancyGrid.Columns[7].ItemStyle.Width = 30;
VacancyGrid.Columns[8].ItemStyle.Width = 30;
VacancyGrid.Columns[9].ItemStyle.Width = 0;
VacancyGrid.Columns[1].Visible = false;
if (Session["strStatus"].ToString() == "1" || Session["strStatus"].ToString() == "3")
{
VacancyGrid.Columns[7].Visible = false;
VacancyGrid.Columns[0].Visible = false;
for (int intRowcount = 0; intRowcount < VacancyTable.Rows.Count; intRowcount++)
{
Label StatusLbl = (Label)VacancyGrid.Rows[intRowcount].Cells[6].FindControl("statusLbl");
if (VacancyTable.Rows[intRowcount]["Status"].ToString() == "False")
{
StatusLbl.ForeColor = Color.Green;
StatusLbl.Text = "Open";
}
else
{
StatusLbl.ForeColor = Color.Red;
StatusLbl.Text = "Closed";
}
}
}
else if (Session["strStatus"].ToString() == "2")
VacancyGrid.Columns[8].Visible = false;
}
}
}
catch (Exception ex)
{
CommonProcedures.WriteErrorLog("Department_VacancyList", "Page_Load", ex.Message);
}
finally
{
Session.Remove("OpResult");
}
}
//protected void VacancyGrid_RowEditing(object sender, GridViewEditEventArgs e)
//{
// int intOpMode = 2;//Edit Mode
// int intVacId = Convert.ToInt32(VacancyGrid.Rows[e.NewEditIndex].Cells[1].Text);
// Response.Redirect("create_vacancyfrm.aspx?VacId="+intVacId+"&OpMode="+intOpMode);
//}
protected void addVacancyBtn_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
int intOpMode = 1;//Edit Mode
int intVacId = 0;
Response.Redirect("create_vacancyfrm.aspx?DeptId=1&CompId=1&VacId=" + intVacId + "&OpMode=" + intOpMode);//Change Here
}
protected void VacancyGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
DataTable InterviewScheduleTable = null;
int intVacid = 0;
try
{
if (e.CommandName == "View Schedule")
{
int intRowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow Row = VacancyGrid.Rows[intRowIndex];
//Table ScheduleTable = (Table)Row.FindControl("ScheduleTable");
intVacid = Convert.ToInt32(Row.Cells[1].Text);
GridView scheduleGrid = (GridView)Row.FindControl("scheduleGrid");
Label ScheduleNotifyLbl = (Label)Row.FindControl("ScheduleNotifyLbl");
if (scheduleGrid.Visible == false)
{
using (vwVacInterviewShcedule oInterviewSchedule = new vwVacInterviewShcedule())
{
InterviewScheduleTable = oInterviewSchedule.getTable("and VacId=" + intVacid);
if (InterviewScheduleTable.Rows.Count > 0)
{
scheduleGrid.Visible = true;
scheduleGrid.DataSource = InterviewScheduleTable;
scheduleGrid.DataBind();
scheduleGrid.ControlStyle.Width = 650;
scheduleGrid.Columns[0].ItemStyle.Width = 10;
scheduleGrid.Columns[1].ItemStyle.Width = 300;
scheduleGrid.Columns[2].ItemStyle.Width = 250;
scheduleGrid.Columns[3].ItemStyle.Width = 90;
}
else
{
if (ScheduleNotifyLbl.Visible == false)
{
ScheduleNotifyLbl.Visible = true;
ScheduleNotifyLbl.Text = "Interview is yet to schedyule for this vacancy";
}
else
{
ScheduleNotifyLbl.Visible = false;
}
}
}
}
else
{
scheduleGrid.Visible = false;
}
}
ViewState.Add("VacId", intVacid);
if (e.CommandName == "Edit")
{
int intOpMode = 2;
int intRowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow Row = VacancyGrid.Rows[intRowIndex];
int intVacId = Convert.ToInt32(Row.Cells[1].Text);
Response.Redirect("create_vacancyfrm.aspx?VacId=" + intVacId + "&OpMode=" + intOpMode);
}
}
catch (Exception ex)
{
CommonProcedures.WriteErrorLog("Department_VacancyList", "VacancyGrid_RowCommand", ex.Message);
}
finally
{
InterviewScheduleTable = null;
}
}
protected void scheduleGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
foreach (GridViewRow Row in VacancyGrid.Rows)
{
GridView ScheduleGrid = (GridView)Row.FindControl("scheduleGrid");
if (e.CommandName == "View Interviewees")
{
int intRowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow ScheduleGridRow = ScheduleGrid.Rows[intRowIndex];
int intVacId = Convert.ToInt32(ScheduleGridRow.Cells[3].Text);
Session.Add("Time",ScheduleGridRow.Cells[2].Text);
Response.Redirect("~/Department Head/Schedulefrm.aspx?VacId="+intVacId);
}
}
}
catch (Exception ex)
{
CommonProcedures.WriteErrorLog("Department_VacancyList", "scheduleGrid_RowCommand", ex.Message);
}
}
}
Please show me my problem...

You have provided too much code, that can't be read easily. You have to narrow it down to a specific point.
Let me try to help you on your specific problem.
If you set the control visible=false it will not render at client side and you can't make that control visible later on in client side. Have a look at this similar thread to get an idea how to proceed: Want to make the visibility true from client side of the control which made invisible from server side

Related

DropdownList SelectedIndexChanged inside Repeater fires up while under UpdatePanel and click another Dropdownlist outside repeater

I have a 2 Dropdownlist outside a repeater (1st ddl will trigger and refresh the content of the repeater, 2nd ddl refresh its list after an item inside the repeater were executed) and a dropdownlist control inside the repeater.i don't have a problem with the 1st dropdownlist but the 2nd dropdownlist when triggered via selectedindexchanged, it also fires up the selectedindexchanged of the dropdownlist inside the repeater. I put up an UpdatePanel on the repeater and on the 2nd dropdownlist but still the error occurs.
How can i trace the step by step execution and also why the selectedindexchanged handler fires up?
Here is the code snippet:
CODE BEHIND:
public partial class NewStyleItem : System.Web.UI.Page
{
protected StyleTemplateManager styleTempMngr = new StyleTemplateManager();
protected StyleFabricationManager styleFabMngr = new StyleFabricationManager();
protected List<ComponentReferenceView> ReferenceLookUpList
{
get
{
return (List<ComponentReferenceView>)ViewState["ReferenceLookUpView"];
}
set
{
ViewState["ReferenceLookUpView"] = value;
}
}
protected List<ComponentReferenceView> ReferenceViewList
{
get
{
return (List<ComponentReferenceView>)ViewState["CompReferenceView"];
}
set
{
ViewState["CompReferenceView"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack == false)
{
LoadBrandList();
ddlGarmentList.Enabled = false;
//ReferenceLookUpList = new List<ComponentReferenceView>();
}
else
{
}
//rptStyleComponents.DataSource = ReferenceLookUpList;
//rptStyleComponents.DataBind();
}
protected void LoadBrandList()
{
BrandManager brandMngr = new BrandManager();
ddlBrandList.Items.Clear();
ddlBrandList.Items.Add(new ListItem { Text = "Select brand", Value = "" });
foreach (Brand item in brandMngr.Brands())
{
ddlBrandList.Items.Add(new ListItem
{
Text = item.BrandDescription,
Value = item.BrandCode
});
}
}
protected void LoadComponentInfo(string BrandCode)
{
if (styleTempMngr.FindTemplateByBrandCode(BrandCode) == true)
{
ReferenceLookUpList = (from StyleComponent i in styleFabMngr.ComponentList
join StyleFabReference x in styleTempMngr.ReferenceList on
i.SectionCode equals x.SectionCode
select new ComponentReferenceView
{
InOrder = x.SortOrder,
IsNeeded = x.IsRequired,
SCode = x.SeriesCode,
SecCode = x.SectionCode,
SecName = i.SectionName,
EntryValue = x.DataCharacter
}).OrderBy(p => p.InOrder).ToList();
ReferenceLookUpList.Where(row => row.SecCode == "BCODE").ToList()
.ForEach(refItem => refItem.EntryValue = ddlBrandList.SelectedValue);
var DistinctList = (from StyleFabReference x in styleTempMngr.ReferenceList.OrderBy(p => p.SortOrder).ToList()
where x.SectionCode != "SPCHAR" && x.SectionCode != "BCODE"
select x.SectionCode).Distinct().ToList();
ReferenceViewList = (from StyleComponent i in styleFabMngr.ComponentList
join x in DistinctList on
i.SectionCode equals x
select new ComponentReferenceView
{
SecCode = x,
SecName = i.SectionName
}).OrderBy(p => p.InOrder).ToList();
}
else
ReferenceViewList = new List<ComponentReferenceView>();
rptStyleComponents.DataSource = ReferenceViewList;
rptStyleComponents.DataBind();
}
protected void LoadGarments(string ApparelCode)
{
if (string.IsNullOrEmpty(ddlBrandList.SelectedValue) == true)
{
ddlGarmentList.SelectedIndex = 0;
ddlGarmentList.Enabled = false;
}
else
{
ddlGarmentList.Enabled = true;
GarmentManager gmMngr = new GarmentManager();
List<Garment> garmentList = new List<Garment>();
garmentList = gmMngr.GetGarmentsByBrand(ddlBrandList.SelectedValue, ApparelCode);
ddlGarmentList.Items.Clear();
ddlGarmentList.Items.Add(new ListItem { Text = "Select garment", Value = "" });
foreach (Garment item in garmentList)
{
ddlGarmentList.Items.Add(new ListItem { Text = item.GarmentDescription, Value = item.GarmentCode });
}
}
}
protected void ddlBrandList_SelectedIndexChanged(object sender, EventArgs e)
{
txtNewStyleNo.Text = string.Empty;
if (string.IsNullOrEmpty(ddlBrandList.SelectedValue) == false)
LoadComponentInfo(ddlBrandList.SelectedValue);
}
[Serializable]
public class ComponentReferenceView
{
public string SCode
{
get;
set;
}
public string SecCode
{
get;
set;
}
public string SecName
{
get;
set;
}
public int InOrder
{
get;
set;
}
public bool IsNeeded
{
get;
set;
}
public string EntryValue
{
get;
set;
}
}
protected void rptStyleComponents_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
}
protected void rptStyleComponents_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddlControl = (DropDownList)e.Item.FindControl("ddlDataSelection");
if (ddlControl != null)
{
ddlControl.AppendDataBoundItems = true;
ddlControl.Items.Add(new ListItem { Text = "Select " + ReferenceViewList[e.Item.ItemIndex].SecName.ToLowerInvariant(), Value = "" });
var itemlist = (from x in styleFabMngr.ComponentRowItems(ReferenceViewList[e.Item.ItemIndex].SecCode).AsEnumerable()
select new ListItem
{
Text = x.Field<string>("col_name"),
Value = x.Field<string>("col_value")
});
ddlControl.Items.AddRange(itemlist.ToArray<ListItem>());
ddlControl.EnableViewState = false;
ddlControl.AutoPostBack = true;
ddlControl.SelectedIndexChanged += new EventHandler(DropDownListSelectedIndexChanged);
}
}
}
protected virtual void DropDownListSelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
RepeaterItem item = (RepeaterItem)ddl.NamingContainer;
ReferenceViewList[item.ItemIndex].EntryValue = ddl.SelectedValue;
ConstructStyleNo();
var Apparelfound = ReferenceViewList.Where(x => x.SecCode == "APCODE" &&
string.IsNullOrEmpty(x.EntryValue) == false).FirstOrDefault();
if (Apparelfound != null)
{
ddlGarmentList.Enabled = true;
LoadGarments(Apparelfound.EntryValue);
}
else
{
ddlGarmentList.Enabled = false;
}
}
private void ConstructStyleNo()
{
foreach (ComponentReferenceView item in ReferenceViewList)
{
ReferenceLookUpList.Where(row => row.SecCode == item.SecCode).ToList()
.ForEach(refItem => refItem.EntryValue = item.EntryValue);
}
string sResult = string.Empty;
var result = (from x in ReferenceLookUpList.OrderBy(y => y.InOrder)
select x.EntryValue);
txtNewStyleNo.Text = string.Empty;
if (result != null)
txtNewStyleNo.Text = String.Join("", result) + "0001";
}
private void ConstructStyleDescription()
{
txtStyleDescription.Text = ddlBrandList.SelectedItem.Text + "-" + ddlGarmentList.SelectedItem.Text;
}
protected void ddlGarmentList_SelectedIndexChanged(object sender, EventArgs e)
{
txtStyleDescription.Text = string.Empty;
if (string.IsNullOrEmpty(ddlGarmentList.SelectedValue) == false)
ConstructStyleDescription();
}
}
ASPX:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel ID="upnlNewFabrication" runat="server">
<ContentTemplate>
<h1>
New Style Item
</h1>
<br />
<%--<usrCtrl:style_generation ID="stylegen_frm" runat="server">
</usrCtrl:style_generation>--%>
<table>
<tr>
<td>
Brand :
</td>
<td>
<asp:DropDownList ID="ddlBrandList" runat="server"
onselectedindexchanged="ddlBrandList_SelectedIndexChanged"
AutoPostBack="True">
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td>
Generated Style# :
</td>
<td>
<asp:TextBox ID="txtNewStyleNo" runat="server" ReadOnly="true"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Style Description :
</td>
<td>
<asp:TextBox ID="txtStyleDescription" runat="server" ReadOnly="true"></asp:TextBox>
</td>
</tr>
<asp:Repeater ID="rptStyleComponents" runat="server"
onitemdatabound="rptStyleComponents_ItemDataBound"
onitemcreated="rptStyleComponents_ItemCreated"
EnableViewState="True">
<ItemTemplate>
<asp:UpdatePanel ID="upnlComponent" runat="server">
<ContentTemplate>
<tr>
<td>
<asp:Label ID="lblSectionName" runat="server" Text='<%# Eval("SecName")%>' ></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddlDataSelection" runat="server">
</asp:DropDownList>
</td>
</tr>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ddlDataSelection" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
</asp:Repeater>
</table>
<br />
<table>
<tr>
<td colspan="2">Description Items</td>
</tr>
<tr>
<td colspan="4"></td>
</tr>
<tr>
<td>Garment Type:</td>
<td>
<asp:UpdatePanel ID="upGarment" runat="server" >
<ContentTemplate>
<asp:DropDownList ID="ddlGarmentList" runat="server"
AppendDataBoundItems="True" AutoPostBack="True"
onselectedindexchanged="ddlGarmentList_SelectedIndexChanged">
<asp:ListItem Text = "Select garment" Value = ""></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="sdsGarment" runat="server"
ConnectionString="<%$ ConnectionStrings:IRMSConnectionString %>"
SelectCommand="Select * from Garments"></asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ddlGarmentList" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td>Cost Price:</td>
<td>
<asp:TextBox ID="txtCostPrice" runat="server"></asp:TextBox></td>
<td>SRP :</td>
<td><asp:TextBox ID="txtSRP" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Quantity :</td>
<td><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
<td>Week :</td>
<td><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>

Adding Dynamic Rows in Gridview and How to retain selected option from user control in Gridview

I have created user control named CRE.ascx,this control has 3 dropdownlist.
First dropdownlist bind data on pageload.Second and third based on SelectedIndexChanged.
<table cellspacing="0" cellspading="0" style="width:550px;height:30px;">
<tr>
<td style="width:30%;">
<asp:DropDownList ID="ddlCRE" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlCRE_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlDataPoints" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlDataPoints_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlErrorCode" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlErrorCode_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:10%;">
<asp:TextBox ID="tbxErrorScore" runat="server" style="height:17px;border:0px;font-family:'Segoe UI';font-size:13px;font-weight:500;color:white;background-color:#333333;
width:65px;" ReadOnly="true"> </asp:TextBox>
</td>
</tr>
</table>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Get Ticket Type Values
dbtickettype = helpdsktcktusrHandler.GetTicketType("DPT0001");
ddlCRE.DataSource = dbtickettype;
ddlCRE.DataValueField = "Type_ID";
ddlCRE.DataTextField = "Type_Name";
ddlCRE.DataBind();
ddlCRE.Items.Insert(0, new ListItem("Select Type", "SLCT0000"));
}
else
{
}
}
protected void ddlCRE_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedTypeID = ddlCRE.SelectedValue.ToString();
try
{
if (selectedTypeID == "SLCT0000")
{
ddlDataPoints.Items.Clear();
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketCategory = helpdsktcktusrHandler.GetTicketCategoryDetails(selectedTypeID);
//Binding Ticket Type values to Listbox
ddlDataPoints.DataSource = dbticketCategory;
ddlDataPoints.DataValueField = "Category_ID";
ddlDataPoints.DataTextField = "Category_Name";
ddlDataPoints.DataBind();
ddlDataPoints.Items.Insert(0, new ListItem("Select Category", "SLCT0000"));
//Clear Items
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlDataPoints_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCatID = ddlDataPoints.SelectedValue.ToString();
try
{
if (selectedCatID == "SLCT0000")
{
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketSubCategory = helpdsktcktusrHandler.GetTicketSubCategoryDetails(selectedCatID);
//Binding Ticket Type values to Listbox
ddlErrorCode.DataSource = dbticketSubCategory;
ddlErrorCode.DataValueField = "Sub_Category_ID";
ddlErrorCode.DataTextField = "Sub_Category_Name";
ddlErrorCode.DataBind();
ddlErrorCode.Items.Insert(0, new ListItem("Select Subcategory", "SLCT0000"));
//Clear Items
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlErrorCode_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedSubcatID = ddlErrorCode.SelectedValue.ToString();
try
{
if (selectedSubcatID == "SLCT0000")
{
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketIssues = helpdsktcktusrHandler.GetTicketIssueDetails(selectedSubcatID);
////Binding Ticket Type values to Listbox
//ddlstIssue.DataSource = dbticketIssues;
//ddlstIssue.DataValueField = "IssueID";
//ddlstIssue.DataTextField = "Issue_Name";
//ddlstIssue.DataBind();
tbxErrorScore.Text = dbticketIssues.Rows[0][1].ToString();
}
}
catch (Exception ex)
{
}
}
then register directive and an instance of the user control added to the page.
In this main page, i have added one Gridview, user control UC1 and two buttons
included in the ItemTemplate.
<%# Register src="~/CRE.ascx" TagName="InsertNewCRE" TagPrefix="uc1" %>
<asp:UpdatePanel ID="MainUpdatePanel" runat="server">
<ContentTemplate>
<div id="dvsubCRE" class="dvsubCRE" runat="server">
<!-----[[[ GRIDVIEW ADDING CRE ]]]----->
<div id="dvAddingErrorInfo" class="dvAddingErrorInfo">
<!-- LOAD CRE DROPDOWN INFO GRID -->
<asp:GridView ID="gvCREInfo" runat="server" CssClass="gvErrorInfo" AlternatingRowStyle-CssClass="" ShowFooter="false" ShowHeader="false"
EnableViewState="True" GridLines="None" EmptyDataText="No records found" AutoGenerateColumns="true" CaptionAlign="Left" CellPadding="0"
ShowHeaderWhenEmpty="True" OnRowCreated="gvCREInfo_RowCreated" OnRowCommand="gvCREInfo_RowCommand" >
<Columns>
<asp:BoundField DataField="RowNumber" />
<asp:TemplateField ItemStyle-Width="25%" ItemStyle-Height="20px">
<ItemTemplate>
<uc1:InsertNewCRE id="UC1InserCRE" runat="server" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgbtnAddCRE" runat="server" Width="20px" Height="20px" value="" ImageUrl="~/Images/Tracker/add.png"
CommandName="ButtonAddCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:ImageButton ID="imgbtnReoveCRE" runat="server" Width="20px" Height="20px" value="" Visible="false" ImageUrl="~/Images/Tracker/delete.png" CommandName="ButtonRemoveCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- LOAD CRE DROPDOWN INFO GRID CLOSE -->
</div>
<!-----[[[ GRIDVIEW ADDING CRE CLOSE ]]]----->
</div>
</ContentTemplate>
</asp:UpdatePanel>
When main page loads, user control UC1 loaded in the gridview and pull out the data from CRE.ascx page.I have bind dummy data on page load to the gridview.Add new row along with user control mentioned in the RowCommand.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
gvCREInfo.DataSource = dt;
gvCREInfo.DataBind();
}
else
{
}
}
catch (Exception ex)
{
}
}
protected void gvCREInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
#region ADD NEW CRE ROW
if (e.CommandName == "ButtonAddCRERow")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvCREInfo.Rows[index];
int count = gvCREInfo.Rows.Count;
DataRow drCurrentRow = null;
UserControl UC1 = (UserControl)(row.Cells[0].FindControl("UC1InserCRE"));
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
for (int i = 0; i <= (count - 1); i++)
{
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows.Add(drCurrentRow);
}
gvCREInfo.DataSource = dtCurrentTable;
gvCREInfo.DataBind();
}
#endregion
}
When i run this code working fine and i changed the first dropdownlist
it will pull data and bind to the second, like wise third one also.But when i click the add button selected data lost in the first row and second row control added not with data.How to retain existing selected data and load user control along with data it should not loss data event post back.Please help me and sort out this.
![enter image description here][1]
http://i.stack.imgur.com/wdYZv.jpg

background image disappears after using button in postbacktrigger of update panel in asp.net

Background image disappears after using button in postbacktrigger of update panel in asp.net.I have designed registraion form and have placed all controls in update panel.After clicking on submit button,data gets submitted ,the page refreshes and background image dissappears.The values are getting properly inserted in database.
PFB the HTML code for Registration.aspx:-
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<%# Register Src="~/UserControls/FacebookUserControl.ascx" TagName="facebookheader" TagPrefix="Uc1"%>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<style type="text/css">
.auto-style1 {
width: 100%;
}
</style>
<script type="text/javascript">
function HideCtrl(ctrl, timer) {
var ctry_array = ctrl.split(",");
var num = 0, arr_length = ctry_array.length;
while (num < arr_length) {
if (document.getElementById(ctry_array[num])) {
setTimeout('document.getElementById("' + ctry_array[num] + '").style.display = "none";', timer);
}
num += 1;
}
return false;
}
</script>
<script>
$(function () {
// Initialize Backgound Stretcher
$('BODY').bgStretcher({
images: ['images/slide-1.jpg'],
imageWidth: 1600,
imageHeight: 964,
resizeProportionally: true
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<section id="content">
<div class="main-block">
<div class="container_12">
<div class="wrapper">
<table>
<tr>
<td>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="vg1" HeaderText="Fields marked with (*) are required"
ForeColor="Red" CssClass="error" />
</td>
</tr>
<tr>
<td>
<div id="divErrorMess" runat="server" visible="false" class="mess">
<asp:Label ID="lblMessage" runat="server" ForeColor="Red" Visible="False"></asp:Label>
</div>
<div id="divBallon" runat="server" visible="false" class="mess">
<div>
<asp:Label ID="lblMessage2" runat="server" Visible="False" ForeColor="Red"></asp:Label>
</div>
</div>
</td>
</tr>
</table>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table style="width:358px; border:0;">
<tr>
<td> Full Name</td>
</tr>
<tr>
<td> <asp:TextBox ID="txtFullName" runat="server" placeholder="Enter your Full Name" ValidationGroup="vg1" Width="250px"></asp:TextBox>
<span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvFullName" runat="server" ErrorMessage=""
ControlToValidate="txtFullName" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationGroup="vg1"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td> Date Of Birth</td>
</tr>
<tr>
<td> <%--<asp:TextBox ID="txtDateOfBirth" runat="server" placeholder="Enter your Date Of Birth" ValidationGroup="vg1" Width="250px" ClientIDMode="Static">
</asp:TextBox>--%><%-- <span style="color:red">*</span> <asp:CalendarExtender ID="CalendarExtender1" runat="server" Format="MM-dd-yyyy"
TargetControlID="txtDateOfBirth"></asp:CalendarExtender>--%><%-- <asp:RequiredFieldValidator ID="rfvDob" runat="server" ErrorMessage=""
ControlToValidate="txtDateOfBirth" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationGroup="vg1"></asp:RequiredFieldValidator>--%><asp:DropDownList ID="ddlMonth" runat="server" OnSelectedIndexChanged="ddlMonth_SelectedIndexChanged" placeholder="Month" AutoPostBack="true">
</asp:DropDownList> <span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvMonth"
runat="server" ErrorMessage="*" ControlToValidate="ddlMonth" ForeColor="Red"
SetFocusOnError="True" ValidationGroup="vg1"></asp:RequiredFieldValidator>
<asp:DropDownList ID="ddlDate" runat="server" AutoPostBack="true">
</asp:DropDownList> <span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvDate"
runat="server" ErrorMessage="*" ControlToValidate="ddlDate" ForeColor="Red"
SetFocusOnError="True" ValidationGroup="vg1"></asp:RequiredFieldValidator>
<asp:DropDownList ID="ddlYear" runat="server" OnSelectedIndexChanged="ddlYear_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList> <span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvYear" runat="server"
ErrorMessage="*"
ForeColor="Red" SetFocusOnError="True" ValidationGroup="vg1"
ControlToValidate="ddlYear"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td> Phone Number</td>
</tr>
<tr>
<td> <asp:TextBox ID="txtPhoneNumber" runat="server" placeholder="Enter your Phone Number" ValidationGroup="vg1" Width="250px">
</asp:TextBox>
<span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvPhone" runat="server" ErrorMessage=""
ControlToValidate="txtPhoneNumber" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationGroup="vg1"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revPhone" runat="server" ErrorMessage="Enter only 10 digit number"
ControlToValidate="txtPhoneNumber" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationExpression="^[0-9]{10}" ValidationGroup="vg1"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td> Email Address</td>
</tr>
<tr>
<td> <asp:TextBox ID="txtEmail" runat="server" placeholder="Enter your Email address" ValidationGroup="vg1" Width="250px">
</asp:TextBox>
<span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvEmail" runat="server" ErrorMessage=""
ControlToValidate="txtEmail" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationGroup="vg1"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmail" runat="server" ErrorMessage="Invalid Email!"
ControlToValidate="txtEmail" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ValidationGroup="vg1">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td> Submit 2 Photos</td>
</tr>
<tr>
<td> <asp:FileUpload ID="FileUpload1" runat="server" Width="250px" />
<span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvPhoto1" runat="server" ErrorMessage=""
ControlToValidate="FileUpload1" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationGroup="vg1"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td> <asp:FileUpload ID="FileUpload2" runat="server" Width="250px"/>
<span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvPhoto2" runat="server" ErrorMessage=""
ControlToValidate="FileUpload2" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationGroup="vg1"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td> Terms & Conditions</td>
</tr>
<tr>
<td> <asp:CheckBox ID="chkAgree" runat="server" /> I agree to Terms and Conditions</td>
</tr>
<tr>
<td> <asp:ImageButton ID="btnSubmit" runat="server" ImageUrl="~/images/submit.png" OnClick="btnSubmit_Click" ValidationGroup="vg1" />
<asp:ImageButton ID="btnReset" runat="server" ImageUrl="~/images/reset.png" CausesValidation="False" OnClick="btnReset_Click" />
</td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlMonth" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="ddlDate" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="ddlYear" EventName="SelectedIndexChanged" />
<asp:PostBackTrigger ControlID="btnSubmit" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
<div class="sidebar">
<Uc1:facebookheader ID="fbtag" runat="server" />
</div>
</div>
</section>
<%-- </div> --%>
</form>
</asp:Content>
PFB code for Registration.aspx.cs:
The below code contains data for registration.aspx. In the below i have used dropdownlist to enter date as input and necessary validations are performed for date.I have used arraylist to add months and used for loop to add years.Also i have used CheckLeapYear fn to check leap year.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Net.Mail;
using System.Collections;
public partial class Register : System.Web.UI.Page
{
int year;
string month;
protected void Page_Load(object sender, EventArgs e)
{
//System.Web.UI.HtmlControls.HtmlGenericControl divmain = (System.Web.UI.HtmlControls.HtmlGenericControl)Master.FindControl("divmain");
//divmain.Attributes.Add("class", "extra-block");
if (!IsPostBack)
{
this.Page.Title = "Register Us With Now to kick start your Career in MatureModelling";
this.Page.MetaDescription =
"MatureModelling connects new faces and models with scouts, international model photo "
+ "shoot and photographers. Casting Directors are now Looking"
+ " For real Models To Front Their Campaigns.";
this.Page.MetaKeywords =
"international photographers, expert model advice";
System.Web.UI.HtmlControls.HtmlGenericControl aRegister = (System.Web.UI.HtmlControls.HtmlGenericControl)Master.FindControl("Register");
aRegister.Attributes.Add("class", "current");
Response.Cache.SetNoStore();
DateTime tnow = DateTime.Now;
ArrayList ayear = new ArrayList();
int i;
for (i = 1970; i <= DateTime.Now.Year; i++)
{
ayear.Add(i);
}
ArrayList amonth = new ArrayList();
amonth.Add("Jan");
amonth.Add("Feb");
amonth.Add("Mar");
amonth.Add("Apr");
amonth.Add("May");
amonth.Add("Jun");
amonth.Add("Jul");
amonth.Add("Aug");
amonth.Add("Sep");
amonth.Add("Oct");
amonth.Add("Nov");
amonth.Add("Dec");
ddlYear.DataSource = ayear;
ddlYear.DataBind();
ddlMonth.DataSource = amonth;
ddlMonth.DataBind();
ddlYear.SelectedValue = tnow.Year.ToString();
ddlMonth.SelectedValue = tnow.Month.ToString();
year = Int32.Parse(ddlYear.SelectedValue);
month = Convert.ToString(ddlMonth.SelectedValue);
BindDays(year, month);
ddlDate.SelectedValue = tnow.Day.ToString();
}
}
#region Button Event
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
lblMessage.Text = "";
string strScript = string.Empty;
string strCtrl = divErrorMess.ClientID;
strScript = "HideCtrl('" + strCtrl + "', '3000')";
try
{
if (chkAgree.Checked)
{
Registration objRegistration = new Registration();
objRegistration.FirstName = txtFullName.Text.Trim().ToString();
//objRegistration.BirthDate = txtDateOfBirth.Text.Trim().ToString();
objRegistration.BirthDate = ddlYear.SelectedItem.Text.ToString()
+ "-" + ddlMonth.SelectedItem.Value.ToString()
+ "-" + ddlDate.SelectedItem.Text.ToString();
objRegistration.EmailId = txtEmail.Text.Trim().ToString();
objRegistration.PhoneNo = txtPhoneNumber.Text.Trim().ToString();
if (FileUpload1.HasFile)
{
objRegistration.Photo1 = DateTime.Now.ToString("ddMMyyyy") + FileUpload1.FileName.ToString();
}
string pathBig = Server.MapPath("~\\ModelPhotos\\" + DateTime.Now.ToString("ddMMyyyy") + FileUpload1.FileName.ToString());
ViewState["pathBig"] = pathBig;
if (File.Exists(pathBig))
{
//File.Delete(pathBig);
FileUpload1.SaveAs(pathBig);
}
else
{
FileUpload1.SaveAs(pathBig);
}
if (FileUpload2.HasFile)
{
objRegistration.Photo2 = DateTime.Now.ToString("ddMMyyyy") + FileUpload2.FileName.ToString();
}
string pathBig1 = Server.MapPath("~\\ModelPhotos\\" + DateTime.Now.ToString("ddMMyyyy")+FileUpload2.FileName.ToString());
ViewState["pathBig1"] = pathBig1;
if (File.Exists(pathBig1))
{
//File.Delete(pathBig1);
FileUpload2.SaveAs(pathBig1);
}
else
{
FileUpload2.SaveAs(pathBig1);
}
if (chkAgree.Checked)
{
objRegistration.IsAgree = "true";
}
else
{
objRegistration.IsAgree = "false";
}
RegistrationOperation objRegisterOperation = new RegistrationOperation();
int k = Convert.ToInt32(objRegisterOperation.InsertRegisterUser(objRegistration));
if (k==0)
{
divErrorMess.Visible = false;
divBallon.Visible = true;
lblMessage2.Visible = true;
lblMessage2.ForeColor = System.Drawing.Color.Green;
lblMessage2.Text = "User Created Successfully!";
lblMessage.Text = string.Empty;
Session["result"] = "insert";
// sendmail();
// sendmailtoadmin();
fnClearControls();
divBallon.Visible = true;
strScript="HideCtrl('"+divBallon.ClientID+"','3000')";
}
else if (k==1)
{
divErrorMess.Visible = true;
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Sorry,Please try again!";
divBallon.Visible = false;
}
else if (k==2)
{
divErrorMess.Visible = true;
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Blue;
lblMessage.Text = "Email Id already exists!";
divBallon.Visible = false;
}
}
else
{
divErrorMess.Visible = true;
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Orange;
lblMessage.Text = "Please accept terms & conditions";
divBallon.Visible = false;
}
}
catch (Exception ex)
{
throw ex;
}
Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), strScript, true);
}
protected void btnReset_Click(object sender, ImageClickEventArgs e)
{
fnClearControls();
divBallon.Visible = false;
divErrorMess.Visible = false;
}
#endregion
#region Private Method
private void fnClearControls()
{
txtFullName.Text = " ";
//txtLastName.Text = "";
txtPhoneNumber.Text = "";
// txtParentsPhoneNumber.Text = "";
txtEmail.Text = "";
chkAgree.Checked = false;
//txtDateOfBirth.Text = "";
ddlDate.SelectedIndex = 0;
ddlMonth.SelectedIndex = 0;
ddlYear.SelectedValue = Convert.ToString(DateTime.Now.Year);
}
public void FillDays()
{
ddlDate.Items.Clear();
//getting numbner of days in selected month & year
int noofdays = DateTime.DaysInMonth(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt32(ddlMonth.SelectedValue));
//Fill days
for (int i = 0; i <= noofdays; i++)
{
ddlDate.Items.Add(i.ToString());
}
ddlDate.Items.FindByValue(System.DateTime.Now.Day.ToString()).Selected = true;
}
private bool CheckLeapYear(int year)
{
if ((year%4==0)&&(year%100!=0)||(year%400==0))
return true;
else return false;
}
private void BindDays(int year, string month)
{
int i;
ArrayList aday = new ArrayList();
switch (month)
{
case "Jan":
case "Mar":
case "May":
case "Jul":
case "Aug":
case "Oct":
case "Dec":
for (i = 1; i <= 31; i++)
{
aday.Add(i);
}
break;
case "Feb":
if (CheckLeapYear(year))
{
for (i = 1; i <= 29; i++)
aday.Add(i);
}
else
{
for (i = 1; i <= 28; i++)
aday.Add(i);
}
break;
case "Apr":
case "Jun":
case "Sep":
case "Nov":
for (i = 1; i <= 30; i++)
aday.Add(i);
break;
}
ddlDate.DataSource = aday;
ddlDate.DataBind();
}
#endregion
Following are dropdownlist events adn BindDays fn is used.
#region DDL events
protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
{
year = Int32.Parse(ddlYear.SelectedValue);
month = Convert.ToString(ddlMonth.SelectedValue);
BindDays(year, month);
}
Following are dropdownlist events adn BindDays fn is used.
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
year = Int32.Parse(ddlYear.SelectedValue);
month = Convert.ToString(ddlMonth.SelectedValue);
BindDays(year, month);
}
#endregion
}
It looks like you probably just need to call that JavaScript function that initializes your "Background Stretcher" on each UpdatePanel update (rather than just when the DOM loads). Changing that function to this should do the trick:
function pageLoad() {
$('BODY').bgStretcher({
images: ['images/slide-1.jpg'],
imageWidth: 1600,
imageHeight: 964,
resizeProportionally: true
});
}
Notice that I used function pageLoad() { (should be called on each postback, including AJAX partial postbacks) rather than $(function () { (only called once, when the DOM loads).

not working paging functionality of my gridview

i put my problem here ,it is shown in screenshot.
my code is below.
code for .aspx file
<asp:GridView ID="grid" runat="server" DataKeyNames="EventID" AutoGenerateColumns="false"
Width="100%" AllowPaging="True" OnRowDataBound="grid_RowDataBound" PageSize="3"
OnRowEditing="grid_RowEditing" OnRowUpdating="grid_RowUpdating" OnRowCancelingEdit="grid_RowCancelingEdit"
OnPageIndexChanging="grid_PageIndexChanging">
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NextPreviousFirstLast"
NextPageText="Next" PreviousPageText="Prev" PageButtonCount="3" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
Client Name
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblClientName" runat="server" Text='<%# Eval("ClientName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtClientName" runat="server" Text='<%# Eval("ClientName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Event Name
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblEventName" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEventName" runat="server" Text='<%# Eval("Name")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Invited Persons
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblNoOfInvitees" runat="server" Text='<%# Eval("No_Of_Invitees")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNoOfInvitees" runat="server" Text='<%# Eval("No_Of_Invitees")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Total Invitees
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblTotalInvitees" runat="server" Text='<%# Eval("Total_Invitees")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtTotalInvitees" runat="server" Text='<%# Eval("Total_Invitees")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Extra Invitees
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblExtraInvitees" runat="server" Text='<%# Eval("Extra_Invitees")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtExtraInvitees" runat="server" Text='<%# Eval("Extra_Invitees")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Confirmed
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblConfirmed" runat="server" Text='<%# Eval("Extra_Invitees")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtConfirmed" runat="server" Text='<%# Eval("Extra_Invitees")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" HeaderText="Edit" />
<%-- <asp:TemplateField>
<HeaderTemplate>
Delete
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton CommandName="Delete" ID="btnDelete" runat="server" Text="Delete"
OnClientClick="return validate();" />
<script type="text/javascript" language="javascript">
function validate() {
return confirm('Are you sure want to delete this user ?');
}
</script>
</ItemTemplate>
</asp:TemplateField>--%>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>
Showing
<asp:Label ID="PageIdxLabel" Text="1" runat="server" />
to
<asp:Label ID="PageRowCountLabel" runat="server" />
of
<asp:Label ID="PageTotalLabel" runat="server" Text="Label" />
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
and aspx.cs file coding is here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataLayer;
using System.Data.Linq;
using System.Web.Extensions;
using System.Web.UI.WebControls.WebParts;
namespace EventManagerApp
{
public partial class EventList : System.Web.UI.Page
{
EventManagerDataContext db = new EventManagerDataContext();
[System.Web.Services.WebMethod]
public static string[] GetNames(string prefixText)
{
EventManagerDataContext db = new EventManagerDataContext();
return db.EMR_EVENTs.Where(n => n.Name.StartsWith(prefixText)).OrderBy(n => n.Name).Select(n => n.Name).ToArray();
//return db.EMR_CLIENTs.Where(n => n.Name.StartsWith(prefixText)).OrderBy(n => n.Name).Select(n => n.Name).ToArray();
}
protected void grid_RowEditing(object sender, GridViewEditEventArgs e)
{
grid.EditIndex = e.NewEditIndex;
grdBind();
}
protected void grid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grid.EditIndex = -1;
grdBind();
}
protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int EventID = Convert.ToInt32(grid.DataKeys[e.RowIndex].Value.ToString());
string ClientName = ((TextBox)grid.Rows[e.RowIndex].FindControl("txtClientName")).Text;
string EventName = ((TextBox)grid.Rows[e.RowIndex].FindControl("txtEventName")).Text;
int TotalInvitees = int.Parse(((TextBox)grid.Rows[e.RowIndex].FindControl("txtTotalInvitees")).Text);
int ExtraInvitees = int.Parse(((TextBox)grid.Rows[e.RowIndex].FindControl("txtExtraInvitees")).Text);
int Confirmed = int.Parse(((TextBox)grid.Rows[e.RowIndex].FindControl("txtConfirmed")).Text);
EventManagerDataContext db = new EventManagerDataContext();
var q = (from a in db.EMR_EVENTs
join b in db.EMR_CLIENTs on a.ClientID equals b.ClientID
where a.EventID == EventID
select a).First();
q.EMR_CLIENT.Name = ClientName;
q.Name = EventName;
q.No_Of_Invitees = TotalInvitees;
q.Extra_Invitees = ExtraInvitees;
q.Total_Invitees = ExtraInvitees + TotalInvitees;
db.SubmitChanges();
grid.EditIndex = -1;
grdBind();
}
protected void Page_Load(object sender, EventArgs e)
{
lblwelcometext.Text = (string)(Session["name"]);
try
{
if (!IsPostBack)
{
grdBind();
bindClients();
}
}
catch (Exception ex)
{
throw ex;
}
}
public class DALClass
{
private static EventManagerDataContext db = new EventManagerDataContext() { CommandTimeout = 36000 };
public static List<EMR_CLIENT> GetClients()
{
return db.EMR_CLIENTs.ToList();
}
}
protected void bindClients()
{
drpClient.DataSource = DALClass.GetClients();
drpClient.DataTextField = "Name";
drpClient.DataValueField = "ClientID";
drpClient.DataBind();
string Name = drpClient.SelectedItem.Value;
}
protected void grdBind()
{
try
{
EventManagerDataContext db = new EventManagerDataContext();
if (txtSearchEvent.Text == "")
{
var q = from a in db.EMR_EVENTs
join b in db.EMR_CLIENTs on a.ClientID equals b.ClientID
select new
{
ClientName = b.Name,
ClientID = a.ClientID,
Name = a.Name,
No_Of_Invitees = a.No_Of_Invitees,
Extra_Invitees = a.Extra_Invitees,
Total_Invitees = a.Extra_Invitees + a.No_Of_Invitees,
EventID = a.EventID
};
grid.DataSource = q.ToList();
grid.PageSize = int.Parse(drpPageSize.SelectedValue);
grid.DataBind();
}
else
{
var data = from a in db.EMR_EVENTs
join b in db.EMR_CLIENTs on a.ClientID equals b.ClientID
where a.Name.StartsWith(txtSearchEvent.Text.Trim())
select new
{
ClientName = b.Name,
ClientID = a.ClientID,
Name = a.Name,
No_Of_Invitees = a.No_Of_Invitees,
Extra_Invitees = a.Extra_Invitees,
Total_Invitees = a.Extra_Invitees + a.No_Of_Invitees,
EventID = a.EventID
};
grid.DataSource = data.ToList();
grid.PageSize = int.Parse(drpPageSize.SelectedValue);
grid.DataBind();
}
}
catch
{
throw;
}
}
protected void txtSearchEvent_TextChanged(object sender, EventArgs e)
{
grdBind();
}
protected void drpPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
grid.PageSize = int.Parse(drpPageSize.SelectedItem.Text);
grdBind();
}
protected void drpClient_SelectedIndexChanged(object sender, EventArgs e)
{
if (drpClient.SelectedIndex == 0)
{
grid.PageSize = int.Parse(drpPageSize.SelectedValue);
grdBind();
}
else
{
var q = from a in db.EMR_EVENTs
join b in db.EMR_CLIENTs on a.ClientID equals b.ClientID
where a.ClientID == int.Parse(drpClient.SelectedValue.ToString())
select new
{
ClientName = b.Name,
ClientID = a.ClientID,
Name = a.Name,
No_Of_Invitees = a.No_Of_Invitees,
Extra_Invitees = a.Extra_Invitees,
Total_Invitees = a.Extra_Invitees + a.No_Of_Invitees,
EventID = a.EventID
};
grid.DataSource = q.ToList();
grid.PageSize = int.Parse(drpPageSize.SelectedValue);
grid.DataBind();
}
}
protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grid.PageIndex = e.NewPageIndex;
grdBind();
}
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
EventManagerDataContext db = new EventManagerDataContext();
var q = from a in db.EMR_EVENTs
join b in db.EMR_CLIENTs on a.ClientID equals b.ClientID
select new
{
ClientName = b.Name,
ClientID = a.ClientID,
Name = a.Name,
No_Of_Invitees = a.No_Of_Invitees,
Extra_Invitees = a.Extra_Invitees,
Total_Invitees = a.Extra_Invitees + a.No_Of_Invitees,
EventID = a.EventID
};
PageTotalLabel.Text = q.Count().ToString();
PageRowCountLabel.Text = grid.Rows.Count.ToString();
// PageIdxLabel.Text = grid.PageIndex.ToString();
}
}
}
so my problem is i want update pageindex value as per click on next and previous button.
This is the solution of my question ,i solved it my self.
Thanks stackoverflow.
int pagetotal = q.Count();
int pagerowcount = (grid.PageIndex * grid.PageSize) + grid.Rows.Count;
PageIdxLabel.Text = ((grid.PageIndex * grid.PageSize) + 1).ToString() + "to " + Convert.ToString(pagerowcount) + "of" + (pagetotal).ToString();

add a onclientclick to gridview pager

Using asp.net and the gridview control with the pager.
How do I add a onclientclick to it, So that it will only page once the onclientclick returns true.
Is this possible as it can be done with a link?
i know I can do this
GridView pager page buttons accessibility
myGridView.Attributes.Add("onClick", "setOKToClose();")
but it addes it to the grid and I want it only added to the pager
Thanks
Convert your pager to template but you will have to make your own logic for showing and managing page index.
Here in a sample code
<PagerTemplate>
<asp:Panel ID="gvpanel" runat="server">
<table cellpadding="3" cellspacing="3" class="style4">
<tr>
<td width="20%">
<asp:Label ID="Label4" runat="server" CssClass="lb" Text="Page "></asp:Label>
<asp:DropDownList ID="ddpage" runat="server" AutoPostBack="True" CssClass="txt"
onselectedindexchanged="ddpage_SelectedIndexChanged">
</asp:DropDownList>
<asp:Label ID="Label5" runat="server" CssClass="lb" Text="of "></asp:Label>
<asp:Label ID="lbltot" runat="server" CssClass="lb" Text="0"></asp:Label>
</td>
<td width="60%">
<table class="style1">
<tr>
<td width="15%">
<asp:LinkButton ID="lbp10" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lbp10_Click">Previous 10</asp:LinkButton>
</td>
<td width="15%">
<asp:LinkButton ID="lbp" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lbp_Click">Previous</asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="lb1" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lb1_Click">1 </asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="lb2" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lb1_Click">2 </asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="lb3" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lb1_Click">3 </asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="lb4" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lb1_Click">4 </asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="lb5" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lb1_Click">5 </asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="lb6" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lb1_Click">6 </asp:LinkButton>
</td>
<td >
<asp:LinkButton ID="lb7" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lb1_Click">7 </asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="lb8" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lb1_Click">8 </asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="lb9" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lb1_Click">9 </asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="lb10" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lb1_Click">10</asp:LinkButton>
</td>
<td width="15%">
<asp:LinkButton ID="lbn" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lbn_Click">Next</asp:LinkButton>
</td>
<td width="15%">
<asp:LinkButton ID="lbn10" runat="server" CssClass="smalllinkbuttonf"
Enabled="False" onclick="lbn10_Click">Next 10</asp:LinkButton>
</td>
</tr>
</table>
</td>
<td width="20%">
</td>
</tr>
</table>
</asp:Panel>
</PagerTemplate>
Here is the c# code
protected void lbp10_Click(object sender, EventArgs e)
{
GridView1.PageIndex = (GridView1.PageIndex - 10);
bind();
}
protected void lbp_Click(object sender, EventArgs e)
{
GridView1.PageIndex = (GridView1.PageIndex - 1);
bind();
}
protected void lbn_Click(object sender, EventArgs e)
{
GridView1.PageIndex = (GridView1.PageIndex + 1);
bind();
}
protected void lbn10_Click(object sender, EventArgs e)
{
GridView1.PageIndex = (GridView1.PageIndex + 10);
bind();
}
protected void lb1_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridView1.PageIndex = (int.Parse(lb.Text) - 1);
bind();
}
Code for creating the footer
void addfooter(int rcount)
{
if (GridView1.BottomPagerRow == null)
{
return;
}
Panel p = (Panel)GridView1.BottomPagerRow.FindControl("gvpanel");
DropDownList dd = (DropDownList)p.FindControl("ddpage");
for (int i = 0; i < rcount; i++)
{
ListItem li = new ListItem();
li.Text = (i + 1).ToString();
li.Value = (i + 1).ToString();
dd.Items.Add(li);
}
Label lbltot = (Label)p.FindControl("lbltot");
lbltot.Text = GridView1.PageCount.ToString();
dd.SelectedIndex = GridView1.PageIndex;
LinkButton lbp10 = (LinkButton)p.FindControl("lbp10");
lbp10.Enabled = false;
lbp10.CssClass = "smalllinkbuttonfd";
LinkButton lbp = (LinkButton)p.FindControl("lbp");
lbp.Enabled = false;
lbp.CssClass = "smalllinkbuttonfd";
LinkButton lbn10 = (LinkButton)p.FindControl("lbn10");
lbn10.Enabled = false;
LinkButton lbn = (LinkButton)p.FindControl("lbn");
lbn.CssClass = "smalllinkbuttonfd";
lbn.Enabled = false;
lbn10.CssClass = "smalllinkbuttonfd";
int cpage = GridView1.PageIndex + 1;
int totpage = GridView1.PageCount;
if (cpage > 10)
{
lbp10.Enabled = true;
lbp10.CssClass = "smalllinkbuttonf";
}
if (cpage > 1)
{
lbp.Enabled = true;
lbp.CssClass = "smalllinkbuttonf";
}
if (cpage < totpage)
{
lbn.Enabled = true;
lbn.CssClass = "smalllinkbuttonf";
}
if (cpage + 10 < totpage)
{
lbn10.Enabled = true;
lbn10.CssClass = "smalllinkbuttonf";
}
for (int i = 1; i < 11; i++)
{
LinkButton lb = (LinkButton)p.FindControl("lb" + i.ToString());
lb.Enabled = false;
lb.CssClass = "smalllinkbuttonfd";
}
int tstart = cpage / 10;
int lcount = tstart + 10;
//int scount = tstart - 10;
int cnt = 1;
for (int i = (tstart * 10); i <= ((tstart * 10) + 10); i++)
{
if (cnt > 10)
{
return;
} if ((i + 1) > totpage)
{
LinkButton lb = (LinkButton)p.FindControl("lb" + cnt.ToString());
lb.Enabled = false;
lb.Text = (i + 1).ToString();
lb.CssClass = "smalllinkbuttonfd";
cnt++;
}
else
{
if ((i + 1) == cpage)
{
LinkButton lb = (LinkButton)p.FindControl("lb" + cnt.ToString());
lb.Enabled = false;
lb.Text = (i + 1).ToString();
lb.CssClass = "smalllinkbuttonfd";
cnt++;
}
else
{
LinkButton lb = (LinkButton)p.FindControl("lb" + cnt.ToString());
lb.Enabled = true;
lb.Text = (i + 1).ToString();
lb.CssClass = "smalllinkbuttonf";
cnt++;
}
}
}
}
Onlink button now you can add onclientclick
This link has a correct answer combined with this answer.
Be sure to add a <asp:ScriptManager runat="server" /> tag in your document. Add the javascript in the page header section.
function pageLoad(sender, args) {
//Your jquery code
}
Excellent reference can be found in $(document).ready() and pageLoad() are not the same!
Cheers!
add to GridView RowDataBound
If e.Row.RowType = DataControlRowType.Pager Then
e.Row.Attributes.Add("onclick", "js_function()")
End If

Categories

Resources