-->

Tuesday, February 6, 2018

Step By Step Guide to use WebAPI in ASP.NET CORE WebApplication

If you have to completed your WebAPI then must to know , how to use it in web application.  Now , you can see , how to use WebAPI in WebApplication.

WEBAPI Project
Step-1 :   Create Model first
public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Step-2 :  Create Data Context Class

public class Context : DbContext
    {
        public Context(DbContextOptions<Context> options) : base(options)
        {

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

    }

Step-3 :  Add Connection String into your Application Setting File

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-6550C064-027F-4939-822B-5B4620D08657;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Step-4 :  Add Connection String in Startup file

  services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


Step-5 Do Migration 
Step-6 :  Create Controller 

namespace WebApiTestApplication.Controllers
{
    [Route("api/[controller]")]
    public class StudentController : Controller
    {
        private Context _context;
        public StudentController(Context context)
        {
            _context = context;
        }
        [HttpGet]
        public List<Student> Get()
        {
            return _context.Students.ToList();
        }

        public IActionResult Index()
        {
            return View();
        }
    }}

Step- 7: Add new project Web Application in the same solution
Step-8 : Add Helper Class  also add View Model class

namespace WebApplication1.Helper
{
    public class StudentAPI
    {
        public HttpClient Initial()
        {
            var Client = new HttpClient();
            Client.BaseAddress = new Uri("http://localhost:56562/");
            return Client;
        }
    }

}

If you Know what is "56562" then must to watch the video

And the model class

namespace WebApiTestApplication.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Step-9 :  Add A controller

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        StudentAPI _api = new StudentAPI();

        public async Task<IActionResult> Index()
        {
            List<Student> student = new List<Student>();
            HttpClient client = _api.Initial();
            HttpResponseMessage res = await client.GetAsync("api/Student");
            if (res.IsSuccessStatusCode)
            {
                var result = res.Content.ReadAsStringAsync().Result;
                student = JsonConvert.DeserializeObject<List<Student>>(result);
            }
         
            return View(student);
        }


    }
}

Step-10  : Generate View as list type 

@model IEnumerable<WebApiTestApplication.Models.Student>

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Id)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
            </td>
        </tr>
}
    </tbody>
</table>



Wednesday, June 15, 2016

How to use FileUpload Control in ASP.NET

Introduction
The FileUpload control displays a text box control and a browse button that enable users to browse a file from the local or remote machine to upload it on the Web server. You can upload a file on the Web Server by specifying the full path of the file to be uploaded (for example D:\Myfiles\Test.txt) in the textbox of this control . Alternatively , you can select the file by clicking the browse button , and then locating it in the Choose File dialog box.

Top Related article


  1. Fileupload control enable disable programmatically in ASP.NET
  2. Programmatically change border color of fileupload control in ASP.NET
  3. Programmatically change background color of fileupload control in ASP.NET
  4. How to validate fileupload control in asp.net also choose selected format
  5. How to insert image into database using file upload control


Public Properties of the FileUpload Class
FileBytes : Obtains an array of the bytes in a file that is specified by using a FileUpload control

FileContent : Obtains a Stream object that points to a file to upload using the FileUpload control.

FileName : Obtains the name of a file on a client to upload using the FileUpload control.

HasFile : Obtains a value indicating whether the FileUpload control contains a file.

PostedFile : Obtains the underlying HttpPostedFile object for a file that is uploaded by using the FileUpload control.

Public Method of the FileUpload Class
SaveAs : Saves the data of an uploaded file to a specified path on the web server.

Example of FileUpload control in ASP.NET

