DataTable Retrieves another DataTable Information? - asp.net

I Have an Exception in my Live Application..DataTable Retrives another DataTable information..
if (HttpContext.Current.User != null)
{
if (Session["username"] != null)
{
string pageName = Page.Page.AppRelativeVirtualPath.Substring(Page.Page.AppRelativeVirtualPath.LastIndexOf('/') + 1);
DataTable dtFeatures2 = new DataTable();
dtFeatures2.Clear();
objMatermenuPL.usertype = Session["UserType"].ToString();
dtFeatures2 = objMastermenuBAL.GetMastermenu(objMatermenuPL);
DataView dt = new DataView(dtFeatures2);
dt.Sort = "fld_feature ASC";
if (dtFeatures2 != null)
{
foreach (Control control in leftpanel.Controls)
{
Type ty = control.GetType();
if (ty.Name.ToUpper() == "HTMLANCHOR")
{
int i = dt.Find(control.ID.Substring(3));
if (i < 0 && control.ID.Contains("lnk"))
control.Visible = false;
if (control.ID.Contains("lnk") && control.ID.Substring(3) + ".aspx" == pageName)
{
HtmlAnchor a = (HtmlAnchor)control;
a.Attributes.Add("class", "active");
}
}
}
}
}
}
else
{
Response.Redirect("~/Login.aspx");
}
This code we use All most all master pages...If an exception Raise,then it comes directly
this line..
dtFeatures2 = objMastermenuBAL.GetMastermenu(objMatermenuPL);
Message like : Cannot find column fld_feature.
"dtFeatures2" is Filled With Before Opened Page DataTable Information...
This exception gone after some..It's Working Fine 100%....Some times only shows these exception...What happend Here........

Related

Retrieving images from Database into ArrayList and Displaying it one by one from ArrayList in ASP.NET

using following code i store images into ArrayList.
public ArrayList getImagesToArray(string qry)
{
ArrayList arr;
if (myConn.State == System.Data.ConnectionState.Closed)
myConn.Open();
if (myDR != null)
myDR.Close();
myComm = new SqlCommand(qry, myConn);
using (myComm)
{
arr = new ArrayList();
myDR = myComm.ExecuteReader();
while (myDR.Read())
{
arr.Add((byte[])myDR[0]);
}
return arr;
}
}
Now i retreive images to an ArrayList using Following Code
ArrayList arrImgs_Main = Q.getImagesToArray("Select FieldImg from InfoTagQA I INNER JOIN PensionScannedDocs P on p.ScanImageID=i.ScanImageID Where P.PersonalNumber='" + hid_PersonalNo.Value + "'");
Now I display image one by one from arrayList to ImageUrl by clicking Next and Previous button
protected void lnk_BackImage_Click(object sender, EventArgs e)
{
try
{
if (arrImgs_Main.Count > 0)
{
if (i > 0)
{
i--;
img_mainImage.ImageUrl = "data:image;base64," + Convert.ToBase64String((byte[])arrImgs_Main[i]);
lab_TotalRecords.Text = "(" + (i + 1) + "/" + arrImgs_Main.Count + ")";
if (i == 0)
{
lnk_ForwardImage.Visible = true;
lnk_BackImage.Visible = false;
}
}
}
}
catch(Exception ee)
{
ShowErrorMsg(ee.Message);
}
}
**All above code works fine and quick on my local machine, but after deployment on server , it take much time in displaying image one by one from array.
Am i doing doing right in above code or going on wrong way. Please guide me **

Custom GridView Server Control DataBind causes duplicate control ID's error

