How to Find the control in repeater - c#

<asp:Repeater ID="rpt_slider" runat="server" OnItemDataBound="rpt_slider_ItemDataBound">
<ItemTemplate>
<cc:HtmlEditor ID="Htmleditor1" runat="server" Height="300px" Width="550px" DialogButtonBarColor="Gray" DialogHeadingColor="Gray" DialogUnselectedTabColor="Gray" TabBackColor="Gray" Text='<%# Eval("banner_text")%>' DialogSelectedTabColor="Gray" EditorBorderColor="Gray" SelectedTabBackColor="Maroon" ToolbarColor="Silver" ToolstripBackgroundImage="Default" ButtonMouseOverColor="Gray" SelectedTabTextColor="WhiteSmoke" TabbarBackColor="Gainsboro" TabMouseOverColor="Gray" DialogSelectedTabTextColor="White" />
</ItemTemplate>
</asp:Repeater>
how to get here text of html editor from Repeater...
here Text='<%# Eval("banner_text")%>' are bound on repeater and how to get text on my c# code??

Try this... I 've tested your tool.. It works..
Add using Winthusiasm.HtmlEditor; as shown below.
Then you can access your editor from server side. You can use below method to find the Editor from your repeater.
By using editor.Text, You can get Editor's Text
If you did't add the Reference DLL Please add it to your references. Otherwise you 'll get errors when you put using Winthusiasm.HtmlEditor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Winthusiasm.HtmlEditor;
namespace ListDrop
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
{
Editor editor= (Editor)item.FindControl("Editor1");
lblMessage.Text = editor.Text;
}
}
}
}
}

FINNAY I GOT MY SOLLUTION.
protected void btnUpdate2_click(object sender, EventArgs e)
{
try
{
Button ib = (Button)sender;
// string index = (ib.CommandName);
RepeaterItem gr = (RepeaterItem)ib.NamingContainer;
int index = gr.ItemIndex;
property.banner_type = "Primary";
property.active = Convert.ToBoolean(((CheckBox)rpt_slider.Items[index].FindControl("checkActive")).Checked);
property.banner_index = Convert.ToInt32(((DropDownList)rpt_slider.Items[index].FindControl("drop_IndexNo")).SelectedValue);
property.banner_id = Convert.ToInt32(ib.CommandArgument);
property.bottom_pos = Convert.ToInt32(((TextBox)rpt_slider.Items[index].FindControl("txtBPOS")).Text);
property.right_pos = Convert.ToInt32(((TextBox)rpt_slider.Items[index].FindControl("txtRPOS")).Text);
property.cr_user = Convert.ToInt32(Session["admin_id"]);
property.cr_date = Convert.ToDateTime(DateTime.Now.ToString());
property.banner_text = Convert.ToString(((HtmlEditor)rpt_slider.Items[index].FindControl("Htmleditor1")).Text);
property.tag = 2;
try
{
int result = 0;
result = balss.banner_insert(property.banner_id, property.banner_type, "", "", property.active, property.banner_index, property.cr_user, property.cr_date, property.banner_text, property.bottom_pos, property.right_pos, property.tag);
if (result > 0)
{
ClientScript.RegisterStartupScript(this.up1.GetType(), "Script", "<script type='text/javascript'>alert('Record Updated successfully.');</script>");
}
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "script", "<script text='text/javascript'> alert('" + ex.Message + "')</script>");
}
finally
{
}
getdata();
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "script", "<script type='text/javascript'>alert(' " + ex.Message + "');</script>", false);
}
finally
{
}
Response.Redirect("edit_banner");
}
on button submit click i am used
property.banner_text = Convert.ToString(((HtmlEditor)rpt_slider.Items[index].FindControl("Htmleditor1")).Text);
for get value of html editor for repeater.

Related

get data from two different pages