<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            FileUpload1.SaveAs(Server.MapPath("~/images/" + FileUpload1.FileName));
        }
        else
        {
            emptyupload.Text = "Choose your file"; 
        }
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1 {
            font-size: larger;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div class="auto-style1">
   
        <strong>Pick Your file from file upload control<br />
        </strong>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save" />   
        <br />
        <asp:Label ID="emptyupload" runat="server"></asp:Label>   
    </div>
    </form>
</body>
</html>
Output
Example of file upload control in asp.net

Example of file upload control

Only GIF image support by FileUpload control   


<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {        string extn=string.Empty ;
        if (FileUpload1.HasFile)
        {
            extn = System.IO.Path.GetExtension(FileUpload1.FileName);
            if ("gif" == extn)
            {
                FileUpload1.SaveAs(Server.MapPath("~/images/" + FileUpload1.FileName));
                emptyupload.Text = "Save sucessfully";
            }
            else
            {
                emptyupload.Text = "only gif support";
            }
        }
        else
        {
            emptyupload.Text = "Choose your file"; 
        }
    }
</script>
Note : GetExtension is the method of the path class which is detect extension of the filename.

Multiple File Upload control on Same Page

This is the new features comes into the DOTNET Framework 3.5. If you have three or more file upload control on same page then what to do for save files into project directory. If you use traditional code like
if(fileupload1.hasfile)
{
//code)}
if(fileupload2.hasfile)
{
//code
}
This is the wrong for developer perspective. You can use new features of DOTNET Framework 3.5 i.e HttpFileCollection class.  By using Request.Files property you can get the files from the server.
Check the simple example of it.


Source Code:

 <div>
 
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <asp:FileUpload ID="FileUpload2" runat="server" />
        <br />
        <asp:FileUpload ID="FileUpload3" runat="server" />
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
 
    </div>
  protected void Button1_Click(object sender, EventArgs e)
    {
        string filepath = "E:\\Upload";
        HttpFileCollection hfc = Request.Files;
        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            try
            {
                if (hpf.ContentLength>0)
                {
                    Label1.Text += "File Content Type: " + hpf.ContentType+"<br/>";
                    Label1.Text += "File Size: " + hpf.ContentLength + "<br/>";
                    Label1.Text += "File Name: " + hpf.FileName + "<br/>";
                    hpf.SaveAs(filepath + "\\" + System.IO.Path.GetFileName(hpf.FileName));
                    Label1.Text += "Location of the file: " + filepath + "\\" + System.IO.Path.GetFileName(hpf.FileName);
                 
                }
            }
            catch (Exception ex)
            {

                Label1.Text += "Error: " + ex.Message;
            }
        }

    }
Code Generate the following output:

Multiple File Upload control on Same Page

Monday, June 13, 2016

ASP.NET Searching Data using SqlDataSource Control

In this article, i will show you, How to search data from database table using SqlDataSource control. Visual Studio SqlDataSource control have inbuilt many functionality to make dynamic application. By using SqlDataSource control you can do different types of functionality like Sorting, Searching, Insert, Update, Delete data. In this article i will show you an example of searching/filtering data from database table. So first of Design a Database table using Sql Server Explorer. Now, you can take  three tuples in it. I have a Database table schema, you can check.

Search Data From Database table using SqlDataSource Control:

1. First to add one TextBox, One Button and a GridView control in a page.
2. By using Show Smart tag you can configure your GridView Control with the database table using SqlDataSource control.
3. When you configure your SqlDataSource control please check the Where clause button. In it you can select Field name, which is used to searching. Operator is "=" and parameter is control.  
4. You can Run your Web Site.

The Complete Source Code:

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

<!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"></asp:TextBox>
        <br />
   
    </div>
        <asp:Button ID="Button1" runat="server" Text="Search Student Details" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="StudentId" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="StudentId" InsertVisible="False" ReadOnly="True" SortExpression="StudentId" />
                <asp:BoundField DataField="StudentName" HeaderText="StudentName" SortExpression="StudentName" />
                <asp:BoundField DataField="StudentCity" HeaderText="StudentCity" SortExpression="StudentCity" />
            </Columns>
        </asp:GridView>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Student] WHERE ([StudentName] = @StudentName)">
            <SelectParameters>
                <asp:ControlParameter ControlID="TextBox1" Name="StudentName" PropertyName="Text" Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>

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

Code Generate the Following output:

ASP.NET Searching Data using SqlDataSource Control

Tuesday, May 24, 2016

Import Export project in ASP.NET C#

Project Introduction:

