Dynamically add static method in aspx page from ascx - asp.net

i was searching google for that is there any way to add any method in my page at run time. i got a link from stackoverflow for this....that is expando object.
i am not familiar with expando object. here is little snippet of code i got and like
namespace DynamicDemo
{
class ExpandoFun
{
public static void Main()
{
Console.WriteLine("Fun with Expandos...");
dynamic student = new ExpandoObject();
student.FirstName = "John";
student.LastName = "Doe";
student.Introduction=new Action(()=>
Console.WriteLine("Hello my name is {0} {1}",student.FirstName,student.LastName);
);
);
Console.WriteLine(student.FirstName);
student.Introduction();
}
}
}
according to my situation i need to add a routine below like
in many aspx page.
[WebMethod]
public static string LoadData(string CountryCode,int PageIndex)
{
string strData = "";
if (CountryCode != "")
{
strData = Left1.HavingCountry(CountryCode, PageIndex);
}
else
{
strData = Left1.WithoutCountry(PageIndex);
}
return strData;
}
so i need to know that is there any way to add some technique in my ascx page which will add the above method in all the aspx pages which host that particular ascx. please help me to achieve it. thanks

I don't think it is possible.
Can you do this way
1. create a `class` which extents `System.Web.UI.Page`.
2. write you `WebMethod` in that class.
3. Create your aspx pages by extending this class
public partial class _Default : TestUserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
public class TestUserControl : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string LoadData(string CountryCode, int PageIndex)
{
string strData = "";
if (CountryCode != "")
{
strData = Left1.HavingCountry(CountryCode, PageIndex);
}
else
{
strData = Left1.WithoutCountry(PageIndex);
}
return strData;
}
}

Related

display next page asynchronously and then run its page load event

I have an airline site in which i am trying to display the fare from different API/Web service. But Firstly i want to display the search page--> Display processing --> binding data in the page from theses API/web service as they received.
but i am not able to display search page before the result processing.
What i have tried (code)-
public partial class asyncgridview : System.Web.UI.Page,ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsCallback)
{
ltCallback.Text = ClientScript.GetCallbackEventReference(this, "'bindgrid'", "EndGetData", "'asyncgrid'", false);
}
}
private string _Callback;
public string GetCallbackResult()
{
return _Callback;
}
public void RaiseCallbackEvent(string eventArgument)
{
DataTable table = fetchData();
gvAsync.DataSource = table;
gvAsync.DataBind();
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
gvAsync.RenderControl(new HtmlTextWriter(sw));
_Callback = sw.ToString();
}
}
}
regards
Avishek

drop-down list in C# issue