Here is my problem. suppose by example, when I click on repeater row id then it will transfer to particular customers invoice.
But in customer invoice page, it opens only when customer Id logged in. So here two different pages accessing one page data. my code is as below.
In repeater's page.
<th>
<asp:LinkButton ID ="lnkbtnStmt" Text ="Statement" OnClick ="lnkbtnStmt_Click" runat="server"></asp:LinkButton>
<asp:HiddenField ID ="hfStmt" runat ="server" Value='<% #Eval("No")%>'/>
</th>
in repeater .cs page :
public void lnkbtnStmt_Click(object sender, EventArgs e)
{
int rptIndex = ((RepeaterItem)((LinkButton)sender).NamingContainer).ItemIndex;
string hfItem = Convert.ToString(((HiddenField)RptEmpCustInvoise.Items[rptIndex].FindControl("hfStmt")).Value);
Customer_Ledger_Entries custlist = new Customer_Ledger_Entries();
List<Customer_Ledger_Entries_Filter> cFilter = new List<Customer_Ledger_Entries_Filter>();
Customer_Ledger_Entries_Filter cfield = new Customer_Ledger_Entries_Filter();
cfield.Field = Customer_Ledger_Entries_Fields.Customer_No;
cfield.Criteria = hfItem;
cFilter.Add(cfield);
Customer_Ledger_Entries[] culist = cls.wsCustInvoice.ReadMultiple(cFilter.ToArray(), null, 1);
if (culist.Length > 0)
{
Response.Redirect("frmCustomerInvoice.aspx?Customer_No=" + hfItem);
}
}
And in another Customer page.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
GetOpeningBal();
bindCustInvoice(objSession.getSession(HttpContext.Current, "NonEmpCode"));
string empCustId = Request.QueryString["Customer_No"];
if (empCustId.Length != 0)
{
CustInvoice("empCustId");
}
GetClosingBal();
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), string.Empty, "alert('" + ex.Message.ToString() + "');", true);
}
}
In this page,bindCustInvoice() method works when customer get logged in and CustInvoice("empCustId"); method works when we clicked on repeater id.
can any one give me solution?
When you clicked on Repeater Id , try to send the Page Name from Query String . and check the page name in your another customer page
Pseudo code
string PageName ="";
if(Request.QueryString["PageName"] != null)
{
PageName= Request.QueryString["PageName"];
}
if(PageName != "")
{
string empCustId = Request.QueryString["Customer_No"];
if (empCustId.Length != 0)
{
CustInvoice("empCustId");
}
}
else{
bindCustInvoice(objSession.getSession(HttpContext.Current, "NonEmpCode"));
}

ASP.NET Textbox text does not change while trying to update