In this project, we have some modules, which is related to Import and Export goods services. This project provides online facilities to pickup your goods from any where in the nation. Actually projects is based on packers and movers functionality. Lots of goods transport one place to another place. We all know about import and export. Suppose, you want to bring goods from other places and that place is far from you place. So , you face too much difficulties. So, i design a packer and mover based project in ASP.NET C#.

Project modules

Project contains lots of things which is related to customer as well as company who pick up goods. So i dived the project in different categories, categories further divided in sub categories.
Module:
  1. User Module (Who Generate pick up request)
  2. Branch Module(Who handle pick up request , i am taking state level branch module)
  3. Agent Module (Who deliever the goods)
  4. Admin (Who handle all such functionality)

Software Requirement of the project : Visual Studio 2013

Front-End and Back End of the project : 

Front-End  : ASP.NET C# ( Here c# work as business logic code)
Back-End : Sql Server 

Project Video :



How to Download the Project:

Mail Me  : narenkumar851@gmail.com 

Sunday, May 22, 2016

How to use ImageMap Control in ASP.NET

Introduction

An image map is a picture on a webpage that provides various links , called hotspots, to navigate to other web pages , depending on the place where the user click (on single image). Web Designer frequently use image maps in their websites . An image map can be included in your web page by using the ImageMap Control.

An ImageMap control exists within the System.Web.UI.WebControls namespace. Image maps are often real maps; for example , you can display the map of the USA and define hotspot regions for each of its state and then navigate to the corresponding page containing the information for the selected state.


Public Properties of the ImageMap Class
Enable : Obtains or sets a value indicating whether the control can respond to user interaction.

HotSpotMode : Obtains or sets the default behavior for the HotSpot objects of an ImageMap control when the HotSpot objects are clicked.

HotSpots : Obtains or sets a group of HotSpot objects that represents the defined hotspot regions in an ImageMap Control.

Target : Obtains or sets the target window to show the Web page content when the ImageMap control is clicked.

Public Event of the ImageMap Class
Click : Occurs when a HotSpot object in an ImageMap control is clicked.
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
            <asp:ImageMap ID="ImageMap1" runat="server" Height="227px" HotSpotMode="Navigate" ImageUrl="~/imagemap.jpg" Width="227px">
            <asp:RectangleHotSpot HotSpotMode="Navigate" Left="10" NavigateUrl="http://www.google.com" Top="100" />
            <asp:RectangleHotSpot HotSpotMode="Navigate" Left="3" NavigateUrl="http://www.microsoft.com" Top="200" />
        </asp:ImageMap>
   
    </div>
    </form>
</body>
</html>
Output
hotspot

Saturday, May 21, 2016

How to Bind Hyperlink control in datalist in asp.net

Datalist introduction
The Datalist control is a data bound control that displays data by using templates. These templates define controls and HTML elements that should be displayed for an item. The Datalist control exists within the System.Web.UI.WebControl namespace.

Related topics



Some steps for binding Hyperlink control in Datalist

Step-1: Create a DataBase Table with  following fields.


Step-2: Fill this field with following values 

DepartmentID           Name                 Description
1                                  IT                     This is first department Name
2                                  CS                    This is Second Department Name


Step-3 : Create Procedure for retrieving values.

Database.mdf-->Stored Procedures -->Right click -->Add new Stored Procedure

CREATE PROCEDURE GetDepartments
AS
SELECT DepartmentID ,Name ,Description From [Table] ;

RETURN 0

Step-4: Take  a webform in your project name as "Departmentlist.aspx"
Step-5:  Paste this code into your Department.aspx





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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:DataList ID="DataList1" runat="server">
            <HeaderTemplate>
                Choose a Department
            </HeaderTemplate>
            <ItemTemplate>
                <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl ='<%#Link .ToDepartment (Eval ("DepartmentID").ToString ()) %>'
                  Text ='<%# HttpUtility .HtmlEncode (Eval ("Name").ToString ()) %>' ToolTip ='<%# HttpUtility .HtmlEncode (Eval ("Description").ToString ()) %>'   >

                </asp:HyperLink>
            </ItemTemplate>
        </asp:DataList>
    <div>
    
    </div>
    </form>
</body>
</html>

Step-6: Paste this code into your codebehind file


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


