Pages

Saturday 29 September 2012

How to insert data into database using Linq?

Step-1: Create a table in your database. In my example I have a table(EmpDetails) which will keep the details(EmployeeID,EmployeeName and Address) of an employee.
Step-2: Add a new "LINQ to SQL Classes" to your Solution. To add this file Right Click on your website=> Click on "Add New Item" =>Choose "LINQ to SQL Classes" from the list. Rename the file as your wish(Extension should be .dbml). I renames it to "EmployeeClass.dbml".
Now, a new file will be added to your solution and two layout panels will open in your design surface.
Step-3: Drag your table from the Server Explorer in to the left layout.
Step-4: Add fields in your page as per your table columns. Though in my case I have three fields and from those three "EmployeeID" is Auto-generated. So I have to send two values(EmployeeName,Address). That's why I added two textboxes into my page and a button also.
Step-5: Add "using System.Linq;" namespace to your Page. Then,write the following lines in the Button's Click Event to send the values to database.
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        using (EmployeeClassDataContext context = new EmployeeClassDataContext())
        {
            EmpDetail details = new EmpDetail();
            details.Address = txtAddress.Text;
            details.EmployeeName = txtEmpName.Text;
            context.EmpDetails.InsertOnSubmit(details);
            context.SubmitChanges();
        }
    }


Step-6: Then, run your page and insert values you want to send to your database.
After inserting the values, when you click on the submit button, the values will be inserted into database.
Output:




Regards,
Prajanuranjan....


Friday 28 September 2012

How to compare two dates in "dd/MM/yyyy" format using CompareValidator in ASP.Net?

We usually don't get any error while comparing two date fields in "MM/dd/yyyy" format using CompareValidator. But, problem arises when the date fields are in "dd/MM/yyyy" format.
Suppose, we have a page where two textboxes are present(one for From Date and another for To Date) and a Button to submit the value. We are comparing the dates using a CompareValidator.
Source View:
<form id="form1" runat="server">
    <div>
        From Date :
        <asp:TextBox ID="txtFromDate" runat="server"></asp:TextBox>
    </div>
    <div>
        To Date :
        <asp:TextBox ID="txtToDate" runat="server"></asp:TextBox>
        <asp:CompareValidator ID="compDate" runat="server" ControlToValidate="txtToDate"
            ControlToCompare="txtFromDate" ErrorMessage="From date should be less than To
            date !" Operator="GreaterThanEqual" SetFocusOnError="true" Type="Date"> 
        </asp:CompareValidator>
    </div>
    <div>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    </div>
</form>
Design View:

Now, it will work properly if we are entering values in "MM/dd/yyyy" format. But, if we enter values in "dd/MM/yyyy" format and especially dates greater than 12, it won't work properly and will give wrong output.

To get rid out of this problem, you just need to change your Page Culture whose default date format is "dd/MM/yyyy". Here, I have changed the Culture to "en-GB" and it worked properly.
protected void Page_Load(object sender, EventArgs e)
{
        Page.Culture = "en-GB";
}

Output:


Regards,
Prajanuranjan....

Saturday 15 September 2012

How to convert a date in "dd/MM/yyyy" format to a DateTime variable "MM/dd/yyyy" format in ASP.Net?

Suppose, we have a date field (Let say "Joining Date") in dd/MM/yyyy and you want to convert it into  DateTime variable, then the following lines will help you to do so.

string DateofJoining = "25/08/2010";
System.Globalization.DateTimeFormatInfo dtformat
= new System.Globalization.DateTimeFormatInfo();
dtformat.ShortDatePattern = "dd/MM/yyyy";
DateTime dtJoiningDate = DateTime.Parse(FromDate, dtformat);

This will convert the string value into datetime("08/25/2012 12:00:00 AM").


Regards,
Prajanuranjan....

How to make a user to enter only numeric values in a textbox using Javascript ?

Suppose, you have a textbox where you want a user can enter only numerical values, then write the following script method inside the head section of your page.
 <script type="text/javascript">   

        function isNumberKey(evt) {
            var charCode = (evt.which) ? evt.which : event.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;
            return true;
        }       
    </script>

Then,call this method in the "onkeypress" event of your textbox.
<asp:TextBox ID="txtPhoneNo" runat="server" onkeypress="return isNumberKey(event)">
    </asp:TextBox>

