Friday, July 31, 2009

Data into DataGridView from XML file

In this article we are going to know how to get data in DataGridView from XML file.
now we create an XML file.

Create an XML file:

< ?xml version="1.0" encoding="utf-8" ? >
< bookstore >
< book >
< title > The < /title >
< price > 8.99 < /price >
< genre > autobiograph < /genre >
< publicationdate > 1981 < /publicationdate >
< ISBN > 1-861003-11- < /ISBN >
< PageSize > 500 < /PageSize >
< /book >

< book >
< title > The Confiden < /title >
< price > 11.99 < /price >
< genre > novel < /genre >
< publicationdate > 1967 < /publicationdate >
< ISBN > 0-201-63361- < /ISBN >
< /book >

< book >
< title > The Gorgias < /title >
< price > 9.99 < /price >
< genre > philosophy < /genre >
< publicationdate > 1991 < /publicationdate >
< ISBN > ss1-861001-57- < /ISBN >
< PageSize > 600 < /PageSize >
< /book >
< /bookstore >

Create the window application:
There are the following steps for creating the window application.

Step 1: Create new project.

Step 2: Drag and drop DataGridView control from the toolbox on form, and fill all required properties.

Step 3: Add the following namespace to page (form):

using System.Data.SqlClient;
using System.Xml;

Step 4: Write the code on the form load event.

For Example:

Form1.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Xml;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
XmlDataDocument xmlDatadoc = new XmlDataDocument();
xmlDatadoc.DataSet.ReadXml("C:\\books.xml");
DataSet ds = new DataSet("Books DataSet");
ds = xmlDatadoc.DataSet;
dataGridView1.DataSource = ds.DefaultViewManager;
dataGridView1.DataMember = "Book";
}
}
}
Read More

Export Data Grid Content to an XML File

we can use the RenderControl method to extract the content into an .xml file from datagridview.
your Data Grid is not associated with any dataset.and not using any XML support functions

The following code explains:


ArrayList al = new ArrayList();
for(int i=0;i<=10;i++)
{
al.Add(i+"");
}
DataGrid1.DataSource=al;
DataGrid1.DataBind();
Response.Clear();
Response.AddHeader("content-disposition","fileattachment;filename=xmltest.xml");
Response.ContentType="text/xml";

StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
DataGrid1.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
Read More

Monday, July 27, 2009

C# Nullable Numeric Data Types

The data types introduced as part of .NET 2.0 that permit the storage of null information. we are going to discuss about them.the variable which are undefined or contain nullable data.

Null Value
When a program works with numeric information, particularly when it utilises information in a database, it is often the case that a value is undefined. An example of this is when a series of simple yes / no questions is asked and the result of each question held in a Boolean format. After a question is answered, the Boolean value can be set to either true or false to indicate the result. However, before the answer is given what should the value hold? The answer is null.

Nullable Numeric Data Types
Null is a special value that represents information that has not yet been defined. in earlier version the null value exists but could not be applied to numeric variables In .NET framework 2.0, Microsoft rectified this problem by introducing nullable versions of these data types.

All of the basic numeric data types have nullable equivalents. There are several ways to declare a variable as a nullable type. The simplest and most readable method is to simply append a question mark (?) to the data type. The following example shows the declaration and assignment of several nullable variables:
int? nullableInt;
int? nullValue = null;
int? notNull = 123;

bool? answer1 = true;
bool? answer2 = false;
bool? answer3 = null;
You can see from the above example that creating a nullable variable is similar to creating a standard numeric variable. As with other numeric variables, a value must be assigned to a variable before it is used, even if that value is null. The following code produces an error if you attempt to compile it.
int? nullableInt;
int? copy = nullableInt; // Invalid as nullableInt is not yet assigned
Data Type Conversion
Numeric nullable data types include very similar implicit and explicit conversion between the various sizes of nullable integers and floating point values. Values can also be converted between their nullable and non-nullable versions. As you would expect, conversion between two incompatibly sized types requires a cast statement, as does casting from a nullable to a non-nullable type.
int standardInteger = 123;
int? nullableInteger;
decimal standardDecimal = 12.34M;