public partial class Departmentlist : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True";
            con.Open ();
        SqlCommand cmd=new SqlCommand ();
        cmd.CommandText ="GetDepartments";
        cmd.CommandType =CommandType .StoredProcedure ;
        cmd.Connection =con;
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds, "Department");
        DataList1.DataSource = ds;
        DataList1.DataBind();



    }
}

Step-7 Make a Link class for absolute url


using System;
using System.Web;

/// <summary>
/// Summary description for Link
/// </summary>
public class Link
{
    public static string BuildAbsolute(string relativeuri)
    {
        // get current uri
        Uri uri = HttpContext.Current.Request.Url;
        // build absolute path
        string app = HttpContext.Current.Request.ApplicationPath;
        if (!app.EndsWith("/"))
               
            app += "/";
        relativeuri = relativeuri.TrimStart('/');
        // return the absolute path
        return HttpUtility .UrlPathEncode (String .Format ("http://{0}:{1}{2}",uri .Host ,uri.Port ,app ));

 

    }
    public static string ToDepartment(string departmentId, string page)
    {
        if (page == "1")
     
            return BuildAbsolute(string.Format("catalog.aspx?DepartmentID={0}", departmentId));
        else
            return BuildAbsolute (string .Format ("catalog.aspx?DepartmentID={0}&Page={1}",departmentId,page ));
           

    }
    //generate a department url for the first page
    public static string ToDepartment(string departmentId)
    {
        return ToDepartment(departmentId, "1");
    }

 
}


Out Put 

Friday, May 20, 2016

Pager Template in FormView Example of ASP.NET C#

In this article i will show you, How to customize paging of FormView using pager template. By using pager template we can changed the structure of paging. I will give you an example of pager template. In this example i will show you, How to prepare paging structure in FormView, after preparing the structure of Edit Item template and Item Template , you can put the structure of pager template. In this example, pager template contain two link button with CommandName and CommandArgument. In CommandName we have single value for both control i.e Page, But CommandArgument contain value i.e "Prev" and "Next". Both CommandArguments are used for specific purpose. I will show you DataBound event, In this, we have pager template information.



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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
        <asp:FormView  ID="FormView1" runat="server" DataKeyNames="Id" AllowPaging="True" OnDataBound="FormView1_DataBound" OnPageIndexChanging="FormView1_PageIndexChanging">
            <EditItemTemplate>
                Id:
                <asp:Label ID="IdLabel1" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                Name:
                <asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
                <br />
                <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
                &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </EditItemTemplate>
            <InsertItemTemplate>
                Id:
                <asp:TextBox ID="IdTextBox" runat="server" Text='<%# Bind("Id") %>' />
                <br />
                Name:
                <asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
                <br />
                <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Insert" />
                &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </InsertItemTemplate>
            <ItemTemplate>
                Id:
                <asp:Label ID="IdLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                Name:
                <asp:Label ID="NameLabel" runat="server" Text='<%# Bind("Name") %>' />
                <br />

                <asp:LinkButton ID="LinkButton3" runat="server" CommandName="Edit">Edit</asp:LinkButton>
                <br />

            </ItemTemplate>
             
            <PagerTemplate>
                <table>
                    <tr>
                        <td>
                            <asp:LinkButton ID="LinkButton1" runat="server" Text="Previous" CommandName="Page" CommandArgument="Prev"/>
                            <asp:LinkButton ID="LinkButton2" runat="server" Text="Next" CommandName="Page" CommandArgument="Next"/>
                        </td>
                        
                        <td>
                          Page No  <asp:Label ID="l1" runat="server"/>
                           Total Page <asp:Label ID="l2" runat="server"/>
                        </td>

                    </tr>


                </table>


            </PagerTemplate>
            <PagerSettings Mode="NextPrevious" Position="Bottom" />



        </asp:FormView>
       
    </form>
</body>
</html>