I have a form where there is a ListBox, a textbox and four buttons called Save, Edit, Delete and Clear. I'm retrieving data from database and populating the ListBox. When I select one of the items in the ListBox, it is populated into the textbox. Now when I delete that item, there is nothing wrong, it works fine. But when I try to update that item, i.e. change the text in the textbox and then click the Edit button, there is problem. In the textbox, I can see the text is being changed, no problem with that, but when I debugged, I found in the backend, the textbox is still containing the old text and not the modified one.
What am I doing wrong?
Here's my UI code:
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<h1>Employee Category</h1>
<table>
<td>
<asp:ListBox ID="listEmployeeCategory" runat="server" Height="164px" Width="210px" AutoPostBack="true" />
</td>
<td>
<table>
<tr>
<td>
<asp:Label ID="lblMessage" runat="server" Text="" Visible="false" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblEmpCategoryName" runat="server" Text="Name: " Font-Bold="true" />
</td>
<td>
<asp:TextBox ID="txtEmpCategoryName" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="rqdEmpCategoryName" ControlToValidate="txtEmpCategoryName" ErrorMessage="Employee Category Name can't be empty!" Style="color:Red" runat="server" />
</td>
</tr>
</table>
<asp:Button ID="btnSave" Text="Save" runat="server" OnClick="btnSave_Click" />
<asp:Button ID="btnEdit" Text="Edit" runat="server" OnClick="btnEdit_Click" />
<asp:Button ID="btnDelete" Text="Delete" runat="server" OnClick="btnDelete_Click" />
<asp:Button ID="btnCancel" Text="Cancel" runat="server" />
</td>
</table>
</asp:Content>
And here's my backend code, for the sake of everyone's understanding, I'm posting my entire backend code (except the BL, DAL and DAO codes):
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 Shelter.DAO.MasterEntry;
using Shelter.BLL.MasterEntry;
namespace Shelter.UI.MasterEntry
{
public partial class EmployeeCategoryUI : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListBox();
}
else
{
if (listEmployeeCategory.SelectedIndex != -1)
{
LoadDataIntoTextBox(Convert.ToInt32(listEmployeeCategory.SelectedValue));
}
}
}
private void LoadDataIntoTextBox(int val)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.ID = Convert.ToInt32(val);
DataTable EmpCategoryDt = new DataTable();
EmpCategoryDt = empCategoryBLL.RetrieveById(objEmployeeCategory);
txtEmpCategoryName.Text = EmpCategoryDt.Rows[0]["EmpCategoryName"].ToString();
}
private void LoadDataIntoListBox()
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
DataSet EmployeeCategoryDs = new DataSet();
EmployeeCategoryDs = empCategoryBLL.RetreiveFromTable();
DataTable EmployeeCategoryDt = EmployeeCategoryDs.Tables[0];
DataRow tempRow = null;
foreach (DataRow tempRow_Variable in EmployeeCategoryDt.Rows)
{
tempRow = tempRow_Variable;
string rowText = tempRow["EmpCategoryName"] + "(" + tempRow["ID"] + ")";
string rowValue = tempRow["ID"].ToString();
listEmployeeCategory.Items.Add(new ListItem(rowText, rowValue));
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.EmpCategoryName = txtEmpCategoryName.Text;
bool isSave = empCategoryBLL.SaveToTable(objEmployeeCategory);
if (isSave)
{
int id = empCategoryBLL.ReturnLastInsertedId();
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data saved successfully!";
string rowText = txtEmpCategoryName.Text + "(" +id.ToString()+ ")" ;
string rowValue = id.ToString();
listEmployeeCategory.Items.Add(new ListItem(rowText, rowValue));
txtEmpCategoryName.Text = "";
}
else
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data saving failed!";
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.EmpCategoryName = txtEmpCategoryName.Text;
objEmployeeCategory.ID = Convert.ToInt32(listEmployeeCategory.SelectedValue);
bool isEdit = empCategoryBLL.EditInTable(objEmployeeCategory);
if (isEdit)
{
int id = objEmployeeCategory.ID;
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data edited successfully!";
}
else
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data editing failed!";
}
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.ID = Convert.ToInt32(listEmployeeCategory.SelectedValue);
bool isDelete = empCategoryBLL.DeleteFromTable(objEmployeeCategory);
if (isDelete)
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data deleted successfully!";
listEmployeeCategory.Items.Remove(new ListItem(listEmployeeCategory.SelectedItem.Text, listEmployeeCategory.SelectedValue));
txtEmpCategoryName.Text = "";
}
else
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data deleting failed!";
}
}
}
}
}
The txtEmpCategoryName.Text is still containing the old value, so whenever I try to update, it only takes the old value and not the modified value in the textbox. It seems that the TextChanged event is not working. What is the fix to this problem?
You can use Entity frame in Visual studio;
right click on your solution - select new Add - then New Project - C# -Class Library give it a project name and Click Ok to add a new project to your existing project.
rename your class to a meaning name such as BusinessLogic and make it public.
right click on the newly added project and select add new item, on your popup windows select data on the right panel then select ADO.NET Entity Data Model rename your edmx to a meaningful name and click on add. default option and click on next, point to your SQL database by clicking on the new Connection.
select your store procedure for populating your listbox and updating the description and click on Finish.
CREATE PROCEDURE Proc_name AS BEGIN SET NOCOUNT ON;
SELECT ID,Description FROM Table_Name END
CREATE PROCEDURE [dbo].[UpdateEmpCategoryBLL]
#ID int, #Description varchar(50) AS BEGIN
SET NOCOUNT ON;
UPDATE Question1 SET Description = #Description WHERE ID = #ID
END
In your class Implement your methods for populating listbox and updating the description
public class Wrapper
{
public static List EmployeeCategory()
{
try
{
return new LOOKUPEntities().empCategoryBLL().ToList();
}
catch (Exception)
{
throw;
}
}
public static void UpdateEmpCategory(int id, string description)
{
try
{
using (LOOKUPEntities client = new LOOKUPEntities())
{
client.UpdateEmpCategoryBLL(id, description);
}
}
catch (Exception)
{
throw;
}
}
}
copy the connection string from you app.config to your web.config. Then add your class library to your references by right clicking on your references and select add reference, select solution and click on add. Add also System.Data,Entity and click ok.
now;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindListBox();
}
}
protected void BindListBox()
{
try
{
ListItem lstBox;
listEmployeeCategory.Items.Clear();
var query = Wrapper.EmployeeCategory();
foreach (var items in query)
{
lstBox = new ListItem(items.Description, items.ID.ToString());
listEmployeeCategory.Items.Add(lstBox);
}
}
catch(Exception ex)
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data loading failed "+ ex +" !";
}
}
protected void listEmployeeCategory_SelectedIndexChanged(object sender, EventArgs e)
{
lblMessage.Visible = false;
try
{
Session["ID"] = listEmployeeCategory.SelectedValue.ToString();
txtEmpCategoryName.Text = listEmployeeCategory.SelectedItem.ToString();
}
catch (Exception ex)
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Loading session data failed " + ex + " !";
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(Session["ID"].ToString());
Wrapper.UpdateEmpCategory(id, txtEmpCategoryName.Text.Trim());
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data edited successfully!";
BindListBox();
txtEmpCategoryName.Text = string.Empty;
}
catch
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data editing failed!";
}
}
done!