Now, as a result the user can not enter any non-numeric value into that textbox.



Regards,
Prajanuranjan....

Friday 14 September 2012

How to Read Data from XML File in ASP.Net(Example-2)?

I have already discussed about reading data from XML File in my previous post(http://mydotnetcollections.blogspot.in/2012/09/how-to-read-data-from-xml-file-in.html). Here, I am showing another way of reading data from XML File.
Suppose we have an XML file "Customer.xml", whose values we want to read.

Step-1: Add a page to your solution and place a button in it.
<asp:Button ID="btnReadXML" runat="server" Text="Read XML"
            onclick="btnReadXML_Click" />
Step-2: Write these following lines in the Button's Click Event.

protected void btnReadXML_Click(object sender, EventArgs e)
    {
        XmlDataDocument doc = new XmlDataDocument();
        XmlNodeList nodes;
        int count = 0;
        string str = null;


As I have the XML File in my solution Folder itself. You can give your own path here.
 
        FileStream fs = new FileStream(Server.MapPath("Customer.xml"), FileMode.Open, FileAccess.Read);
        doc.Load(fs);
        nodes = doc.GetElementsByTagName("Customers");
        for (int i = 0; i < nodes.Count; i++)
        {
            nodes[i].ChildNodes.Item(0).InnerText.Trim();
            str = nodes[i].ChildNodes.Item(0).InnerText + "|" + nodes[i].ChildNodes.Item(1).InnerText.Trim();
            Response.Write(str+"<br/>");
        }
    }
Now, debug your page and click on the button to print the desired value.

Output: 

Regards,
Prajanuranjan....


How to Read Data from XML File in ASP.Net(Example-1) ?

Suppose we have an XML file "Customer.xml", whose values we want to read.

Step-1: Add a page to your solution and place a button in it.
<asp:Button ID="btnReadXML" runat="server" Text="Read XML"
            onclick="btnReadXML_Click" />


Step-2: Write these following lines in the Button's Click Event.
protected void btnReadXML_Click(object sender, EventArgs e)
    {
As I have the XML File in my solution Folder itself. You can give your own path here.
 
        XmlReader xml = XmlReader.Create(Server.MapPath("Customer.xml"), new XmlReaderSettings());
        DataSet dt = new DataSet();
        dt.ReadXml(xml);
        for (int i = 0; i < dt.Tables[0].Rows.Count; i++)
        {
            Response.Write(dt.Tables[0].Rows[i].ItemArray[2].ToString()+"<br/>");
        }
    }

If you debug the page and place a break point at the "dt.ReadXml(xml);", you can see that the DataSet is filled with the values present in the XML FIle.

Output: As we are sending only the Values of 3rd column(Customer Name") to the front, it will print only the customers Name.


Regards,
Prajanuranjan....


How to open a Div as a popup at the center of a page using JQuery ?

Let say we have a div "popup_div" which we want to open as a popup at the center of the page. We can do the same by following the below steps.
Step-1: Add a Div to your page which you want to open as popup and give it as id="popup_div".

<div id="popup_div">
            <div style="width: 99%; height: 20px; background-color: #303030; font-family:   
                 Calibri;font-size: 14px; font-weight: bold; color: White; padding-left: 8px;  
                 vertical-align: middle">View Chart</div>
</div>

Step-2: Add the CSS style to your div "popup_div". 

<style type="text/css">
        .div_popup_
        {
            display: none;
            position: fixed;
            _position: absolute;
            height: 320px;
            width: auto;
            background: #FFFFFF;
            z-index: 100;
            margin-left: 15px;
            border: 2px solid #999999;
            padding: 6px;
            font-size: 15px;
            -moz-box-shadow: 0 0 5px #ff0000;
            -webkit-box-shadow: 0 0 5px #ff0000;
        }
    </style>

<div id="popup_div" class="div_popup_">
            <div style="width: 99%; height: 20px; background-color: #303030; font-family
                 Calibri;font-size: 14px; font-weight: bold; color: White; padding-left: 8px;   
                 vertical-align: middle">View Chart</div>
</div>

Step-3: Add the following JQuery Function to your page which will open the div as popup that also at the center of the page.

function ShowPopUp() {
            $('#popup_div').fadeIn(500);
//-- The following line is to open at the center of the page --//
            $('#popup_div').css({ top: '50%', left: '50%', margin: '-' + ($('#popup_div').height() / 2) + 'px 0 0 -' + ($('#popup_div').width() / 2) + 'px' });

        };
Step-4: Call this method whenever you want to open the div.

Output: In my example I had to open a popup showing a chart. That's why I had placed a Chart control to the div and wrote all the codes to make a chart control. After that when I clicked the button to open the popup, the output was like the following.


Regards,
Prajanuranjan....


Tuesday 11 September 2012

How to generate XML File in ASP.Net from SQL Server(Example-2) ?

    I have already discussed about generating XML File from database in my previous article(http://mydotnetcollections.blogspot.in/2012/09/how-to-create-xml-file-from-sql-server.html). Now, I am discussing about generating XML File in another method.
Step-1: Create a Table(Customer) in your Database and add three columns(CustomerID ,Name, Address) to it.
Step-2: Insert some default values to it.

Step-3: Add a Page to your website for generating XML. Also add a button(GenerateXML) to the Page. Add a Namespace- "using System.Xml;".

Step-4: Write these following lines in the button's Click_Event.

protected void GenerateXML_Click(object sender, EventArgs e)
    {
        //***************** Retriving Customer Details From Database ********************//
        SqlConnection con = new SqlConnection("------Your Connection String------");
        SqlCommand com = new SqlCommand("select * from Customer", con);
        SqlDataAdapter da = new SqlDataAdapter(com);
        DataTable dt = new DataTable();
        dt.TableName = "Customers";
        da.Fill(dt);
        XmlTextWriter xml = new XmlTextWriter(Server.MapPath("Customer.xml"), System.Text.Encoding.UTF8);
        xml.WriteStartDocument(true);
        xml.Formatting = Formatting.Indented;
        xml.Indentation = 2;
        xml.WriteStartElement("Customer");
        foreach (DataRow dr in dt.Rows)
        {
            xml.WriteStartElement("CustomerDetails");
            xml.WriteStartElement("CustomerID");
            xml.WriteString(dr[0].ToString());
            xml.WriteEndElement();
            xml.WriteStartElement("Name");
            xml.WriteString(dr[1].ToString());
            xml.WriteEndElement();
            xml.WriteStartElement("Address");
            xml.WriteString(dr[2].ToString());
            xml.WriteEndElement();
            xml.WriteEndElement();
        }
        xml.WriteEndElement();
        xml.WriteEndDocument();
        xml.Close();
    }
Here, I have generated and stored the XML File in the Solution Folder itself. You can give your own Location for saving the generated XML File.
Step-5: Now, Run your webpage and Click the button to generate XML File. After that, an XML File ("Customer.xml") will be generated in your given Folder. In my case it will be stored in my Solution Folder.

The Customer.xml 





Regards,
Prajanuranjan.....

How to create XML File from SQL Server Database in ASP.Net(Example-1)?

In this example I am going to describe you how to generate an XML File in ASP.Net. Here, I am generating XML File of the Customer Details.
Step-1: Create a Table(Customer) in your Database and add three columns(CustomerID ,Name, Address) to it.
Step-2: Insert some default values to it.

Step-3: Add a Page to your website for generating XML. Also add a button(GenerateXML) to the Page. Add a Namespace- "using System.Xml;".

Step-4: Write these following lines in the button's Click_Event.

    protected void GenerateXML_Click(object sender, EventArgs e)
    {
        //************ Retriving Customer Details From Database **************//
        SqlConnection con = new SqlConnection("--------- Your Connection String -------");
        SqlCommand com = new SqlCommand("select * from Customer", con);
        SqlDataAdapter da = new SqlDataAdapter(com);
        DataTable dt = new DataTable();
        dt.TableName = "Customers";
        da.Fill(dt);
        //******************************************************************//
        dt.WriteXml(Server.MapPath("Customer.xml"));
    }

Here, I have generated and stored the XML File in the Solution Folder itself. You can give your own Location for saving the generated XML File.
Step-5: Now, Run your webpage and Click the button to generate XML File. After that, an XML File ("Customer.xml") will be generated in your given Folder. In my case it will be stored in my Solution Folder.

The Customer.xml 




Regards,
Prajanuranjan....


Total Pageviews