Code Behind page

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 Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            formviewload();
        }
    }

    private void formviewload()
    {
        //throw new NotImplementedException();
        SqlConnection con = new SqlConnection();
        con.ConnectionString =ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        con.Open();
        SqlCommand cmd= new SqlCommand();
        cmd.CommandText ="select * from [Employee]";
        cmd.Connection =con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        FormView1.DataSource =ds;
        FormView1.DataBind();

    }
    protected void FormView1_DataBound(object sender, EventArgs e)
    {
        FormViewRow pagerrow = FormView1.BottomPagerRow;
        Label pageno = (Label)pagerrow.Cells[0].FindControl("l1");
        Label totalpage = (Label)pagerrow.Cells[0].FindControl("l2");
        if ((pageno!=null) && (totalpage!=null))
        {
            int pagen = FormView1.PageIndex +1;
            int total = FormView1.PageCount;
            pageno.Text = pagen.ToString();
            totalpage.Text = total.ToString();

        }
    }
    protected void FormView1_PageIndexChanging(object sender, FormViewPageEventArgs e)
    {
        FormView1.PageIndex = e.NewPageIndex;
        formviewload();

    }
}

Code generates the following output

Pager Template in FormView Example of ASP.NET C#


Monday, May 9, 2016

How to Design Country, State, and City DropDownList using SqlDataSource

In this article i will show you, How to bind Dropdownlist with the Country, State and City table using SqlDataSource. We all that If among tables are related to each other then we can show among tables one by one on indexChanged event. So, First of all design tables following ways:

[CountryTable]
CountryId  int primary_key Identity(1,1)
Country_Name nvarchar(100)

[State]
StateId int primary_key Identity(1,1)
State_Name nvarchar(100)
CountryId int

[City]
CityId int primary_key Identity(1,1)
City_Name nvarchar(100)
StateId int


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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        Select Country :
        <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="CountryName" DataValueField="CountryId" Height="19px" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" Width="150px">
            <asp:ListItem Value="0">Select</asp:ListItem>
        </asp:DropDownList>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Country]"></asp:SqlDataSource>
        <br />
        <br />
        Select State :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="SqlDataSource2" DataTextField="StateName" DataValueField="StateId" Height="19px" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" Width="150px">
            <asp:ListItem Value="0">Select</asp:ListItem>
        </asp:DropDownList>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [State] WHERE ([CountryId] = @CountryId)">
            <SelectParameters>
                <asp:ControlParameter ControlID="DropDownList1" Name="CountryId" PropertyName="SelectedValue" Type="Int32" />
            </SelectParameters>
        </asp:SqlDataSource>
        <br />
        <br />
        Select City :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:DropDownList ID="DropDownList3" runat="server" AppendDataBoundItems="True" DataSourceID="SqlDataSource3" DataTextField="CityName" DataValueField="CityId" Height="19px" Width="150px">
            <asp:ListItem Value="0">Select</asp:ListItem>
        </asp:DropDownList>
        <asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [City] WHERE ([StateId] = @StateId)">
            <SelectParameters>
                <asp:ControlParameter ControlID="DropDownList2" Name="StateId" PropertyName="SelectedValue" Type="Int32" />
            </SelectParameters>
        </asp:SqlDataSource>
   
    </div>
    </form>
</body>
</html>

Thursday, May 5, 2016

How to Edit picture from FormView using SQLDataSource control in ASP.NET C#