OK. I've long used this site as a reference, but I've now hit a wall of my own.
I am creating a custom server control which inherits from the System.Web.UI.WebControls.GridView class. It's purpose is simply to display a grid with a very defined format. It binds and loads the data fine, but trying to activate any of the paging throws an exception saying "Multiple controls with the same ID 'lblHdrText_2' were found. FindControl requires that controls have unique IDs.".
I could just throw the event out to the user and let them do the paging, but one of the goals was to have this control be able to handle its own paging, just like the GridView control already does.
I'm having the same problem for sorting and altering the page size as well. Basically anytime I call "DataBind" within the control after it has already been rendered.
Here's the code to handle those events:
protected void OnFirstPageClicked(EventArgs e)
{
if (this.FirstPageClicked != null)
this.FirstPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(0);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex = 0;
this.RefreshData();
this.OnPageIndexChanged(e);
}
protected void OnLastPageClicked(EventArgs e)
{
if (this.LastPageClicked != null)
this.LastPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(this.PageCount - 1);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex = this.PageCount - 1;
this.RefreshData();
this.OnPageIndexChanged(e);
}
protected void OnPreviousPageClicked(EventArgs e)
{
if (this.PageIndex > 0)
{
if (this.PreviousPageClicked != null)
this.PreviousPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(this.PageIndex++);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex--;
this.RefreshData();
this.OnPageIndexChanged(e);
}
}
protected void OnNextPageClicked(EventArgs e)
{
if (this.PageIndex < this.PageCount - 1)
{
if (this.NextPageClicked != null)
this.NextPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(this.PageIndex++);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex++;
this.RefreshData();
this.OnPageIndexChanged(e);
}
}
protected void OnPageSizeChanged(EventArgs e)
{
this.RefreshData();
if (this.PageSizeChanged != null)
this.PageSizeChanged.Invoke(this, e);
}
protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
}
private void RefreshData()
{
this.DataBind();
}
private void imgPg_OnCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "FirstPage":
this.OnFirstPageClicked(EventArgs.Empty);
break;
case "LastPage":
this.OnLastPageClicked(EventArgs.Empty);
break;
case "PrevPage":
this.OnPreviousPageClicked(EventArgs.Empty);
break;
case "NextPage":
this.OnNextPageClicked(EventArgs.Empty);
break;
}
}
private void drpPageSz_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList drpPgSz = (sender as DropDownList);
if (drpPgSz != null)
{
this.PageSize = int.Parse(drpPgSz.SelectedValue);
this.OnPageSizeChanged(e);
}
else
throw new Exception("Unable to determine page size: cannot cast sender as DropDownList.");
}
The actual event handlers are at the bottom. The "RefreshData" method is just there because I was experimenting with different ways of clearing the controls from the grid before I called "DataBind". So far, everything I've tried results in the entire grid not rendering after postback.
I am doing quite a bit with the Render and CreateChildControls, but the header generation itself is completely internal to the System.Web.UI.WebControls.GridView control. Here's my rendering code, if it helps at all:
protected override void OnPreRender(EventArgs e)
{
Control link = this.Page.Header.FindControl("CustomGridViewCss");
if (link == null)
{
System.Web.UI.HtmlControls.HtmlLink newLink = new System.Web.UI.HtmlControls.HtmlLink();
newLink.ID = "CustomGridViewCss";
newLink.Attributes.Add("href", this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.style.CustomGridView.css"));
newLink.Attributes.Add("type", "text/css");
newLink.Attributes.Add("rel", "stylesheet");
this.Page.Header.Controls.Add(newLink);
}
base.OnPreRender(e);
this.EnsureChildControls();
}
protected override void Render(HtmlTextWriter writer)
{
if (this._imgFPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgFPg.UniqueID);
if (this._imgPrevPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgPrevPg.UniqueID);
if (this._imgNextPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgNextPg.UniqueID);
if (this._imgLastPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgLastPg.UniqueID);
if (this._drpPageSz != null)
this.Page.ClientScript.RegisterForEventValidation(this._drpPageSz.UniqueID);
if (this.HeaderRow != null)
for (int i = 1; i < this.HeaderRow.Cells.Count - 2; i++)
if (i < this.Columns.Count && this.Columns[i] is SortableField && ((this.Columns[i] as SortableField).ShowSort))
{
ImageButton img = (this.HeaderRow.Cells[i].FindControl("imgSort_" + i.ToString()) as ImageButton);
if (img != null)
this.Page.ClientScript.RegisterForEventValidation(img.UniqueID);
}
base.Render(writer);
}
protected override Table CreateChildTable()
{
this.PagerSettings.Visible = false;
this.GridLines = GridLines.None;
Table tbl = base.CreateChildTable();
tbl.Attributes.Add("name", this.UniqueID);
return tbl;
}
protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
{
this.GridLines = GridLines.None;
int iCount = base.CreateChildControls(dataSource, dataBinding);
// Modify footer row
System.Web.UI.WebControls.GridViewRow ftr = this.FooterRow;
// NOTE: We're modifying the footer first, because we're looking at the
// total number of rows in the header for the ColSpan property we
// use in the footer and we want the row count *before* we modify
// the header.
ftr.Cells.Clear();
this.BuildFooter(this.FooterRow);
// Modify Header Row
System.Web.UI.WebControls.GridViewRow hdr = this.HeaderRow;
hdr.CssClass = "GridViewHeader";
for (int c = 0; c < hdr.Cells.Count; c++)
{
hdr.Cells[c].CssClass = "GridViewHeaderTC";
if (c > 0)
hdr.Cells[c].Style.Add("border-left", "solid 1px #ccccd3");
if (c < this.Columns.Count && this.Columns[c] is SortableField && ((this.Columns[c] as SortableField).ShowSort))
{
hdr.Cells[c].Controls.Clear();
Label lblHdrText = new Label();
lblHdrText.ID = "lblHdrText_" + c.ToString();
lblHdrText.Text = hdr.Cells[c].Text;
hdr.Cells[c].Controls.Add(lblHdrText);
ImageButton imgSort = new ImageButton();
imgSort.ID = "imgSort_" + c.ToString();
imgSort.CssClass = "GridViewHeaderSort";
imgSort.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.Sort.png");
imgSort.AlternateText = "";
imgSort.CommandArgument = (this.Columns[c] as BoundField).DataField;
imgSort.CommandName = "Sort";
imgSort.Command += new CommandEventHandler(this.imgSort_OnCommand);
hdr.Cells[c].Controls.Add(imgSort);
imgSort.Attributes.Add("name", imgSort.UniqueID);
}
}
TableCell tdTL = new TableCell();
tdTL.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdTL.CssClass = "GridViewHeaderTL";
hdr.Cells.AddAt(0, tdTL);
TableCell tdTR = new TableCell();
tdTR.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdTR.Style.Add("border-left", "1px solid #ccccd3;");
tdTR.CssClass = "GridViewHeaderTR";
hdr.Cells.Add(tdTR);
// Modify individual rows
for (int i = 0; i < this.Rows.Count; i++)
{
System.Web.UI.WebControls.GridViewRow tr = this.Rows[i];
tr.CssClass = (i % 2 == 0) ? "GridViewLineAlt" : "GridViewLine";
for (int c = 0; c < tr.Cells.Count - 1; c++)
tr.Cells[c].Style.Add("border-right", "solid 1px #ccccd3");
TableCell tdL = new TableCell();
tdL.CssClass = "GridViewLineLeft";
tr.Cells.AddAt(0, tdL);
TableCell tdR = new TableCell();
tdR.CssClass = "GridViewLineRight";
tr.Cells.Add(tdR);
}
return iCount;
}
protected void BuildFooter(GridViewRow tr)
{
TableCell tdBL = new TableCell();
tdBL.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdBL.CssClass = "GridViewFooterBL";
tr.Cells.Add(tdBL);
int colCount = this.HeaderRow.Cells.Count;
TableCell td = new TableCell();
td.ID = "tdFooterControls";
td.CssClass = "GridViewFooterBC";
td.ColumnSpan = colCount;
this._spanPgBtns = new Label();
this._spanPgBtns.ID = "spanPgButtons";
this._spanPgBtns.Style.Add("float", "right");
this._spanPgBtns.Style.Add("margin-right", "20px");
this._imgFPg = new ImageButton();
this._imgFPg.ID = "imgFPg";
this._imgFPg.CssClass = "FirstPg";
this._imgFPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.FstPg.png");
this._imgFPg.ImageAlign = ImageAlign.Middle;
this._imgFPg.CommandName = "FirstPage";
this._imgFPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgFPg);
this._imgPrevPg = new ImageButton();
this._imgPrevPg.ID = "imgPrevPg";
this._imgPrevPg.CssClass = "PrevPg";
this._imgPrevPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.PrevPg.png");
this._imgPrevPg.ImageAlign = ImageAlign.Middle;
this._imgPrevPg.CommandName = "PrevPage";
this._imgPrevPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgPrevPg);
Label lblPageNum = new Label();
lblPageNum.ID = "lblPageNum";
lblPageNum.Width = new Unit("50px");
lblPageNum.Text = string.Format("{0} / {1}", this.PageIndex + 1, this.PageCount);
lblPageNum.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
this._spanPgBtns.Controls.Add(lblPageNum);
this._imgNextPg = new ImageButton();
this._imgNextPg.ID = "imgNextPg";
this._imgNextPg.CssClass = "NextPg";
this._imgNextPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.NextPg.png");
this._imgNextPg.ImageAlign = ImageAlign.Middle;
this._imgNextPg.CommandName = "NextPage";
this._imgNextPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgNextPg);
this._imgLastPg = new ImageButton();
this._imgLastPg.ID = "imgLastPg";
this._imgLastPg.CssClass = "LastPg";
this._imgLastPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.LstPg.png");
this._imgLastPg.ImageAlign = ImageAlign.Middle;
this._imgLastPg.CommandName = "LastPage";
this._imgLastPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgLastPg);
td.Controls.Add(this._spanPgBtns);
Label spanPageSz = new Label();
spanPageSz.ID = "spanPageSz";
spanPageSz.Style.Add("margin-left", "20px");
this._drpPageSz = new DropDownList();
this._drpPageSz.ID = "drpPageSzSelect";
this._drpPageSz.AutoPostBack = true;
this._drpPageSz.SelectedIndexChanged += new EventHandler(drpPageSz_SelectedIndexChanged);
this._drpPageSz.Items.Add(new ListItem("10", "10"));
this._drpPageSz.Items.Add(new ListItem("25", "25"));
this._drpPageSz.Items.Add(new ListItem("50", "50"));
this._drpPageSz.Items.Add(new ListItem("100", "100"));
spanPageSz.Controls.Add(this._drpPageSz);
td.Controls.Add(spanPageSz);
Label lblRecVis = new Label();
lblRecVis.ID = "lblRecordsCount";
lblRecVis.Style.Add("margin-left", "20px");
lblRecVis.Text = string.Format("Displaying {0} of {1} records.", Math.Min(this.PageSize, this.Rows.Count - (this.PageIndex * this.PageSize)), this.Rows.Count);
lblRecVis.Text = "Total Record Display";
td.Controls.Add(lblRecVis);
tr.Cells.Add(td);
TableCell tdBR = new TableCell();
tdBR.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdBR.CssClass = "GridViewFooterBR";
tr.Cells.Add(tdBR);
this._imgFPg.Attributes.Add("name", this._imgFPg.UniqueID);
this._imgPrevPg.Attributes.Add("name", this._imgPrevPg.UniqueID);
this._imgNextPg.Attributes.Add("name", this._imgNextPg.UniqueID);
this._imgLastPg.Attributes.Add("name", this._imgLastPg.UniqueID);
this._drpPageSz.Attributes.Add("name", this._drpPageSz.UniqueID);
}
I'm only about 6/10 on custom server controls, so I'm sure there's at least one thing I'm doing wrong here :)
Thanks in advance for any help!
OK. I finally found a reference and answered my own question. The trick is in overriding the "PerformSelect" method and handling DataSource vs DataSourceID there.
Details on how to do this can be found on this MSDN page:
http://msdn.microsoft.com/en-us/library/ms366539(v=vs.90).aspx
Look for the section titled "Initiate Data Retrieval" a little over half-way down.

