-->

Tuesday, January 12, 2016

ASP.NET C# add Multiple table into DataSet

In this article, I will show you, How to add multiple Database tables in DataSet. I write many articles on DataSet. We all know that we can store multiple Database Table in it. To do this task, first of all add two Gridview control on web form, now your web form look like :

Source Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="addmultipletable.aspx.cs" Inherits="addmultipletable" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <br />
        <asp:GridView ID="GridView2" runat="server">
        </asp:GridView>

    </div>
    </form>
</body>
</html>

Here, I am using two Gridview control. Both are bind with different tables. Actually i am retriving two tables using SQL Query. For the binding we are using two class i.e SqlConnection and SqlCommand.

Code Behind File

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class addmultipletable : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        bindgrid();
       //bindsecondgrid();
    }

    private void bindgrid()
    {
        string query="select * from [user_table]";
        query +="select * from [customer]";
        SqlConnection con = new SqlConnection();
        con.ConnectionString=ConfigurationManager.ConnectionStrings["ConnectionStringtr"].ToString();
        con.Open();
        SqlCommand cmd=new SqlCommand();
        cmd.CommandText =query;
        cmd.Connection=con;
        DataSet ds=new DataSet();
        SqlDataAdapter da=new SqlDataAdapter(cmd);
        da.Fill(ds);
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
        GridView2.DataSource = ds.Tables[1];
        GridView2.DataBind();
      //  throw new NotImplementedException();
    }
}

Sunday, January 10, 2016

Change System date Format using c#

If you want to change Your system date format using c# then you must to use RegistryKey class. This class is available in Microsoft.Win32 namespace. By using this class you can change the short and long date format, Before any changes the Date format look like.

Change System date Format using c#

Now, after the code you can change the Date format:

using Microsoft.Win32;

private void button1_Click(object sender, EventArgs e)
        {
            RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"Control Panel\International", true);
            regkey.SetValue("sShortDate", "10/12/87");
            regkey.SetValue("sLongDate", "10/12/87");
        }

Customized Date Format

Friday, January 8, 2016

Export DataGridView to Excel using OpenXML and ClosedXML

In this article, I will explain you, How to export data of DataGridView to Excel file. In this article, I will use OpenXML and ClosedXml libraries for export data. We can also export data of DataGridView using Foreach loop by fetching each row of it. To do this task, first of all Download two assemblies i.e :

  1. Open XML SDK 2.0 For Microsoft Office 
  2. Closed XML

Now, Add windows form into your project. Add a DataGridView and single button on it.

using System;
using System.Windows.Forms;
using System.IO;
using System.Data;
using System.Reflection;
using ClosedXML.Excel;

namespace Export_DataTable_Excel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.BindData();
        }

        private void BindData()
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("StudentId", typeof(int)),
            new DataColumn("StudentName", typeof(string)),
            new DataColumn("StudentCity",typeof(string)) });
            dt.Rows.Add(1, "Jacob lefore", "US");
            dt.Rows.Add(2, "Ammey smith", "UK");
            dt.Rows.Add(3, "Bill Smith", "Fr");
            dt.Rows.Add(4, "Robert", "Ru");
            this.dataGridView1.DataSource = dt;
        }

        private void ExportExcel_Click(object sender, EventArgs e)
        {
     
            DataTable dt = new DataTable();

 
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                dt.Columns.Add(column.HeaderText, column.ValueType);
            }

   
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                dt.Rows.Add();
                foreach (DataGridViewCell cell in row.Cells)
                {
                    dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
                }
            }

            //Exporting to Excel
            string folderPath = "C:\\my\\";
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            using (XLWorkbook xlfile = new XLWorkbook())
            {
               xlfile.Worksheets.Add(dt, "students");
               xlfile.SaveAs(folderPath + "data.xlsx");
            }
        }
    }
}

Code Generates the following output

Export DataGridView to Excel using OpenXML and ClosedXML

Program x to power y in C Language

Introduction 

The meaning of x to the power of y is , a variable x is multiply for y time. Lets take a simple example a variable x is hold 2 and y hold 5. Now the answer is 2 multiply for 5 times such as..
z=2*2*2*2*2;
z=32

Method-1: 

Design a Algorithm in c

Step-1 : Take two value in variable x and y by user input.
Step-2 :  Use pow function in  "C" , which is available in math.h header file.
Step-3 :  Take another variable Z for holding answer of the x to the power of y.
Step-4 : Print z 
Step-5 : End of the program.

Program :

#include<conio.h>
#include<stdio.h>
#include<math.h>
void main()
{
int x,y,z;
printf("enter X value");
scanf("%d",&x);
printf("Enter Y value");
scanf("%d",&y);
z=pow(x,y);
printf("output of the x power y is%d",z);
getch();
}