In this ASP.NET article i will show you, How to edit picture using FormView control. We all know that when FormView bind from SqlDataSource control then image have display on label control bydefault. First of all change label control with the image control. If you see the source code then you find that a label control bind with the image column using Eval("column name") method in embedded code block (<%# %> ). If you have to change label text with imageUrl then image will display on that place. Similarly in edit section take a fileupload control for picking file from local computer. Find it (Fileupload control) from Form View control in code file also save file in project folder. Lets see the example :

Wednesday, May 4, 2016

How to fetch data from database in asp.net

Introduction
In this article i will show you how to fetch data from sql server to GridView by coding. Example of binding gridview with SQL Server database. There are many ways to fetch data from database table. I have to mention list of table:

  1. Get Data from database using SqlDataReader.
  2. Get Data from database using DataSet with SqlDataAdaptor
  3. Get Data from Database using SqlDataSource Control.
  4. Get Data From Database using EDMX File (Entity Framework)

The C# GridView Control
The C# GridView control is a Data bound control that displays the values of a data source in the form of a table . In this table , each column represents a field and each row represents a record . The C# GridView control exists within the System.Web.UI.Controls namespace . When you drag and drop the GridView control on the designer page , the following syntax is added to the source view of the page.

<asp:gridview id="GridView1" runat="server"> </asp:gridview>

ASP.NET reduce lots of code in binding process, provide binding controls such as SqlDataSource for connecting database. The GridView data control has a built-in capability of sorting ,paging , updating and deleting data. You can also set the column fields through the AutoGenerate property to indicate whether bound fields are automatically created for each field in the data source.
In the below mentioned example, step 1 is define for add gridview in the webpage. Now, come to second step create columns in the gridview, which is depend on user choice. Under the <Columns> tag, create TemplateFields, which is used for design first column, according to step 3.


STEP-1 : Drag Gridview from Toolbox and Drop on design window.

    <form id="form1" runat="server">
    <div>  
        <asp:GridView ID="GridView1" runat="server">        
        </asp:GridView>  
    </div>
    </form>

STEP-2 : Create columns inside Gidview

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

STEP-3 : Create first column using TemplateField

  <Columns >
<asp:TemplateField>
</asp:TemplateField>
            </Columns>

STEP-4 : Create ItemTemplate inside <asp:TemplateField>
STEP-5 :  Also bind with table Attribute/Field

<asp:TemplateField>
   <ItemTemplate>
    <%# Eval("EmployeeId") %>
        </ItemTemplate>
</asp:TemplateField>

STEP-6:
Make StoredProcedure for retrieving data from database table.

CREATE PROCEDURE [dbo].[getdata]

AS
SELECT * from [Table]

RETURN 0



STEP-7 : Create code for binding data

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

public partial class binggrid : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page .IsPostBack)
        {
            getdataload();

        }

    }

    private void getdataload()
    {
        using (SqlConnection con = new SqlConnection())
        {
            con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
            con.Open();
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "getdata";
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                using (DataSet ds = new DataSet())
                {
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                        GridView1.DataSource = ds;
                        GridView1.DataBind();

                    }

                }  
         
            }
       
        }

    }
}

Output of the program
C# gridview bind in asp.net

Note : Some Extra Column appear in gridview like EmployeeId, name
if you want to remove these column add attribute inside gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns ="false">

Main Output of the program are:



C# gridview bind in asp.net
Here we are using single Template field. If you want to make more column then you must take more than one template field. Each template specifies column of the GridView.


Top related post

Tuesday, May 3, 2016

Online Student Information System in ASP.NET

Introduction

"Independent functional unit work together" known as system. Like Computer System, it contains multiple independent units ( Hard disk, mother board , processor etc) But these units are depended on each other. Same thing in Student Information System, which contains different types of module such as
  • Personal Information of students 
  • Progress Card information of student
  • And last one is Current status of student.
Brings these module, we will design a System. First of all we discuss about Personal Information. Before reading about this project , you can see my project gallery.

  1. Online Course Registration System Project
  2. Online Hotel Reservation System Project
  3. Finger Print Based System.
  4. Online Blood bank Project System
  5. Offline Banking System
  6. Online Polling System
  7. Student and Fees management system
  8. Online Mobile Shopping Project
  9. College WebSite Project
  10. Online Job Project Portal 
  11. Online Gym Application Project

Student's Personal Information

Store information related to student like StudentID, StudentName, Student Address and many more things. All Information stored in Database table, Store data related to other database table.

How to Design Online Student Information System

  1. First to design Master page for this Project 
  2. Learn How to store information of student 
  3. Learn How to retrieve Information of student 
  4. Learn How to update information of student 
  5. How to delete wrong information of student.

Monday, April 4, 2016

Delete selected item from DropdownList / Select List Using JQuery