// Implicit conversion from int to int?
nullableInteger = standardInteger;

// Explicit conversion from int? to int
standardInteger = (int)nullableInteger;

// Explicit cast from decimal to int?
nullableInteger = (int?)standardDecimal;
Care must be taken when casting a nullable value as a non-nullable data type. If the value of the nullable data type is null, this cannot be represented in the destination value and a run-time error will occur. This can be avoided by checking if the value is set to null before attempting the conversion.
Arithmetic Operators
The standard arithmetic operators can be used with numeric nullable data types. However, if the value of any of the operands is null, the result will always be null regardless of any other values.
int? a = 55;
int? n = null;
int? result;

result = a * 2; // result = 110
result = a * n; // result = null
Boolean Operators
When using nullable Boolean data types, the binary standard Boolean logical operators can be used. Where both of the operands used are set to either true or false, the results of the operation are exactly the same as for non-nullable Booleans. Where one or both of the operands used in a logical operation are set to null, the result is usually null. There are two special cases where this does not happen. In a logic OR operation, if any value is true then the result is true, even if the other operand is null. For logical AND operations, if either value is false then the result is also false.
bool? result;

result = true & null; // result = null
result = false & null; // result = false

result = true | null; // result = true
result = false | null; // result = null

result = true ^ null; // result = null
result = false ^ null; // result = null
Relational Operators
The relational operators are all valid for use with nullable numeric data types. However, when the value being compared is null, the results are not always as expected. The equal to and not equal to operators are able to make comparisons with both numeric and null values. With all of the other relational operators, the result of the comparison is always false when a value being compared is null.
int? a = 55;
int? n = null;
bool result;

result = a == n; // result = false
result = a != n; // result = true
result = n == null; // result = true

result = a > n; // result = false
result = a < n; // result = false


Testing for Null Values
The previous section showed the use of the relational operators with numeric nullable types. Included in the examples you can see that it is possible to use the equal to or not equal to operators to test if the value of a variable is null. In addition to these operators, the nullable data types define several properties and methods for checking if the value is null and for retrieving the value where it is not.
HasValue Property
The first property of the numeric nullable types of interest is the HasValue property. This property simply returns a Boolean value indicating whether the nullable variable contains a real value or a null value. To access the value of a property, the member access operator is used. This is simply a full stop (period or dot) placed between the name of the variable and the name of the member (property or method) to be used. The following example shows the HasValue property used to set a non-nullable value to the value of a nullable type with a default value of -1 where the nullable variable has no value.
int? a = 10;
int? n = null;
int result;
bool checkIfNull;

checkIfNull = a.HasValue; // checkIfNull = true
result = checkIfNull ? (int)a : -1; // result = 10

checkIfNull = n.HasValue; // checkIfNull = false
result = checkIfNull ? (int)n : -1; // result = -1
Value Property
The numeric nullable data types include a second property that can be used to retrieve the value from a variable as a non-nullable type. This provides the same effect as a cast from a nullable type to its non-nullable counterpart. As with this type of cast however, a run-time error will occur should the value of the variable be null. The previous example can therefore also be written as follows:
int? a = 10;
int? n = null;
int result;
bool checkIfNull;

checkIfNull = a.HasValue; // checkIfNull = true
result = checkIfNull ? a.Value : -1; // result = 10

checkIfNull = n.HasValue; // checkIfNull = false
result = checkIfNull ? n.Value : -1; // result = -1

result = n.Value; // This causes a run-time error.
GetValueOrDefault Method
The GetValueOrDefault method is available to all of the numeric nullable data types. This method provides all of the functionality of the previous example in a single line of code. The method can be called in two ways. If the method is used without a parameter then the numeric value of the nullable data is returned. If the variable in question has a null value, a zero is returned instead. The second manner to call the method includes passing a parameter to specify the default value to replace nulls with. As with all methods, the parameter is held in parentheses with an empty pair of parentheses should no parameter be specified.
int? a = 10;
int? n = null;
int result;

