-->

Tuesday, June 3, 2014

How to create database table in entity framework windows form c#

I am very happy from entity framework, thanks to Microsoft. Through easy steps you can easily design database table in entity framework. These easy steps are:
Step-1 : Add entity framework package from package manager console.

Tools  --> Library Package Manager --> Package Manager Console

PM> install-package entityframework

Step-2 : First to create a class, which named as 'student'. This class work as database table in entity framework. like that

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsFormsApplication10
{
   public class Student
    {
        public int Id { get; set; }
        public string name { get; set; }
    }
}
Step-3 : Create a connection string in app.config file like

<connectionStrings>
    <add name="connectionstring1" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0; Initial Catalog=STUDENTer; Integrated Security=true" />
  </connectionStrings>

Step-4 :  Create an another class, which named as 'DataContext'. This class is inherited from DbContext base class and add student table in it.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace WindowsFormsApplication10
{
    class DataContext: DbContext
    {
        public DataContext() :
            base("connectionstring1")
        {
         

        }
        public DbSet<Student> Students { get; set; }

    }
}

Here DataContext class constructor call our base class constructor and pass the connection string , which is define in app.config file. Also add the student table in STUDENTer database.

Step-4 : Add new window form in our project , also create object of DataContext class in form constructor.

public Form1()
        {
            InitializeComponent();
            DataContext dc = new DataContext();
       
        }
Step-5 :  Create break point after DataContext Object.
Create break point after DataContext Object
table confirmation after count is zero


Step-6 : Run your application
How to create database table in entity framework windows form c#

Monday, June 2, 2014

How to get Visitor's IP in ASP.NET

In this article , we will learn how to get visitor's machine IP address and where we use it. Normally this types of query is generated for ptc sites because ptc sites take visitor's ip address in its database table then no buddy cheat with them. This article is very useful, where you establish intranet, through this you can easily determine call request. Here we have two parameters in ServerVariables that is 

HTTP_X_FORWARDED_FOR
REMOTE_ADDR 

In this article both keep different meaning, such as HTTP_X_FORWARDED_FOR parameter used where visitor behind the proxy server, now through this parameter you can easily get 
proxy server ip + client machine ip

Note : Suppose your visitor visit your site through proxy server ip address then you would not get actual ip address of the visitor , through this parameter you can get both (proxy + machine address) address.

REMOTE_ADDR parameter get the router or proxy server ip. Now take an simple example , but in this example we always get 127.0.0.1 because server and client machine are same.
 

Example 

Step-1 : Add Label and Button on webform
Step-2 : Raise click event 
Step-3 : Copy this code and paste into your click handler

Source 
<form id="form1" runat="server">
    <div>
    
        <asp:Label ID="Label1" runat="server"></asp:Label>
        <br />
    
    </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
        Text="Get Ip Address" />
    </form>

Code Behind

 protected void Button1_Click(object sender, EventArgs e)
    {
        string ip;
        ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (ip == "" || ip == null)
            ip = Request.ServerVariables["REMOTE_ADDR"];

        Label1.Text = ip;

    }

Code Generate the following output

How to get Visitor's IP in ASP.NET

Sunday, June 1, 2014

How to get cell value in selected row of DataGridView in windows form c#

If you want to get cell value from DataGridview then first to bind grid with data table with any data source. Now, use this code to retrieve the cell value.

Binding Data 

 private void binddata()
        {
            con.Open();
            cmd.CommandText = "select * from [student_record]";
            cmd.Connection = con;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            dataGridView1.DataSource = ds;
            dataGridView1.DataMember = ds.Tables[0].ToString ();
           
        }

Get cell value on message box

  private void button1_Click(object sender, EventArgs e)
        {
            string name = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
            MessageBox.Show(name);

        }

Code generate the following output

How to get cell value in selected row of DataGridView in windows form c#

Saturday, May 31, 2014

How to validate fileupload control in asp.net also choose selected format

In my previous article we already discussed about file upload control. Suppose your picture is required in the form of registration then you must to validate the file upload control. Also you want to take only jpeg, gif and selected format then should use RegularExpressionValidator with regular expression. Now lets take a simple example.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>dotptogramming</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:FileUpload ID="fileUpload1" runat="server" Width="280px" />
                                
<asp:RequiredFieldValidator ID="R1" runat="server" 
            ErrorMessage="Select File From File Upload" Text="*"  ValidationGroup="v2" 
            ControlToValidate="fileUpload1" ForeColor="Red"></asp:RequiredFieldValidator>

<asp:RegularExpressionValidator ID="RE1" runat="server" 
            ErrorMessage="Upload .jpg, .jpeg, .gif files only." Text="*"  
            ValidationGroup="v2" ControlToValidate="fileUpload1" 
            ValidationExpression="^.+\.((jpg)|(jpeg)|(gif))$" ForeColor="Red"></asp:RegularExpressionValidator>

    </div>
    <p>

        <asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="v2"/>
    </p>
    <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
        ValidationGroup="v2" ForeColor="Red" />
    </form>
</body>
</html>

Code Generate the following output

How to validate fileupload control in asp.net also choose selected format

How to validate fileupload control in asp.net also choose selected format

How to pass session value in page title in asp.net

Suppose you have to enter into your account. Now, a session variable created after login and you want to pass this value in page title. If you have a master page then simple use this code in code behind page. Also you can use this code in web form. Lets take a simple example

Use only Business Logic code


public partial class Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["username"] = "- ASP.NET CODE";
        Page.Title += Session["username"].ToString();
    }
} 

Code Generate the following Output

How to pass session value in page title in asp.net

Dynamically add rows and columns in data table, also bind Gridview with data table

First create instance of DataTable class, which is inside in System.Data namespace. After that you make columns and rows inside the DataTable. First create columns with their data type also insert rows data in it.

Source Code

<div>
        <asp:GridView ID="GridView1" runat="server">
        <HeaderStyle BackColor ="Green" ForeColor ="Orange" />
        <RowStyle BackColor ="Black" ForeColor ="White" />

        </asp:GridView><br />

        <asp:Button ID="B1" runat="server" Text="Bind GridView" onclick="B1_Click" />
    
    </div>

Business Logic Code

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

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


    protected void B1_Click(object sender, EventArgs e)
    {
  
DataTable datatable = new DataTable();
datatable.Columns.Add("serial Number", typeof(Int32));
datatable.Columns.Add("Name", typeof(string));
datatable.Columns.Add("Address", typeof(string));
datatable.Rows.Add(1, "Jacob", "USA");
datatable.Rows.Add(2, "Lefore", "USA");
datatable.Rows.Add(3, "Bill", "UK");
datatable.Rows.Add(4, "Smith", "UK");
GridView1 .DataSource =datatable;
            GridView1.DataBind ();

    }
}

Code Generate the following Output

Dynamically add rows and columns in data table, also bind Gridview with data table

Friday, May 30, 2014

How to call event in page load method and example of EventHandler class

If you want to add event at run time like click event in page load method. For this types of problem you can use EventHandler class. Create a object of this class also pass new method as a parameter.

Source Code

<div>
    
        <asp:Button ID="B1" runat="server" CommandName="Add" Text="Button" />
    
    </div>

    Business Code


    public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        B1.Click += new System.EventHandler(this.calculate);
    }
    protected void calculate(object sender, System.EventArgs e)
    {
        switch (((Button)sender).CommandName)
        {
            case "Add": Response.Write("hello");
                break;
        }
    }

}
Code Generate the following output
How to call event in page load method and example of EventHandler class
© Copyright 2013 Computer Programming | All Right Reserved