Output
Program x to power y in C


Method-2 : Using recursion

Algorithm of the program

Step-1: Step-1 : Take two value in variable x and y by user input.
Step-2: Create a function  and pass values of x and y  to the function.
Step-3 : Call same function for y times 
Step-4 : Return function 

Program

#include<conio.h>
#include<stdio.h>
#include<math.h>
void main()
{
int x,y,z;
clrscr();
printf("enter X value");
scanf("%d",&x);
printf("Enter Y value");
scanf("%d",&y);
z=fun(x,y);
printf("output of the x power y is%d",z);
getch();
}
int fun(int a,int b)
{
if(b>=1)
{
return a*fun(a,--b);
}
else
return 1;
}




Output
Program x to power y in C

Method -3:Using third variable

Algorithm:
Step-1: Take two value in variable x and y by user input.
Step-2: Run for loop for y times.
Step-3 : Take third variable z with 1 value
Step-4 : Multiply x with z for y times in for loop
Step-5 : Take output value in z variable
Step-6 :  End of the program

Program


#include<conio.h>
#include<stdio.h>
#include<math.h>
void main()
{
int x,y,i,z=1;
clrscr();
printf("enter X value");
scanf("%d",&x);
printf("Enter Y value");
scanf("%d",&y);
for(i=0;i<y;i++)
{
z=x*z;
}
printf("output of the x power y is%d",z);
getch();
}

Output

Program x to power y in C

Structure of a C program

The structure of a C program is nothing but the way of framing the group of statements while writing a C program. We put the general structure of a C program first as shown below:

[preprocessor directives]
[global declarations]

returning_type main( )
{
[Declaration Section (local)]

[Executable Section]
}

[User defined functions]

Note : The bold faced characters such as main( ) in one line along with the left parenthesis '(' and the right parenthesis ')' should be typed as they are. The Declaration section and Executable section enclosed within '{' and '}' is called the body of the main function. The data or value returned by the function main( ) is indicated by' returning_type'. Normally main( ) doesn't return any value. So, the returning type void is used. The function main( ) can be preceded by global declarations and preprocessor directives.





Preprocessor directives : The preprocessor statements starts with '#' symbol. These statements instruct the compiler to include the specified file in the beginning of the program. One important point about preprocessor directives is that these statements are never terminated by ';' for example,


#include<stdio.h>  /* Only one file is permitted for one #include */
#include<math.h>


are the files that the compiler includes into the user program. These two files "stdio.h" and "math.h" are called header files and hence the extension '.h' . Using the preprocessor directive the user can define the constant. For example,

#define SIZE 100 /*Only one constant can be defined using one #define */
#define N 50
Here , Size and N are called symbolic constants. Their value is not changed during program execution.

Global declarations: The variables that are declared before all the functions are called global variables. All the functions can access these variables. By default the global variables are initialized with '0'.
main( ) : Each and every C program should have a function main( ) and there should be one and only one function by name 'main( )' . This function is always executable first. The function main( ) may call other functions. The statements enclosed within left and right curly braces are called body of the function main( ).

Declaration section : The local variables that are to be used in the function main( ) should be declared in the declaration section. The variables declared are identified as identifiers by the C compiler. The variables can also be initialized. For example, consider the declarations shown below:


int sum=0 ; /* The declared variables is initialized to 0 */
int a;           /* The declared variable contains garbage(unwanted) value */
float b,c,d;  /* More than one variables can be declared by single statements */

Executable section : This section contains the building blocks of the program. The blocks containing executable statements represent the directions given to the processor to perform the task. A statements may represent an expression to be evaluated, input/output operation , assignment operation, etc. The statements may be even control statements such as if statements , for statement , while statement,do-while statement,etc. Each executable statement of a block should end with a ';' .The symbol ';' is also called as statement terminated or separator.

User defined functions: This is the last optional section of the program structure. The functions written by the user to perform particular or special task are called defined functions. These are called as sub-programs. the basic structure of the user defined function resembles that of the function main( ).

Now, let us write a small program to display the message " dotprogramming":
#include <stdio.h>
main( )
{
printf("dotprogramming");
}

Principles of Programming in C language

Introduction to Programming
Remember your last visit to the super market. You might have purchased many items. What did you do after picking all the items and putting them into the carriage? Probably you met with the billing clerk to make the payment. Have you observed his way of preparing the bill? He picks the items one by one and enters something into the computer repeating the same task for all the items.
Within a count of few minutes or even may be within few seconds he gives the bill , you pay and come out carrying all the required things. So what made him to process the bill so fast? It is nothing but the “program” running in the computer’s memory. If you want to become a billing clerk, then what is needed is to just learn the method to use the program that helps in the billing the items.
Stop, don’t think in that way. You should dream something high! To design a program that helps the billing clerks to prepare the bill fast and in a most efficient way.