Handling Exception is ASP.NET Webforms using Custom validator

Im having a problem handing an exception in ASP.net WebForms(i'm a beginner)
i want to display the error in the webform using CustomValidator but with no luck, below is my code.
protected void dvEmployeeList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
GridViewRow rowSelect = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int rowindex = rowSelect.RowIndex;
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
try
{
int empID;
empID = int.TryParse(dvEmployeeList.DataKeys[rowindex].Value.ToString(), out empID) ? empID : 0;
oEmployeeBLL.DeleteEmployee(empID);
dvEmployeeList.DataSource = oEmployeeBLL.GetEmployeeList();
dvEmployeeList.DataBind();
}
catch (Exception ex)
{
var delConstrainsVal = new CustomValidator();
delConstrainsVal.IsValid = false;
delConstrainsVal.ErrorMessage = "Update failed: " + ex.Message;
delConstrainsVal.Text = delConstrainsVal.ErrorMessage;
Page.Validators.Add(delConstrainsVal);
}
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('User cancel!')", true);
}
}
it catch the exception but didnt display the message on the on the form.
Please guide me, thanks!
Validators are meant to validate user input, not to display server errors. You should consider using a simple <asp:Label>.
The reason why the error doesn't appear is probably because validation happens before the control is added.

Global variable empty in page load