drop-down list in C#.net not showing the items it supposed to show!
i hv a drop-down list that suppose to show image names from a folder, but it is not doing that!
i dont have errors when launching the .aspx file!
buuuuuut when i get output there is only empty dropdown list!
this the ManageProducts.aspx codes are:
Name:
Type:
" SelectCommand="SELECT * FROM [ProductTypes] ORDER BY [Name]">
Price:
Image:
Description:
and this the behind codes:
using System;
using System.Collections;
using System.IO;
public partial class PagesNew_ManagementPages_ManageProducts : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) //this baby makes the data not come every time the pg is refreshed ,
//postback=refresh page
GetImages();
}
private void GetImages()
{
try
{
//get all filepaths
string[] images = Directory.GetFiles(Server.MapPath("~/Img/Products/"));
//get all filenames and put them in a stupid array....yeah DSA days
ArrayList imageList = new ArrayList();
foreach (string image in images)
{
string imageName = image.Substring(image.LastIndexOf(#"\", StringComparison.Ordinal) + 1);
imageList.Add(imageName);
// see the Array in dd viwe datasource and refresh
ddImage.AppendDataBoundItems = true;
ddImage.DataBind();
}
}
catch (Exception e)
{
lblResult.Text = e.ToString();
}
}
protected void ddImage_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
You want to bind your datalist outside of the for loop.
ArrayList imageList = new ArrayList();
foreach (string image in images)
{
string imageName = image.Substring(image.LastIndexOf(#"\", StringComparison.Ordinal) + 1);
imageList.Add(imageName);
}
ddImage.DataSource = imageList;
ddImage.AppendDataBoundItems = true;
ddImage.DataBind();

IsHandleCreated Prop. is always false for gridview control in dev express

My windows form contains ​DevExpress.XtraGrid.GridControl on Form1 similar way there is also 2nd class called it as Form2. On Form1 I am loading data from database. When I double click on grid row it assigns to an Form2. on Form1 gridControl1_DoubleClick event IsHandleCreated prop is true (Form2 is Inherited from Form1)
void gridControl1_DoubleClick(object sender, EventArgs e)
{
if (gridControl1.IsHandleCreated)
{
}
Form2 obj = new Form2();
obj.Display();
}
so I have created one property like on Form1
public GridControl GridControl1
{
get { return gridControl1; }
}
but when I call the Display() method of Form2 and check the IsHandleCreated prop on Form2 is false.
public void Display()
{
if (handleCreated)
{
}
}
complete code as below **Form1**
public partial class Form1 : Form
{
public GridControl GridControl1
{
get { return gridControl1; }
}
public bool handleCreated
{
get { return gridControl1.IsHandleCreated; }
}
public Form1()
{
InitializeComponent();
gridControl1.DataSource = CreateTable(20);
gridControl1.DoubleClick += gridControl1_DoubleClick;
}
void gridControl1_DoubleClick(object sender, EventArgs e)
{
if (gridControl1.IsHandleCreated)
{
}
Form2 obj = new Form2();
obj.Display();
}
private DataTable CreateTable(int rowCount)
{
DataTable table = new DataTable();
table.Columns.Add("String", typeof(string));
table.Columns.Add("Int", typeof(int));
table.Columns.Add("Date", typeof(DateTime));
for (var i = 0; i < rowCount; i++)
{
table.Rows.Add(string.Format("Row {0}", i), i, DateTime.Today.AddDays(i));
}
return table;
}
}
**Form2**
public class Form2 : Form1
{
public Form2()
{
}
public void Display()
{
if (handleCreated)
{
}
//Form1 obj = new Form1();
//if (obj.handleCreated)
//{
//}
}
}
In Form2 handleCreated its always false I dont know why?
please help me
This is because your form2 object is just only initialized. Control will get its handle only after window is created, which displays this control. So, you need to call form2.Show() or form2.ShowDialog() and after that check for gridControl1.IsHandleCreated.
You can simply test this behavior by using this code:
Form2 obj = new Form2();
MessageBox.Show("Created: " + obj.handleCreated);
obj.Show();
MessageBox.Show("Shown: " + obj.handleCreated);

Find all textbox control in a page

i am trying to use http Module to disable textbox of each page. Here is my sample coding
public void context_OnPreRequestHandlerExecute(object sender, EventArgs args)
{
try
{
HttpApplication app = sender as HttpApplication;
if (app != null)
{
Page page = app.Context.Handler as Page;
if (page != null)
{
page.PreRender += OnPreRender;
page.PreLoad += onPreLoad;
}
}
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
public void OnPreRender(object sender, EventArgs args)
{
Page page = sender as Page;
if (page.IsCrossPagePostBack)
{
DisableAllTextBoxes(page);
}
}
private static void DisableAllTextBoxes(Control parent)
{
foreach (Control c in parent.Controls)
{
var tb = c as Button;
if (tb != null)
{
tb.Enabled = false;
}
DisableAllTextBoxes(c);
}
}
This coding can work very well but when i use server.transer to another page. Button are not able to disable already.
For example webform1 transfer to webform2. Webform 1's button is able to disable but webform2 is not able to disable. Can anyone solve my problem?
Server.Transfer DOES NOT go through all http module pipline (thats why context_OnPreRequestHandlerExecute isn't executed for you )
you should try Server.TransferRequest or response.redirect or HttpContext.Current.RewritePath
Use LINQ to get all your textbox controls.
Don't use Server.Transfer()
Create an extension method on ControlCollection that returns an IEnumerable. That handles the recursion. Then you could use it on your page like this:
var textboxes = this.Controls.FindAll().OfType<TextBox>();
foreach (var t in textboxes)
{
t.Enabled = false;
}
...
public static class Extensions
{
public static IEnumerable<Control> FindAll(this ControlCollection collection)
{
foreach (Control item in collection)
{
yield return item;
if (item.HasControls())
{
foreach (var subItem in item.Controls.FindAll())
{
yield return subItem;
}
}
}
}
}
Taken from this answer.

MS-Sharepoint 2007: Custom Field Control, TemplateContainer.FindControl always returns NULL

I have SharePoint 2007 on Windows Server 2003 SP1 (in VM).
I am running the web application here: http://vspug.com/nicksevens/2007/08/31/create-custom-field-types-for-sharepoint/
Part of it is below:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace CustomControl
{
public class customfieldcontrol : BaseFieldControl
{
protected TextBox txtFirstName;
protected TextBox txtLastName;
protected override string DefaultTemplateName
{
get { return "CustomFieldRendering"; }
}
public override object Value
{
get
{
EnsureChildControls();
return txtFirstName.Text + "%" + txtLastName.Text;
}
set
{
try
{
EnsureChildControls();
txtFirstName.Text = value.ToString().Split('%')[0];
txtLastName.Text = value.ToString().Split('%')[1];
}
catch { }
}
}
public override void Focus()
{
EnsureChildControls();
txtFirstName.Focus();
}
protected override void CreateChildControls()
{
if (Field == null) return;
base.CreateChildControls();
//Don't render the textbox if we are just displaying the field
if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.Display) return;
txtFirstName = (TextBox)TemplateContainer.FindControl("txtFirstName");
txtLastName = (TextBox)TemplateContainer.FindControl("txtLastName");
if (txtFirstName == null) throw new NullReferenceException("txtFirstName is null");
if (txtLastName == null) throw new NullReferenceException("txtLastName is null");
if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.New)
{
txtFirstName.Text = "";
txtLastName.Text = "";
}
}
}
}
This line:
txtFirstName = (TextBox)TemplateContainer.FindControl("txtFirstName");
always returns null.
I removed base.CreateChildControls() but it still returns null.
Any assistance would be greatly appreciated.
Place your control's .ascx file right under CONTROLTEMPLATES folder and try.

Resources