Program Concept
By and large computers are used either to run the designed programs or to design the program itself. As an upcoming programmer you are going to use the computer to design the programs. That should be your main dream and aim. Keeping that in mind, let us see “what is program?”
Definition:  A program, strictly, a computer program is a collection of coded instructions to direct a computer to perform a desired set of operations. So, coding the instructions to make a program is an art. This art of making or designing a program is called programming. The person who writes such programs is called programmer.

Another definition of program:

Algorithm + Data Structure = Program

Definition : A program can be defined as the combination or clubbing of algorithm and data structure together into single unit. Here the algorithm refers to the procedure containing primitive steps to solve a particular task. A primitive step implies an easily understandable one. Data structure refer to the modeling of the required data to solve the task.

A programmer can design the program as per the customer's needs. The customer's need is collected as problem . The problem is analyzed to arrived at a solution. This solution provided using certain tools is called program. Whenever a problem arises , the programmer can design a program. The designed program can also be used to solve some related problems with the little modification. Changes is the nature! The new demands, requirements , etc. rise as the time passes. The programmer should react properly to these and should come out with a new solution from the existing solutions. Such existing solutions along with the new solution frame a program library. Now, let us see " what is program library?"

Definition: A library , a store or collection of computer programs is called program library . Each and every program in the library is designed to solve a certain type of problem.

What is canned program?

Definition: A program in a library of computer programs is called canned program. Existence of libraries of programs that are easy to use and designed to solve very general problems is important. The Turbo C compiler, you are going to learn, is the best example that contains many canned programs.
Turbo C compiler container many small programs in the form of built-in-functions contained in header tiles. With the help of such canned programs you can become a very good programmer. So, you should practice using such canned programs. Such canned programs are designed and added to the library. The canned programs are established and maintained by various computer manufacturers and centers.
For example, you will use a function scanf ( ) to read the input for almost all the programs you write and learn throughout the learning of this course. Similarly, you will use printf ( ) to display the messages and values or data on the output screen. Using such library functions or canned programs you build your own programs to solve general purpose or system-oriented problems. These two functions are canned in a header file “stdio.h”.
The C language that you are learning, contains nearly 27 such header files to design a program. All the header files inclusively contain hundreds of built-in functions. The header file “stdio.h” contains 56 built-in functions to solve many problems related to input and output operations. The following list provides a rough idea of number of built-in functions available in C:
“stdio.h” - 56, “conio.h”- 29,
“stdlib.h” - 42, “string.h” - 37,
“math.h” - 30, “ctype.h” - 17, etc.

Thursday, January 7, 2016

Text to Image Conversion in ASP.NET C#

In this article, I will show you how to convert Text into image. I will take text from TextBoxes and convert it into image using Graphics class. Generated image will be show on image control. I have an example of it.  First of all add one TextBox, One Button and One image control on web form.



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="texttoimage.aspx.cs" Inherits="texttoimage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        Enter Name :
        <asp:TextBox ID="TextBox1" runat="server" Width="192px"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Text 2 Image" />

    </div>
        <p>
            <asp:Image ID="Image1" runat="server" Height="178px" Visible="False" Width="315px" />
        </p>
    </form>
</body>
</html>

By using DrawString ( ) method we can put Text on image. There are following parameter which are put into this method:
Text = Which is taken from textBox.
Font  = Font, it means Font family, Font Size, Font style, font unit etc. You can add all these properties by using Font class.

By using the Bitmap class we can create Image. In it we have two parameters i.e width and height.


Code Behind Code

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class texttoimage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string textboxtext = TextBox1.Text.Trim();
        Bitmap bitmap = new Bitmap(1, 1);
        Font font = new Font("Arial", 20, FontStyle.Regular, GraphicsUnit.Pixel);
        Graphics grap = Graphics.FromImage(bitmap);
        int width = (int)grap.MeasureString(textboxtext, font).Width;
        int height = (int)grap.MeasureString(textboxtext, font).Height;
        bitmap = new Bitmap(bitmap, new Size(width, height));
        grap = Graphics.FromImage(bitmap);
        grap.Clear(Color.White);
        grap.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        grap.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        grap.DrawString(textboxtext, font, new SolidBrush(Color.FromArgb(255, 1, 1)), 0, 0);
        grap.Flush();
        grap.Dispose();

        string savefile = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".jpg";
        bitmap.Save(Server.MapPath("~/img/") + savefile, ImageFormat.Jpeg);
        Image1.ImageUrl = "~/img/" + savefile;
        Image1.Visible = true;





    }
}
© Copyright 2013 Computer Programming | All Right Reserved