I created a List as global variable in my page.
public static List<LinkButton> allControlsLinkButtonSalles = new List<LinkButton>();
And in a function called during Page_Load, I add some elements like this:
foreach (var childControl in allControlsLinkButton)
{
if (childControl.CssClass == "linkButtonSalleActive" || childControl.CssClass == "linkButtonSalle")
{
allControlsLinkButtonSalles.Add(childControl);
}
}
Just after that, when I do this:
foreach (LinkButton value in allControlsLinkButtonSalles)
{
literal2.Text += " <br /> Text " + value.Text;
}
And there are definitely 3 elements that show up.
However when I try to do this:
literal2.Text += " First element " + allControlsLinkButtonSalles.First().Text;
An error occurs. How come that is possible ?
Here is the message:
Description : An unhandled exception occurred during the execution of the current web request. Check the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The sequence contains no elements.
Source Error:
Ligne 605 : }
Ligne 606 :
Ligne 607 : literal2.Text += " First " + allControlsLinkButtonSalles.First().Text;
Ligne 608 :
Ligne 609 : //allControlsLinkButtonSalles[0].CssClass = "linkButtonSalleActive";
Stack Trace:
[InvalidOperationException: The sequence contains no elements.]
    System.Linq.Enumerable.First (IEnumerable `1 source) +269
test2MasterPage.Page_init() in c:\Users....\Documents\Visual Studio 2012\WebSites\test1\test2MasterPage.aspx.cs:607
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +9807957
System.Web.UI.Control.OnInit(EventArgs e) +92
System.Web.UI.Page.OnInit(EventArgs e) +12
System.Web.UI.Control.InitRecursive(Control namingContainer) +134
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +489
Here is the complete code:
public static List<DataTable> ListTable = new data().GetTable();
public static List<string> SallesList = new data().SallesListCreation(ListTable[0]);
//DataTable dt = new data().
public static int Load_Counter = 0;
List<Button> allControlsButton = new List<Button>();
public static List<LinkButton> allControlsLinkButtonSalles = new List<LinkButton>();
List<LinkButton> allControlsLinkButtonAffichages = new List<LinkButton>();
List<LinkButton> allControlsLinkButtonSemaine = new List<LinkButton>();
protected void Page_Load(object sender, EventArgs e)
{
literal2.Text += "<br /> counter : " + Load_Counter.ToString();
DateTime today = DateTime.Now;
string sToday = DateTime.Now.ToString("dd/MM/yyyy");
string finDate = today.AddDays(+6).ToString("dd/MM/yyyy");
literaltest.Text = "Semaine du " + sToday + " au " + finDate;
PlaceHolder1.Controls.Add(new LiteralControl("<br /><br /><br /> kyofu<br /><br />"));
foreach (string sallesel in SallesList)
{
PlaceHolder1.Controls.Add(CreateLinkButton(sallesel + "lkbtn", sallesel, "linkButtonSalle"));
}
Page_init();
}
protected void Page_init()
{
List<LinkButton> allControlsLinkButton = new List<LinkButton>();
GetControlList<LinkButton>(Page.Controls, allControlsLinkButton);
DateTime today = DateTime.Now;
string sToday = DateTime.Now.ToString("dd/MM/yyyy");
// the list of controllers is filled
foreach (var childControl in allControlsLinkButton)
{
if (childControl.CssClass == "linkButtonSalleActive" || childControl.CssClass == "linkButtonSalle")
{
allControlsLinkButtonSalles.Add(childControl);
literal2.Text += " allControlsLinkButtonSalles " + childControl.Text;
}
if (childControl.CssClass == "linkButtonAffichage" || childControl.CssClass == "linkButtonAffichageActive")
{
allControlsLinkButtonAffichages.Add(childControl);
}
if (childControl.CssClass == "linkButtonSemaine" || childControl.CssClass == "linkButtonSemaineActive")
{
allControlsLinkButtonSemaine.Add(childControl);
SemaineSync(childControl);
}
}
literal2.Text += " taille " + allControlsLinkButtonSalles.Count();
//literal2.Text += " Text " + allControlsLinkButtonSalles[1].Text;
foreach (LinkButton value in allControlsLinkButtonSalles)
{
literal2.Text += " <br /> Text " + value.Text;
}
literal2.Text += " First " + allControlsLinkButtonSalles.First().Text;
ListFilmsBySalle(SallesList[0]);
}
private void GetControlList<T>(ControlCollection controlCollection, List<T> resultCollection)
where T : Control
{
foreach (Control control in controlCollection)
{
//if (control.GetType() == typeof(T))
if (control is T) // This is cleaner
resultCollection.Add((T)control);
if (control.HasControls())
GetControlList(control.Controls, resultCollection);
}
}
You don't use the static key word properly.
Static variable, is belong to the class itself and don't belong to the current instanace.
Try to use:
public List<LinkButton> allControlsLinkButtonSalles
{
get
{
if(Session["allControlsLinkButtonSalles"] == null)
Session["allControlsLinkButtonSalles"] = new List<LinkButton>();
return (List<LinkButton>) Session["allControlsLinkButtonSalles"];
}
set
{
Session["allControlsLinkButtonSalles"] = value;
}
}
Another isue to take look for is that actually something enter to the list, try to debug it.
Create a Static Class and Create some Attributes and Set your Values to those
Attributes their Whenever you Want you can take it from their if Data has any change
Again set those attributes so that you will get your data from the Class
Public static class Helper
{
public string SOMEPROPERTY
{
get;
set;
}
.
.
.
public List<LinkButton> SOMEPROPERTY
{
get;
set;
}
}
Got the same error as you at first, realised I had no controls in the List you are looking at because I had no LinkButton s with either of the classes that were being searched for with regard to the allControlsLinkButtonSalles list.
I added the CssClass of ""linkButtonSalleActive"" on all of the LinkButton s on my page and I got no debug error.
Add in a check that the list is actually empty for the times where there are no Salle specific links, and you shouldn't have any issues.
Here is the sample code I worked with:
Default.aspx
<!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">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" id="literal2" /> <br />
<asp:Label runat="server" id="literaltest" /> <br />
<asp:LinkButton runat="server" CssClass="linkButtonSalleActive" text="1"/>
<asp:LinkButton runat="server" CssClass="linkButtonSalleActive" text="2"/>
<asp:LinkButton runat="server" CssClass="linkButtonSalleActive" text="3"/>
<asp:LinkButton runat="server" CssClass="linkButtonSalleActive" text="4"/>
</div>
</form>
</body>
</html>
Default.aspx.cs (modified version of you complete code)
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
//DataTable dt = new data().
public static int Load_Counter = 0;
List<Button> allControlsButton = new List<Button>();
public static List<LinkButton> allControlsLinkButtonSalles = new List<LinkButton>();
List<LinkButton> allControlsLinkButtonAffichages = new List<LinkButton>();
List<LinkButton> allControlsLinkButtonSemaine = new List<LinkButton>();
protected void Page_Load(object sender, EventArgs e)
{
literal2.Text += "<br /> counter : " + Load_Counter.ToString();
DateTime today = DateTime.Now;
string sToday = DateTime.Now.ToString("dd/MM/yyyy");
string finDate = today.AddDays(+6).ToString("dd/MM/yyyy");
literaltest.Text = "Semaine du " + sToday + " au " + finDate;
//PlaceHolder1.Controls.Add(new LiteralControl("<br /><br /><br /> kyofu<br /><br />"));
//foreach (string sallesel in SallesList)
//{
// PlaceHolder1.Controls.Add(CreateLinkButton(sallesel + "lkbtn", sallesel, "linkButtonSalle"));
//}
Page_init();
}
protected void Page_init()
{
List<LinkButton> allControlsLinkButton = new List<LinkButton>();
GetControlList<LinkButton>(Page.Controls, allControlsLinkButton);
DateTime today = DateTime.Now;
string sToday = DateTime.Now.ToString("dd/MM/yyyy");
// the list of controllers is filled
foreach (var childControl in allControlsLinkButton)
{
if (childControl.CssClass == "linkButtonSalleActive" || childControl.CssClass == "linkButtonSalle")
{
allControlsLinkButtonSalles.Add(childControl);
literal2.Text += " allControlsLinkButtonSalles " + childControl.Text;
}
if (childControl.CssClass == "linkButtonAffichage" || childControl.CssClass == "linkButtonAffichageActive")
{
allControlsLinkButtonAffichages.Add(childControl);
}
if (childControl.CssClass == "linkButtonSemaine" || childControl.CssClass == "linkButtonSemaineActive")
{
allControlsLinkButtonSemaine.Add(childControl);
//SemaineSync(childControl);
}
}
literal2.Text += " taille " + allControlsLinkButtonSalles.Count();
//literal2.Text += " Text " + allControlsLinkButtonSalles[1].Text;
foreach (LinkButton value in allControlsLinkButtonSalles)
{
literal2.Text += " <br /> Text " + value.Text;
}
/*
* CHANGES HERE
*/
literal2.Text += allControlsLinkButtonSalles.Count > 0 ?
" First " + allControlsLinkButtonSalles.First().Text :
String.Empty;
//ListFilmsBySalle(SallesList[0]);
}
private void GetControlList<T>(ControlCollection controlCollection, List<T> resultCollection)
where T : Control
{
foreach (Control control in controlCollection)
{
//if (control.GetType() == typeof(T))
if (control is T) // This is cleaner
resultCollection.Add((T)control);
if (control.HasControls())
GetControlList(control.Controls, resultCollection);
}
}
}
}
As per your code value to the list allControlsLinkButtonSalles is added only if childControl.CssClass == "linkButtonSalleActive",
I am sure there in no value being added, check what you are getting for literal2.Text at:-
literal2.Text += " taille "+ allControlsLinkButtonSalles .Count();
Having said that you should not be using static variables or properties on page unless you have a valid reason to do so.

metabuilder checked listbox selected index changed not working on server

am using meta builder checked listbox and their selected index changed working fine in local.but not working on server side. please help me to fix this error. My partial code is here..
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (ListBox1.Items.Count > 0)
{
for (int i = 0; i <= ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected == true)
{
lblempid.Text = Convert.ToString(ListBox1.Items[i].Text.Substring(0, 8));
lblempname.Text = Convert.ToString(ListBox1.Items[i].Text.Substring(9));
DataSet5TableAdapters.sp_GetallpayperiodTableAdapter TA = new DataSet5TableAdapters.sp_GetallpayperiodTableAdapter();
DataSet5.sp_GetallpayperiodDataTable DS = TA.GetData();
if (DS.Rows.Count > 0)
{
fromdate = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldstartdate"]);
todate = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldtodate"]);
status = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldstatus"]);
if (status == "OPEN")
{
lblfromdate.Text = Convert.ToString(Convert.ToDateTime(fromdate).ToShortDateString());
lbltodate.Text = Convert.ToString(Convert.ToDateTime(todate).ToShortDateString());
}
}
}
}
}
}
catch (Exception e1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "onload", "<script language='javascript'>alert('" + e1.Message + "');</script>", false);
}
Design code:
<%# Register Assembly="MetaBuilders.WebControls" Namespace="MetaBuilders.WebControls"
TagPrefix="mb" %>
<mb:CheckedListBox ID="ListBox1" runat="server" CssClass="textbox" Width="250px"
Height="515px" AutoPostBack="True" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</mb:CheckedListBox>
please check if the auto post back is true in your aspx code:
Example:
<asp:DropDownList ID="ddlForecastOption" runat="server"
onselectedindexchanged="ddlForecastOption_SelectedIndexChanged"
AutoPostBack="true">

Categories