how to check items in checkboxlist?

i have a checkboxlist that i want to check some of it's items,
items that i wanna check store in database, i'm selecting them from database and in a loop i wrote thees but just last item selected :(( :
var selectedRoles = (from r in DataContext.Context.Core_PagesPermission
where r.PageName.Contains(pageName) select r)
.FirstOrDefault();
if(selectedRoles != null)
{
string roles = selectedRoles.Roles;
string[] role = roles.Split(',');
int countTags = role.Count();
foreach (string word in role)
{
CheckBoxList1.SelectedValue = word;
Response.Write(word + "<br/>");
countTags -= 1;
}
}
this worked :
var selectedRoles = (from r in DataContext.Context.Core_PagesPermission where r.PageName.Contains(pageName) select r)
.FirstOrDefault();
dsRoles.DataBind();
CheckBoxList1.DataBind();
if(selectedRoles != null)
{
string roles = selectedRoles.Roles;
string[] role = roles.Split(',');
foreach (string word in role)
{
try
{
CheckBoxList1.Items.FindByValue(word).Selected = true;
}
catch (Exception exp)
{
lbError.Text= exp.ToString();
}
You will want to select the individual items:
CheckBoxList1.Items.FindByText(word).Selected = true;
or
CheckBoxList1.Items.FindByValue(word).Selected = true;
However, if the checkboxlist doesn't have the text/value you are looking for, it will throw an error.
datatable method checkboxlist
for (int i = 0; i < dt.Rows.Count; i++)
{
chkCategories.Items.FindByValue(dt.Rows[i]["CategoryID"].ToString()).Selected = true;
}

In ASP.net ".aspx" pages placed in subfolder can not access when in click on that specific page in menu

i am using jquery menu on master page. menu containt bind at runtime depend upon user right.
in my project ".aspx" pages placed in root folder as well as subfolder ..when i click on page name on menu it redirect me to that specific page which is located in root part of my project.
but i can't redirect to pages in subfolder..
target page name is defined in database. on clicking it pick up target url from datatbse and redirect to page.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using AjaxPro;
public partial class Reports_fleet : System.Web.UI.MasterPage
{
Jetfleet_Framework.clsDataAcess objData = new Jetfleet_Framework.clsDataAcess();
DataSet dsMenu = new DataSet();
HttpBrowserCapabilities objbrowser;
protected void Page_Load(object sender, EventArgs e)
{
objbrowser = Request.Browser;
if (objbrowser.Browser == "AppleMAC-Safari")
{
loctbl.Style.Add("margin-top", "30px");
loctbl.Style.Add("margin-left", "-30px");
sumnu.Style.Add("margin-top", "2px");
}
if (objbrowser.Browser == "Firefox")
{
loctbl.Style.Add("margin-top", "30px");
loctbl.Style.Add("margin-left", "-50px");
sumnu.Style.Add("margin-top", "2px");
}
lbl.Text = Session["ServiceLocName"].ToString();
hdnRelease.Value = Session["Release"].ToString();
hdnCloseWindow.Value = Session["userId"].ToString();
Utility.RegisterTypeForAjax(typeof(Reports_fleet));
Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
Response.Expires = -1500;
Response.Cache.SetNoStore();
Response.CacheControl = "no-cache";
if (Session["userId"] == null)
{
Response.Redirect("LogIn.aspx");
}
//name.InnerHtml = Session["userFullName"].ToString();
BuildNavigationMenu();
name.InnerHtml = Session["userFullName"].ToString();
if (!this.IsPostBack)
{
if (Session["Release"] == "True")
{
string spRelease = "usp_ins_upd_task_assign;3";
Object[] paramRelease = new Object[1];
paramRelease[0] = (Object)Session["userId"].ToString();
objData.ExecuteNonQuery(spRelease, paramRelease);
}
else
{
Session["Release"] = "True";
}
}
}
private void BuildNavigationMenu()
{
//Creates html UL element for menu.
string uname = "", pass = "", location = "";
Session["bchk"] = "True";
int userId = System.Int32.Parse(Session["userId"].ToString());
int roleId = System.Int32.Parse(Session["userRole"].ToString());
try
{
if (Session["navigation_menu_dataset"] != null)
{
dsMenu = (DataSet)Session["navigation_menu_dataset"];
}
else
{
dsMenu = GetNavigationMenu(userId, roleId);
Session["navigation_menu_dataset"] = dsMenu;
}
uname = Session["userName"].ToString();
pass = Session["password"].ToString();
location = Session["loction"].ToString();
Session["username"] = uname;
Session["password"] = pass;
Session["Location"] = location;
int mnuCount, totalMenus;
totalMenus = System.Int32.Parse(dsMenu.Tables[1].Rows[0]["total_menus"].ToString());
HtmlGenericControl divMenu = new HtmlGenericControl("div");
divMenu.Attributes["id"] = "menu";
HtmlGenericControl ulMenu = new HtmlGenericControl("ul");
ulMenu.Attributes["class"] = "menu";
for (mnuCount = 1; mnuCount <= totalMenus; mnuCount++)
{
HtmlGenericControl liMain = new HtmlGenericControl("li");
if (mnuCount == totalMenus)
{
liMain.Attributes["class"] = "last";
}
else
{
liMain.Attributes["class"] = "parent";
}
HtmlGenericControl aMain = new HtmlGenericControl("a");
aMain.Attributes["href"] = "#";
HtmlGenericControl spMenu = new HtmlGenericControl("span");
DataRow[] drMenu = null;
drMenu = dsMenu.Tables[0].Select("parent_menu_id = " + mnuCount);
if (drMenu.Length != 0)
{
spMenu.InnerHtml = drMenu[0]["parent_menu_name"].ToString();//Masters
aMain.Controls.Add(spMenu);
liMain.Controls.Add(aMain);
HtmlGenericControl divMenu1 = new HtmlGenericControl("div");
HtmlGenericControl ulMenu1 = new HtmlGenericControl("ul");
int subMenuStepTo = 0;
for (int rowcnt = 0; rowcnt < drMenu.Length; rowcnt++)
{
if (drMenu[rowcnt]["is_folder"].ToString().ToLower() == "false")
{
//If no submenus are there.
HtmlGenericControl liMain1 = new HtmlGenericControl("li");//Booking Upload
HtmlGenericControl aMain1 = new HtmlGenericControl("a");
aMain1.Attributes["href"] = drMenu[rowcnt]["target_url"].ToString();
HtmlGenericControl spMenu1 = new HtmlGenericControl("span");
spMenu1.InnerHtml = " " + drMenu[rowcnt]["display_text"].ToString();
aMain1.Controls.Add(spMenu1);
liMain1.Controls.Add(aMain1);
ulMenu1.Controls.Add(liMain1);
}
if (drMenu[rowcnt]["is_folder"].ToString().ToLower() == "true")
{
//submenus are there
DataRow[] drSubMenu;
HtmlGenericControl liMain1 = new HtmlGenericControl("li");//Customer
liMain1.Attributes["class"] = "parent";
HtmlGenericControl aMain1 = new HtmlGenericControl("a");
aMain1.Attributes["href"] = "#";
HtmlGenericControl spMenu1 = new HtmlGenericControl("span");
subMenuStepTo = rowcnt;
spMenu1.InnerHtml = " " + drMenu[subMenuStepTo]["display_name"].ToString(); //subMenuStepTo
aMain1.Controls.Add(spMenu1);
liMain1.Controls.Add(aMain1);
drSubMenu = dsMenu.Tables[0].Select("display_name = '" + drMenu[subMenuStepTo]["display_name"].ToString() + "' AND parent_menu_id = " + mnuCount);//subMenuStepTo
HtmlGenericControl divMenu2 = new HtmlGenericControl("div");
HtmlGenericControl ulMenu2 = new HtmlGenericControl("ul");
for (int rowcnt1 = 0; rowcnt1 < drSubMenu.Length; rowcnt1++)
{
if (mnuCount == 3)
{
AppRelativeTemplateSourceDirectory = "~/Reports";
}
HtmlGenericControl liMain2 = new HtmlGenericControl("li");//Corporate
HtmlGenericControl aMain2 = new HtmlGenericControl("a");
aMain2.Attributes["href"] = drSubMenu[rowcnt1]["target_url"].ToString();
HtmlGenericControl spMenu2 = new HtmlGenericControl("span");
spMenu2.InnerHtml = " " + drSubMenu[rowcnt1]["display_text"].ToString();
aMain2.Controls.Add(spMenu2);
liMain2.Controls.Add(aMain2);
ulMenu2.Controls.Add(liMain2);
}
subMenuStepTo = subMenuStepTo + (drSubMenu.Length - 1);
divMenu2.Controls.Add(ulMenu2);
liMain1.Controls.Add(divMenu2);
ulMenu1.Controls.Add(liMain1);
}
if (drMenu[rowcnt]["is_folder"].ToString().ToLower() != "false")
{
rowcnt = subMenuStepTo;
}
}
divMenu1.Controls.Add(ulMenu1);
liMain.Controls.Add(divMenu1);
}
ulMenu.Controls.Add(liMain);
}
divMenu.Controls.Add(ulMenu);
mnuContainer.Controls.Add(divMenu);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
dsMenu.Dispose();
}
}
private DataSet GetNavigationMenu(int userId, int roleId)
{
//Gets menu items based on user id.
try
{
string spMenu = "usp_get_navigation_menu;2";
Object[] paramsMenu = new object[2];
paramsMenu[0] = (Object)userId;
paramsMenu[1] = (Object)roleId;
objData.FillDataset(spMenu, dsMenu, null, paramsMenu);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
objData.Dispose();
}
return dsMenu;
}
[AjaxPro.AjaxMethod]
public void CloseWindow(int userid, string release)
{
if (release == "False")
{
string spRelease = "usp_ins_upd_task_assign;3";
Object[] paramRelease = new Object[1];
paramRelease[0] = (Object)userid;
objData.ExecuteNonQuery(spRelease, paramRelease);
}
}
}
this is my code to bind menu at runtime ..i can't access subfolder pages ..i tried to define subfolder path in database ..it works at first time but when i click on other menu
page which is in root then in address bar ".aspx" page name attach with subfolder name
...so page could not found
please help me .........
use "< base href='http://localhost/testapp/' />" in master page, it will help you..

Dynamically add checkboxlist into placeholder and get the checked value of the checkboxlist

I am creating an admin Page, in which checkboxlist(User list from DB)is to be created dynamically and its the checked users value is retrieved.
There are different types of users, so it is distinguised groupwise.
Now first a panel is defined, the checkboxlist is created dynamically and placed inside the panel, then the panel is placed inside a Placeholder.
What Iam doing here is placing the checkboxlist inside the panel, then the panel inside the placeholder. So the values of the Checkboxlist is not retrieved, due to the panel it doesnt get the checkboxlist and it doesn't loop through the Checkboxlist.
What I have done is.
private void AddControl(string pUserGrp, int pUserGrp_Id, int pName)
{
CheckBoxList chkList = new CheckBoxList();
CheckBox chk = new CheckBox();
User us = new User();
us.OrderBy = "Order By User_Name";
us.WhereClause = "Where UserRole_Id = " + pUserGrp_Id ;
chkList.ID = "ChkUser" + pName ;
chkList.AutoPostBack = true;
chkList.Attributes.Add("onClick", "getVal(ChkUser" + pName + ");");
chkList.RepeatColumns = 6;
chkList.DataSource = us.GetUserDS();
chkList.DataTextField = "User_Name";
chkList.DataValueField = "User_Id";
chkList.DataBind();
chkList.Attributes.Add("onClick", "getVal(this);");
Panel pUser = new Panel();
if (pUserGrp != "")
{
pUser.GroupingText = pUserGrp ;
chk.Text = pUserGrp;
}
else
{
pUser.GroupingText = "Non Assigned Group";
chk.Text = "Non Assigned group";
}
pUser.Controls.Add(chk);
pUser.Controls.Add(chkList);
Place.Controls.Add(pUser);
}
private void setChecked(int pPageGroupId)
{
ArrayList arr = new ArrayList();
PageMaster obj = new PageMaster();
obj.WhereClause = " Where PageGroup_Id = " + pPageGroupId;
arr = obj.GetPageGroupUserRights(null);
CheckBoxList chkList = (CheckBoxList)Place.FindControl("ChkUser");
if (chkList != null)
{
for (int i = 0; i < chkList.Items.Count; i++)
{
if (arr.Count > 0)
{
int ii = 0;
while (ii < arr.Count)
{
PageMaster oCand = (PageMaster)arr[ii];
if (oCand.User_Name == chkList.Items[i].Text)
{
if (!chkList.Items[i].Selected)
{
chkList.Items[i].Selected = true;
}
}
ii++;
oCand = null;
}
}
}
}
}
public string GetListCheckBoxText()
{
StringBuilder sbtext = new StringBuilder();
foreach (Control c in Place.Controls)
{
if (c.GetType().Name == "CheckBoxList")
{
CheckBoxList cbx1 = (CheckBoxList)c;
foreach (ListItem li in cbx1.Items)
{
if (li.Selected == true)
{
sbtext.Append(",");
sbtext.Append(li.Value);
}
else
{
sbtext.Append(li.Value);
}
}
}
}
return sbtext.ToString(); }
It doesnt get through the Checkboxlist control in the setChecked(), also doesnt loop through the GetListCheckBoxTest().
Anyone can plz help me.
Regards
The problem is that you are trying to find a control (in setChecked) without setting the Name property. You are using this:
CheckBoxList chkList = (CheckBoxList)Place.FindControl("ChkUser");
But where is this in AddControl?
chkList.Name = "ChkUser";
And in GetListCheckBoxText instead of...
if (c.GetType().Name == "CheckBoxList")
...use this:
if (c.GetType()== typeof(CheckBoxList))

Resources