result = a.GetValueOrDefault(); // result = 10

result = n.GetValueOrDefault(); // result = 0
result = n.GetValueOrDefault(-1); // result = -1
The Null Coalescing Operator
The null coalescing operator is a new operator introduced as a part of the .NET framework version 2.0. This operator can be used on any numeric nullable data type and also other nullable data types that have yet to be introduced in the C# Fundamentals tutorial.
The null coalescing operator tests the value of a variable to check if it is null. If the value is not null then the variable's value is returned unaffected. If the variable is null however, a substitute value is provided as a second operand. The operator provides similar functionality to the GetValueOrDefault method with the benefit that it can be used on data that does not provide this functionality. The operator's symbol is a double question mark (??).
int? a = 10;
int? n = null;
int result;

result = a ?? -1; // result = 10
result = n ?? -1; // result = -1
Read More

Calling JavaScript from ASP.NET Master Page and Content Pages

1. Create a JavaScript function on the fly and call the JavaScript function in the Content Page Page_Load() event
C#
protected void Page_Load(object sender, EventArgs e)
{
const string someScript = "alertMe";
if (!ClientScript.IsStartupScriptRegistered(this.GetType(), someScript))
{
ClientScript.RegisterStartupScript(this.GetType(),
someScript, "alert('I was called from Content page!')", true);
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim someScript As String = "alertMe"
If (Not ClientScript.IsStartupScriptRegistered(Me.GetType(), someScript)) Then
ClientScript.RegisterStartupScript(Me.GetType(), someScript, "alert('I was called from Content page!')", True)
End If
End Sub

2. Call a JavaScript function declared in a .js file from the Content Page
If you have a .js file and want to call the function from your Content Page, then here’s how to do so.
Let’s create a .js file called TestScript.js and add the following function in the .js file.
function insideJS() {
alert('Inside .js');
}
Assuming that your .js file is kept in a Script folder, reference the file in your MasterPage in the following manner.
< head runat="server" >
< title >< /title >
< script src="Scripts/TestScript.js" type="text/javascript" >< /script >
...
Now in your Content Page(in our case Default.aspx.cs or .vb), call the JavaScript function on the Page_Load:
C#

protected void Page_Load(object sender, EventArgs e)
{
if (!Master.Page.ClientScript.IsStartupScriptRegistered("alert"))
{
Master.Page.ClientScript.RegisterStartupScript
(this.GetType(), "alert", "insideJS();", true);
}
}

VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If (Not Master.Page.ClientScript.IsStartupScriptRegistered("alert")) Then
Master.Page.ClientScript.RegisterStartupScript (Me.GetType(), "alert", "insideJS();", True)
End If
End Sub
3. Referencing the .js file from a Content Page instead of the Master page
The approach shown above in Tip 2 works well, however this approach would add a reference to the .js file for every page in the application (since we are adding the .js in the Master Page). If you want to avoid this approach, then remove the reference added to the .js file in Tip 2 in the Master Page. Now add a reference to the .js file from the Content Page using the ‘RegisterClientScriptInclude’ as shown below:
C#
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptInclude("selective", ResolveUrl(@"Scripts\TestScript.js"));
if (!Master.Page.ClientScript.IsStartupScriptRegistered("alert"))
{
Master.Page.ClientScript.RegisterStartupScript
(this.GetType(), "alert", "insideJS();", true);
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Page.ClientScript.RegisterClientScriptInclude("selective", ResolveUrl("Scripts\TestScript.js"))
If (Not Master.Page.ClientScript.IsStartupScriptRegistered("alert")) Then
Master.Page.ClientScript.RegisterStartupScript(Me.GetType(), "alert", "insideJS();", True)
End If
End Sub
Using this approach, we can avoid referencing the .js file for every content page.
Note: This approach adds the JavaScript reference inside the < body >tag of the page.

4. Declare JavaScript inside the Content page and execute it
If you are looking out to declare JavaScript inside the Content Page, then here’s how to do so. Add the following markup inside the Content page (in our case Default.aspx)
< asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server" >
< asp:Panel ID="panelContent" GroupingText="ContentPage Controls" runat="server" >
< asp:TextBox ID="txtContent" runat="server" >< /asp:TextBox >
< asp:Button ID="btnContent" runat="server" Text="Button" OnClientClick="Populate();" / >
< /asp:Panel >
< script type="text/javascript" language="javascript" >
function Populate() {
{
document.getElementById('< %=txtContent.ClientID% >').value = "Hi";
}
}
< /script >
< /asp:Content >
The markup shown above populates the textbox with some text on a button click.

5. Accessing a Control on the Master Page From a ContentPage using JavaScript
We have added a textbox control to the < body > of the MasterPage as shown below:
< body >
< form id="form1" runat="server" >
< div >
< asp:Panel ID="panelMaster" GroupingText="MasterPage controls" runat="server" >
< asp:TextBox ID="txtMaster" runat="server" >< /asp:TextBox >
< br / >
< /asp:Panel >
< asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server" >

< /asp:ContentPlaceHolder >
< /div >
< /form >
< /body >
We will now access this TextBox ‘txtMaster’ in the ContentPage using JavaScript
To do so, go to the Content page (Default.aspx) and add the following line below the < Page > directive to register the MasterPage
< %@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" % >
...
< %@ MasterType VirtualPath="~/MasterPage.master" % >
...
Now in the code behind of Default.aspx.cs or .vb, access the MasterPage control in the following manner
C#
protected void Page_Load(object sender, EventArgs e)
{
TextBox tb = (TextBox)Master.FindControl("txtMaster");
string val = tb.ClientID;
string script = @"< script >
function PopulateMaster() {
document.getElementById('" + val + @"').value = 'Via Content Page. Love dotnetcurry';
}
PopulateMaster();
< /script >";
if (!Page.ClientScript.IsStartupScriptRegistered("Mast"))
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"Mast", script);
}

}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim tb As TextBox = CType(Master.FindControl("txtMaster"), TextBox)
Dim val As String = tb.ClientID
Dim script As String = "< script >" & ControlChars.CrLf & " function PopulateMaster() {" & ControlChars.CrLf & " document.getElementById('" & val & "').value = 'Via Content Page. Love dotnetcurry.com'; " & ControlChars.CrLf & " }" & ControlChars.CrLf & " PopulateMaster();" & ControlChars.CrLf & " < /script >"
If (Not Page.ClientScript.IsStartupScriptRegistered("Mast")) Then
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Mast", script)
End If

End Sub

Observe how we have used the RegisterStartupScript instead of RegisterClientScriptBlock. The main difference is that the 'RegisterStartupScript' method places the JavaScript at the bottom of the ASP.NET page right before the closing < /form > element whereas the 'RegisterClientScriptBlock' method places the JavaScript directly after the opening < form > element in the page. Had we used the 'RegisterClientScriptBlock', the browser would have executed the JavaScript before the text box is on the page. Therefore, the JavaScript would not have been able to find a ‘txtMaster’ and would give a control not found error. Understanding this simple difference between the two methods can save you hours of work!

6. Call JavaScript function from an ASP.NET AJAX enabled Content Page
If your content page is wrapped in an ASP.NET AJAX UpdatePanel, then you cannot use the ClientScript.RegisterStartupScript to call a JavaScript function during a partial-page postback. Instead, use the ScriptManager.RegisterStartupScript() method.
C#
protected void Page_Load(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"< script language='javascript' >");
sb.Append(@"alert('I love dotnetcurry.com');");
sb.Append(@"< /script >");

ScriptManager.RegisterStartupScript(this, this.GetType(), "ajax", sb.ToString(), false);

}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As New System.Text.StringBuilder()
sb.Append("< script language='javascript' >")
sb.Append("alert('I love dotnetcurry');")
sb.Append("< /script >")

ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ajax", sb.ToString(), False)

