Invoking a Page Method from User control in C#
Scenario:
Calling a method defined in the page CodeBehind file from a user control.
For example, if you want to refresh some controls in page when you saved some data in user control through an event in the user control.
To do this, we can define an event handler in the CodeBehind and it can be invoked from user control whenever required. From the event in the page we can call the page method which can refresh the page controls.
This sample code explains how to create event handler for page events and invoking the event in User Control
WebUserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Button ID="btnSave" runat="server" Text="btnSave" OnClick="btnSave_Click" />
WebUserControl.ascx.cs
public partial class WebUserControl : System.Web.UI.UserControl
{
public event EventHandler ehClick;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
ehClick.Invoke(this, new EventArgs());
}
}
Default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Register an event handler which will be invoked from the user control
this.WebUserControl1.ehClick += new EventHandler(this.btnPageButton_Click);
}
public void SaveData()
{
//Page Method
/*
Code
*/
//Displaying Current Date
Response.Write(System.DateTime.Now.ToString());
}
protected void btnPageButton_Click(object sender, EventArgs e)
{
SaveData();
}
}
The single place to get answer to your .net and business Intelligence Questions
Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts
Monday, January 3, 2011
Wednesday, May 27, 2009
Display unicode characters in the web control
First let me explain the scenario.
You have unicode data in one of the fields of my DB table, and you want to fetch the unicode data and display it in a textbox lets say a currency symbol £ (GPB).
Now if you are simply assigning the text from datatable field then it would not show £ sign rather some other code value.
Its very simple to display it in its actual form just use
HttpUtility.HtmlDecode on the string
coming from the DB and get the correct output.
Cheers
You have unicode data in one of the fields of my DB table, and you want to fetch the unicode data and display it in a textbox lets say a currency symbol £ (GPB).
Now if you are simply assigning the text from datatable field then it would not show £ sign rather some other code value.
Its very simple to display it in its actual form just use
HttpUtility.HtmlDecode on the string
coming from the DB and get the correct output.
Cheers
Wednesday, April 1, 2009
Check availability of user name on a registration / Signup form
While registering a new user on your site, the idea to check the availability of user name is of great use.
It saves the time of registering user and makes a great value for users.
You need to do following things in order to achieve that-
1) Include the below give javascript file in your project
2) Identify the event on which the availability is to be checked (better if you give a seperate button or simply a href for it), in my code i've used a href to check the availability.
3) Areas and messages to be displayed (you can customize the messages to be displayed)
4) On code behind define a [WebMethod] for checking the availability
JScript File
var usernameCheckerTimer;
var isavailable=false;
function usernameChecker(username)
{
clearTimeout(usernameCheckerTimer);
if (username.length == 0){
{
//You can customize the mesage for blank user name
$get("spanAvailability").innerHTML = "<span style='color: Red;'>Can't be blank";
document.forms[0].txtLoginId.focus();
}
else
{
//You can customize the mesage for Checking..
$get("spanAvailability").innerHTML = "<span style='color: #000;'>Checking...";
usernameCheckerTimer = setTimeout("checkUsernameUsage('" + username + "');", 750);
}
}
function checkUsernameUsage(username)
{
// initiate the ajax pagemethod call
// upon completion, the OnSucceded callback will be executed
PageMethods.IsUserAvailable(username, OnSucceeded);
}
// Callback function invoked on successful completion of the page method.
function OnSucceeded(result, userContext, methodName)
{
$get("spanAvailability").innerHTML = "";
if (methodName == "IsUserAvailable")
{
if (result == true)
{
//You can customize the mesage for Available
$get("spanAvailability").innerHTML = "<span style='color: DarkGreen;'>Available";
isavailable=true;
}
else
{
//You can customize the mesage for NotAvailable
$get("spanAvailability").innerHTML = "<span style='color: Red;'>Unavailable";
document.forms[0].txtLoginId.focus();
isavailable=false;
}
}
}
The link for checking the availability
<a href="#" onclick="usernameChecker(document.getElementById('txtLoginId').value);">Check Availability?/a>
The webmethod for your code behind page
[WebMethod]
public static bool IsUserAvailable(string username)
{
MembershipUser usr = Membership.GetUser(username);
return (usr == null);
}
Don't forgrt to include
using System.Web.Services;
Cheers
It saves the time of registering user and makes a great value for users.
You need to do following things in order to achieve that-
1) Include the below give javascript file in your project
2) Identify the event on which the availability is to be checked (better if you give a seperate button or simply a href for it), in my code i've used a href to check the availability.
3) Areas and messages to be displayed (you can customize the messages to be displayed)
4) On code behind define a [WebMethod] for checking the availability
JScript File
var usernameCheckerTimer;
var isavailable=false;
function usernameChecker(username)
{
clearTimeout(usernameCheckerTimer);
if (username.length == 0){
{
//You can customize the mesage for blank user name
$get("spanAvailability").innerHTML = "<span style='color: Red;'>Can't be blank";
document.forms[0].txtLoginId.focus();
}
else
{
//You can customize the mesage for Checking..
$get("spanAvailability").innerHTML = "<span style='color: #000;'>Checking...";
usernameCheckerTimer = setTimeout("checkUsernameUsage('" + username + "');", 750);
}
}
function checkUsernameUsage(username)
{
// initiate the ajax pagemethod call
// upon completion, the OnSucceded callback will be executed
PageMethods.IsUserAvailable(username, OnSucceeded);
}
// Callback function invoked on successful completion of the page method.
function OnSucceeded(result, userContext, methodName)
{
$get("spanAvailability").innerHTML = "";
if (methodName == "IsUserAvailable")
{
if (result == true)
{
//You can customize the mesage for Available
$get("spanAvailability").innerHTML = "<span style='color: DarkGreen;'>Available";
isavailable=true;
}
else
{
//You can customize the mesage for NotAvailable
$get("spanAvailability").innerHTML = "<span style='color: Red;'>Unavailable";
document.forms[0].txtLoginId.focus();
isavailable=false;
}
}
}
The link for checking the availability
<a href="#" onclick="usernameChecker(document.getElementById('txtLoginId').value);">Check Availability?/a>
The webmethod for your code behind page
[WebMethod]
public static bool IsUserAvailable(string username)
{
MembershipUser usr = Membership.GetUser(username);
return (usr == null);
}
Don't forgrt to include
using System.Web.Services;
Cheers
Labels:
asp.net,
c#,
check availability,
check user name availability,
code,
example,
javascript,
sign up,
signup,
user name
Tuesday, December 23, 2008
Scrolling News on a Web page
On many of the web portals/sites it is observed that latest news start scrolling from down to top.
To do this need to write JavaScript in detail, there could be number of storing news format. I have written this web control to avoid extensive use of JavaScript by using Marquee at server side.
Requirement: Need To make following tables in SQL Server Database, and put corresponding records in the tables.
This is a very simple table structure in Master Detail format. In tbl_News all the titles and date created will be stored and corresponding newsDetail are stored in tbl_NewsDetail.
News Table
create table tbl_News
(
newsId int primary key identity(1,1) Not null,
newTitle varchar(50) Not null,
dateCreated datetime
)
News Detail Table
create table tbl_NewsDetail
(
dtlId int primary key identity(1,1) Not Null,
newsId int foreign key references tbl_news,
newsDetail varchar(8000)
)
Explanation in detail about the coding
In folder called as "userControll" I have web control as "Scrolling_News.ascx".
The code behind of this page i.e. on page load I have following code
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
SqlConnection myCon = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);
string strSql = "SELECT * FROM tbl_News order by dateCreated asc";
string strScrolling = "";
HtmlTableCell cellScrolling = new HtmlTableCell();
SqlCommand myComd = new SqlCommand(strSql,myCon);
SqlDataReader sqlRdr;
try
{
myCon.Open();
sqlRdr = myComd.ExecuteReader();
strScrolling = "?Marquee OnMouseOver='this.stop();' OnMouseOut='this.start();' direction='up' scrollamount='2' bgcolor='#000000' width='40%'?";
//replace ? with < >
while(sqlRdr.Read())
{
strScrolling = strScrolling + " ('newsDetail.aspx?NewsId="+sqlRdr.GetValue(0)
+"','NewsDetail','width=400,height=400;toolbar=no;');"+"> face='verdana' size='2' color='#ffffff'>"+ sqlRdr.GetValue(1)
+" "+sqlRdr.GetValue(2).ToString()+"
";
}
strScrolling = strScrolling +"?/Marquee>";
sqlRdr.Close();
cellScrolling.InnerHtml = strScrolling;
rowScrolling.Cells.Add(cellScrolling);
}
catch(Exception msg)
{
Response.Write(msg.Message);
}
finally
{
//close sql connection
myCon.Close();
}
}
Which just prepare a connection with the database and get the newsTitle and dateCreated to scroll in the marquee in direction='UP'. I have prepared a string which can be added dynamically in a table row to fit in appropriate table row, which generates scrolling news section with anchor (link) to open detail in the new window. Idea behind opening in new window to stick the user to same site. You can do following with the marquee and JavaScript functionality used in the same.
Change the direction of the scrolling [direction='up']
Can stop on mouseover of the link [OnMouseOver='this.stop();']
Can start on mouseout of the link [OnMouseOut='this.start();']
Can controll the speed of the scrolling [direction='up' scrollamount='2']
Microsoft also provide Add rotator component which can be used with XML, but it differs with respect that
by having above functionality.
In newsDetail.aspx page, I have again simple code to get the detail based on querystring of newsId.
Using this control in a page
Register this control as below in a file in which you want to use this
<%@ Register TagPrefix="Scrolling" TagName="News" src="userControll/Scrolling_News.ascx" %>
and use this in a table as below
?table width="100%" bgColor="#ccccff">
?tr>
?td width="60%">?STRONG>?FONT face="Tahoma">News Section ?/FONT? ?/STRONG? ? /td>
?tr>
?td> ?SCROLLING:NEWS id="scroller" runat="server"> ?/SCROLLING:NEWS> ?/td>
?/tr>
?/table>
Replace ? with < >
That' all enjoy...
To do this need to write JavaScript in detail, there could be number of storing news format. I have written this web control to avoid extensive use of JavaScript by using Marquee at server side.
Requirement: Need To make following tables in SQL Server Database, and put corresponding records in the tables.
This is a very simple table structure in Master Detail format. In tbl_News all the titles and date created will be stored and corresponding newsDetail are stored in tbl_NewsDetail.
News Table
create table tbl_News
(
newsId int primary key identity(1,1) Not null,
newTitle varchar(50) Not null,
dateCreated datetime
)
News Detail Table
create table tbl_NewsDetail
(
dtlId int primary key identity(1,1) Not Null,
newsId int foreign key references tbl_news,
newsDetail varchar(8000)
)
Explanation in detail about the coding
In folder called as "userControll" I have web control as "Scrolling_News.ascx".
The code behind of this page i.e. on page load I have following code
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
SqlConnection myCon = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);
string strSql = "SELECT * FROM tbl_News order by dateCreated asc";
string strScrolling = "";
HtmlTableCell cellScrolling = new HtmlTableCell();
SqlCommand myComd = new SqlCommand(strSql,myCon);
SqlDataReader sqlRdr;
try
{
myCon.Open();
sqlRdr = myComd.ExecuteReader();
strScrolling = "?Marquee OnMouseOver='this.stop();' OnMouseOut='this.start();' direction='up' scrollamount='2' bgcolor='#000000' width='40%'?";
//replace ? with < >
while(sqlRdr.Read())
{
strScrolling = strScrolling + " ('newsDetail.aspx?NewsId="+sqlRdr.GetValue(0)
+"','NewsDetail','width=400,height=400;toolbar=no;');"+"> face='verdana' size='2' color='#ffffff'>"+ sqlRdr.GetValue(1)
+" "+sqlRdr.GetValue(2).ToString()+"
";
}
strScrolling = strScrolling +"?/Marquee>";
sqlRdr.Close();
cellScrolling.InnerHtml = strScrolling;
rowScrolling.Cells.Add(cellScrolling);
}
catch(Exception msg)
{
Response.Write(msg.Message);
}
finally
{
//close sql connection
myCon.Close();
}
}
Which just prepare a connection with the database and get the newsTitle and dateCreated to scroll in the marquee in direction='UP'. I have prepared a string which can be added dynamically in a table row to fit in appropriate table row, which generates scrolling news section with anchor (link) to open detail in the new window. Idea behind opening in new window to stick the user to same site. You can do following with the marquee and JavaScript functionality used in the same.
Change the direction of the scrolling [direction='up']
Can stop on mouseover of the link [OnMouseOver='this.stop();']
Can start on mouseout of the link [OnMouseOut='this.start();']
Can controll the speed of the scrolling [direction='up' scrollamount='2']
Microsoft also provide Add rotator component which can be used with XML, but it differs with respect that
by having above functionality.
In newsDetail.aspx page, I have again simple code to get the detail based on querystring of newsId.
Using this control in a page
Register this control as below in a file in which you want to use this
<%@ Register TagPrefix="Scrolling" TagName="News" src="userControll/Scrolling_News.ascx" %>
and use this in a table as below
?table width="100%" bgColor="#ccccff">
?tr>
?td width="60%">?STRONG>?FONT face="Tahoma">News Section ?/FONT? ?/STRONG? ? /td>
?tr>
?td> ?SCROLLING:NEWS id="scroller" runat="server"> ?/SCROLLING:NEWS> ?/td>
?/tr>
?/table>
Replace ? with < >
That' all enjoy...
Labels:
.net,
asp.net,
c#,
how to scroll news,
html,
news,
problem,
programming,
scroll,
scrolling,
scrolling news,
scrolling text,
text,
web pages
Friday, April 4, 2008
To insert / displayRow number in DataGridView
Add following code to the event dataGridView1_RowPostPaint in your Code behind
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
// get the row number in leading zero format,
// where the width of the number = the width of the maximum number
int RowNumWidth = dataGridView1.RowCount.ToString().Length;
StringBuilder RowNumber = new StringBuilder(RowNumWidth);
RowNumber.Append(e.RowIndex + 1);
while (RowNumber.Length < RowNumWidth)
RowNumber.Insert(0, "0");
// get the size of the row number string
SizeF Sz = e.Graphics.MeasureString(RowNumber.ToString(), this.Font);
// adjust the width of the column that contains the row header cells
if (dataGridView1.RowHeadersWidth < (int)(Sz.Width + 20))
dataGridView1.RowHeadersWidth = (int)(Sz.Width + 20);
// draw the row number
e.Graphics.DrawString(
RowNumber.ToString(),
this.Font,
SystemBrushes.ControlText,
e.RowBounds.Location.X + 15,
e.RowBounds.Location.Y + ((e.RowBounds.Height - Sz.Height) / 2));
}
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
// get the row number in leading zero format,
// where the width of the number = the width of the maximum number
int RowNumWidth = dataGridView1.RowCount.ToString().Length;
StringBuilder RowNumber = new StringBuilder(RowNumWidth);
RowNumber.Append(e.RowIndex + 1);
while (RowNumber.Length < RowNumWidth)
RowNumber.Insert(0, "0");
// get the size of the row number string
SizeF Sz = e.Graphics.MeasureString(RowNumber.ToString(), this.Font);
// adjust the width of the column that contains the row header cells
if (dataGridView1.RowHeadersWidth < (int)(Sz.Width + 20))
dataGridView1.RowHeadersWidth = (int)(Sz.Width + 20);
// draw the row number
e.Graphics.DrawString(
RowNumber.ToString(),
this.Font,
SystemBrushes.ControlText,
e.RowBounds.Location.X + 15,
e.RowBounds.Location.Y + ((e.RowBounds.Height - Sz.Height) / 2));
}
Insert / display row number in GridView
To insert row number in GridView -
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<%# Container.DataItemIndex + 1 %>
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<%# Container.DataItemIndex + 1 %>
Thursday, April 3, 2008
Refresh a web page automatically
<Head>
<%--Following line will automatically refresh the page every 5 seconds
--%>
<meta equiv="refresh" content="5">
</Head>
<%--Following line will automatically refresh the page every 5 seconds
--%>
<meta equiv="refresh" content="5">
</Head>
Labels:
asp.net,
automatic page refresh,
c#,
html,
meta tag,
page refresh
Subscribe to:
Posts (Atom)