In this article i will show you how to delete selected item from DropdownList/Select List Using JQuery. We all know that select/DropdownList contain option tag for value. So, the main logic behind the question is first to get the select list by using their id property then use option tag with selected attribute after that remove.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default10.aspx.cs" Inherits="Default10" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>

        $(function () {
            $("#btdel").bind("click", function () {
                $("#fruitlist option:selected").remove();
            });
                    });


    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <select id="fruitlist">

        <option value="1">Mango</option>
        <option value="2">Apple</option>
        <option value="3">Orange</option>
        <option value="4">Grapes</option>



    </select>
        <input type="button" id="btdel" value="Delete" />
    </div>
    </form>
</body>
</html>

GridView Row Delete using Delete Command Name Example in ASP.NET C#

In this video i will explain you how to delete row from GridView as well as Database in ASP.NET C#. The main logic behind the code is CommandName, i.e predefined in asp.net library. If you want to update row then you have a Update command Name similarly if you want to delete row from GridView then you have Delete command Name and their respective event. Keep watching and learn better.


Tuesday, March 29, 2016

How to use ADO.NET Entity Data model with database

ADO.NET Entity Data Model provides you a better and fast approach for communicating with database objects like Table, Stored Procedure etc. After added it, you have some models (classes ) which is related to tables and context classes. I mean to say that you can access database table directly by using context classes. In the context class, we have some public properties, through these we can retrieve table values. These all such things are related to model first approach , i mean to day that ADO.NET Entity Data model is based on model first approach. Let's start to configure it with the database, you can follow these steps , if you want to configure it:
Step-1 : Right Click on your project name , select add new item from the appearing menu. 
Step-2 :
How to use ADO.NET Entity Data model with database
 
Step-3: Press "OK" to continue.
Step-4: Select "EF designer from Database" option in the Entity Data Model wizard.
Step-5:  Now, press Next to continue in model wizard, select Connection string from Dropdown menu if exists. You can create "New Connection" by using Sql Server Database.

Entity Data Model Wizard

Step-6: Also select "Save Connection String into web.config file" CheckBox to save your whole connection parameter in web.config file.
Step-7: Press "Next" to continue. Select either all of them  Table, Views, Stored processor and one of them.
How to use ADO.NET Entity Data model with database

Step-8: Click to "Finish" Button.

Thursday, March 24, 2016

DropdownList Selected Disabled Default item in ASP.NET C#

In this article, I will show you, How to add default item at index 0 in DropdownList, also select default item, default item will be disabled when drop down the popup. For this task, first of all bind the DropdownList then you can add default item at index first by using following line of code:

      DropDownList1.Items.Insert(0, "Select");
After that you can select or disabled default item by the following line of code:
        DropDownList1.Items[0].Selected = true;
        DropDownList1.Items[0].Attributes["Disabled"] = "Disabled";
Source Code

<div>
    
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
    
    </div>

Code Behind Code

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

public partial class Default9 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            binddrop();
        }
    }

    private void binddrop()
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString  =ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        con.Open();

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText ="select * from [Employee]";
        cmd.Connection =con;

        SqlDataReader rd=  cmd.ExecuteReader();
        DropDownList1.DataSource =rd;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "Id";
        DropDownList1.DataBind();

        DropDownList1.Items.Insert(0, "Select");
        DropDownList1.Items[0].Selected = true;
        DropDownList1.Items[0].Attributes["Disabled"] = "Disabled";


    }
}

Code generates the following output :


Monday, March 21, 2016

Online Course Registration System Project in ASP.NET C#

In this Project we have a logical system. By using this system we can store courses and their subjects in the system database. The all things we can do by administrator. First of all, administrator do login in the system. He/ She can change our profile like change password, username and etc. In the Courses tab, we will provide some following things like "Manage Courses", "Add Courses", "Manage subject combination" and "Add subject combination". In the section of Manage courses, i will provide you a GridView control with the following action control like:

Manage Courses

By using Edit and Delete button we can make some changes in the course table. By using Subject combination we can configure subjects under defined courses. I will provide you a interface through which you can add new courses in the table like :

After add course details , you can add subjects in particular course also configure it by using some action command like "Edit" and "Delete". Now, by mentioned snap, you can add new subject details in the courses like:
subject details in the courses

Software Requirement :  Visual Studio 2013

Download : mail me : narenkumar851@gmail.com
© Copyright 2013 Computer Programming | All Right Reserved