End Sub
Observe that the last parameter for RegisterStartupScript() is set to 'false'. This means that the < script > tags will not be added automatically. Since we have already inserted the < script > tags while creating the script in the StringBuilder, we do not need to insert them now.
Read More

Execute JavaScript function from ASP.NET codebehind

by declaring a JavaScript function in your code as shown below you can easly do it:

JavaScript


< head runat="server" >

< title >Call JavaScript From CodeBehind< /title >

< script type="text/javascript" >



function alertMe() {

alert('Hello');

}

< /script >

< /head >



now write below code in Page_Load to call it from code behind:

VB.NET


If (Not ClientScript.IsStartupScriptRegistered("alert")) Then

Page.ClientScript.RegisterStartupScript _

(Me.GetType(), "alert", "alertMe();", True)

End If

C#


if (!ClientScript.IsStartupScriptRegistered("alert"))

{

Page.ClientScript.RegisterStartupScript

(this.GetType(), "alert", "alertMe();", true);

}








The Page.ClientScript.RegisterStartupScript() allows you to emit client-side script blocks from code behind.
Read More

Call codebehind server code from javascript

to execute the code written in code behind (c#, vb.net). we need to know that the exists on server, not at client. so it is needed to make a postback to reach the code.

to avoid full postback we can use AJAX.



put the code below in your .aspx.cs file



private void Page_Load(object sender, System.EventArgs e)

{

Ajax.Utility.RegisterTypeForAjax(typeof(WebForm1));

DropDownList1.Attributes.Add("onchange","CallBack();");

}

[Ajax.AjaxMethod()]

public int ServerSideAdd(int firstNumber,int secondNumber)

{

return firstNumber + secondNumber;

}

Put the given below code in your aspx file

< script language="javascript" >

function CallBack()

{

val1=document.getElementById('txtValue1').value;

val2=document.getElementById('txtValue2').value;

WebForm1.ServerSideAdd(val1,val2, ServerSideAdd_CallBack);



}

function ServerSideAdd_CallBack(response)

{

alert(response.value);

}

< /script >

< body MS_POSITIONING="GridLayout" >

< form id="Form1" method="post" runat="server" >

< INPUT onclick="CallBack()" type="button" value="Button" runat="server" >

< asp:dropdownlist id="DropDownList1" style="Z-INDEX: 101; LEFT: 224px; POSITION: absolute; TOP: 48px"

runat="server" >

< asp:ListItem Value="Rajesh" >Amit< /asp:ListItem >

< asp:ListItem Value="Rolen" >Ajay< /asp:ListItem >

< asp:ListItem Value="JSJodha" >Arun< /asp:ListItem >

< asp:ListItem Value="Mukesh" >Ravi< /asp:ListItem >

< /asp:dropdownlist >< asp:button id="Button1" style="Z-INDEX: 102; LEFT: 280px; POSITION: absolute; TOP: 160px" runat="server"

Text="Button" >< /asp:button >

< asp:TextBox id="txtValue" style="Z-INDEX: 103; LEFT: 304px; POSITION: absolute; TOP: 88px" runat="server" >< /asp:TextBox >

< asp:TextBox id="txtValue1" style="Z-INDEX: 104; LEFT: 312px; POSITION: absolute; TOP: 232px"

runat="server" >< /asp:TextBox >

< asp:TextBox id="txtValue2" style="Z-INDEX: 105; LEFT: 520px; POSITION: absolute; TOP: 200px"

runat="server" >< /asp:TextBox >< /form >

< /body >

Read More

Friday, July 10, 2009

ASP.NET Website Administration Tool With Custom Role Provider

you could just copy the files from "C:\Windows\Microsoft.NET\Framework\v2.0.50727\ASP.NETWebAdminFiles" to your live site. this is web administartion files used by visual studio. so its bug free as well as readily available.
Read More
Powered By Blogger · Designed By Seo Blogger Templates