-->

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.

Get the Cell value of selected Row From DataGrid in WPF

In this article i will show you, how to get the cell value from datagrid in WPF. We all know that dataGrid is use for storing data in a tabular format. By using AutoGenerateColumns we will show our table columns in it.  If you want to show your customized columns in it the  add DataGridTemplate Column.  In it we have cell template, by using this we can design our dataGrid cells. In the first DataTemplate i will take a button control through it we can show the cell value of dataGrid.


<Window x:Class="WpfApplication13.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid Name="grid1" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Name="b1" Click="b1_Click" Content="click" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Id" Binding="{Binding Id}" />
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>

            </DataGrid.Columns>
         
        </DataGrid>
    </Grid>
</Window>

In this XAML code we have a Id and Name property which is bind with public property of student class.

using System;
using System.Windows;

namespace WpfApplication13
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
           grid1.ItemsSource = Student.getStudent();
        }

        private void b1_Click(object sender, RoutedEventArgs e)
        {
            Student st = grid1.SelectedItem as Student;
            string studentid = Convert.ToString(st.Id);
            string studentName = st.Name;
            MessageBox.Show(studentid + " " + studentName);

        }
    }
}

using System.Collections.ObjectModel;

namespace WpfApplication13
{
    class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public static ObservableCollection<Student> getStudent()
        {
            var student = new ObservableCollection<Student>();
            student.Add(new Student() { Id = 1, Name = "Jacob" });
            student.Add(new Student() { Id = 2, Name = "Bill" });
            return student;



        }
    }
}

Friday, April 29, 2016

Similar to TextChanged Event in ASP.NET MVC

This is very good article for web form users who want to get value on TextChanged Event. I mean to say that  TextChanged Event occurs when we move one textbox to another using "Tab" key. When, Web form users moves to MVC projects. He/ She faces some problems in logics. Because, in MVC, For each request we must to call controller. I have an idea to remove such task. I prefer JQuery. So first to Add a ViewModel Class into your project. You can take this sample.

1. Add a new Folder in your project, name of the folder is "viewModel". Now, add a class, which name as addition like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication27.viewModel
{
    public class addition
    {
        public int FirstNumer { get; set; }
        public int SecondNumber { get; set; }
        public int result { get; set; }
    }
}

In this we have three public property.Now, Add a controller class in Controller folder. Like that.

using System.Web.Mvc;

namespace WebApplication27.Controllers
{
    public class DefaultController : Controller
    {
        // GET: Default
        public ActionResult Index()
        {
            return View();
        }
    }
}

Add View, By using Right click on Action method name. In View section, i will add code of JQuery. You can see

@model WebApplication27.viewModel.addition

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@using(Html.BeginForm())
{
    @Html.TextBoxFor(m=>Model.FirstNumer)
    @Html.TextBoxFor(m=>Model.SecondNumber)
    @Html.TextBoxFor(m => Model.result)
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
    $(function () {
        $("#SecondNumber").blur(function () {
            $("#result").val(parseInt($("#FirstNumer").val()) + parseInt($("#SecondNumber").val()))
        });
    })
</script>

Wednesday, April 27, 2016

Bind ComboBox with Enum Type in WPF


In this article i will show you, How to Bind ComboBox with Enum properties.  Enum is a type, which is used to fix no of values like Sunday, Monday, Tuesday...etc.). By using XAML, you can add static resources for enumeration. In WPF We have a ObjectDataProvider for enumeration. Lets check the code.

XAML Code :

<Window x:Class="WpfApplication1212.Window2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local1="clr-namespace:WpfApplication1212"
        xmlns:codeg="clr-namespace:System;assembly=mscorlib"
        Title="Window2" Height="300" Width="300">
    <Window.Resources>
        <ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type codeg:Enum}" x:Key="myenu">
            <ObjectDataProvider.MethodParameters>
                <x:Type Type="local1:week1" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    <Grid>
        <ComboBox ItemsSource="{Binding Source={StaticResource myenu}}" />
    </Grid>
</Window>

Enumeration code 

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

namespace WpfApplication1212
{
    class Order
    {
    }
    public enum week1
    {
        sun,mon,tue,wed,
    }
}

Thursday, April 21, 2016

WPF: How to take image and button control in WPF ListView

Good Morning: Today i will teach you how to add controls in ListView. In this article i will add button control and image control. According to my previous article image control bind with source, so  it required source for binding, so i have create a ImageSource public property in class. We know that ListView contain only single view i.e GridView. A GridView contain rows and column , also we can say that cell is a combination of rows and column. In this article i have create CellTemplate.  Inside the CellTemplate we have a Data Template. In the Code behind page, we have a class with one property i.e "ImageSource", which is used for Image binding. Add a list control with class type, in it we have two images. Lets check the code and their output
XAML Code
<Window x:Class="WpfApplication11.ImageinListview"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ImageinListview" Height="300" Width="300">
    <Grid>
        <ListView Name="List1" MouseDoubleClick="getSelectedItem">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Action">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Button Content="Click Me" Click="Button_Click"/>                              
                            </DataTemplate>                        
                           
                        </GridViewColumn.CellTemplate>                      
                    </GridViewColumn>
                    <GridViewColumn Header="Image">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Image Source="{Binding ImageSource}" Width="100" Height="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>

                    </GridViewColumn>

                </GridView>
            </ListView.View>        
           
        </ListView>
       
    </Grid>
</Window>

Code Behind Code:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;

namespace WpfApplication11
{
    /// <summary>
    /// Interaction logic for ImageinListview.xaml
    /// </summary>
    public partial class ImageinListview : Window
    {
        public ImageinListview()
        {
            InitializeComponent();
            bindlist();
        }

        private void bindlist()
        {
           // throw new NotImplementedException();
            List<imgs> listr = new List<imgs>();
            listr.Add(new imgs() { ImageSource = "/imag/11.png" });
            listr.Add(new imgs() { ImageSource = "/imag/bleaching.jpg" });
            List1.ItemsSource = listr;


        }
        private void getSelectedItem(object sender, MouseButtonEventArgs e)
        {
            imgs imgh = List1.SelectedItems[0] as imgs;
            MessageBox.Show(imgh.ImageSource);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
    
        }
    }
    public class imgs
    {
        public string ImageSource { get; set; }
    }
}
Code generate the following output

WPF: How to take image and button control in WPF ListView


Monday, April 18, 2016

Design ASP.NET MVC form using ViewModel class

Welcome, user. Today i would like to share something about Forms and their control like TextBox, Label, DropdownList(SelectListItem), Radio Button etc in ASP.NET MVC. Before going to details, first to share something about ViewModel.
 A ViewModel is a temporary class file which is used to store data values in properties.   
First to take fields which are used in form like UserName, Password, Email, Gender, religions etc. Because we will need controls for each fields. Lets take an simple example. Create a new MVC project.

  1. Right click on your project, Add a new Directory which name should have ViewModel
  2. Add this class file inside the ViewModel

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

namespace MvcApplication1.ViewModel
{
    public class FormVM
    {
        public int Id { get; set; }
        public String UserName { get; set; }
        public String Password { get; set; }
        public String Gender { get; set; }
        public String Religion { get; set; }
        public String Image { get; set; }

        
        public bool IsSubmitted { get; set; }

    }
}

According to the ViewModel class we will take Two TextBox for UserName and Password, Three radio button for Religion, one file control for Image, one DropdownList for Gender and last One Submit control.After add this file, come to controller part. Add a new controller like this.

using MvcApplication1.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class TutorialController : Controller
    {
       public ActionResult AddUser()
        {
            FormVM viewModel = new FormVM();
            viewModel.IsSubmitted = false;
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult AddUser(FormVM model, HttpPostedFileBase file)
        {
            model.IsSubmitted = true;
            if (file != null)
            {
                string pic = System.IO.Path.GetFileName(file.FileName);
                model.Image = pic;
            }
            ViewBag.Values = model.UserName + ", " + model.Password + ", " + model.Gender + ", " + model.Religion + ", " + model.Image;
            return View(model);
        }

    }
}

By above mentioned code AddUser( ) method return a ViewModel class. Also set IsSubmitted property to false. So using ViewModel class you can create a model control into your view class. So i have a view class for you where your control designed. Let see.

@model MvcApplication1.ViewModel.FormVM

@{
    ViewBag.Title = "AddUser";
    List<SelectListItem> listItems = new List<SelectListItem>();
    listItems.Add(new SelectListItem
    {
        Text = "Male",
        Value = "Male",
        Selected = true
    });
    listItems.Add(new SelectListItem
    {
        Text = "Female",
        Value = "Female"
    });
    listItems.Add(new SelectListItem
    {
        Text = "None",
        Value = "None"
    });
}



<h2>AddUser</h2>

@using (Html.BeginForm("AddUser","Tutorial",FormMethod.Post, new { enctype = "multipart/form-data" })) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>FormVM</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UserName)
            @Html.ValidationMessageFor(model => model.UserName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Gender)
        </div>
        <div class="editor-field">
           @Html.DropDownListFor(model => model.Gender, listItems, "  Select Gender  ")
        </div>
        <br />
        <div class="editor-label">
            @Html.LabelFor(model => model.Religion)
        </div>
        <br />
        <div class="editor-field">
            @Html.RadioButtonFor(model => model.Religion, "Hindu", new { id = "rbHindu" })
            @Html.Label("Hindu")
            @Html.RadioButtonFor(model => model.Religion, "Muslim", new { id = "rbMuslim" })
            @Html.Label("Muslim")
            @Html.RadioButtonFor(model => model.Religion, "Other", new { id = "rbOther" })
            @Html.Label("Other")
        </div>
        <br/>
        <div class="editor-label">
            @Html.LabelFor(model => model.Image)
        </div>
        <div class="editor-field">
            <input type="file" name="file" id="file" style="width: 100%;" />
            
        </div>

        <p>
            <input type="submit" value="Submit" />
        </p>
    </fieldset>
}

<div>
    @if(Model.IsSubmitted){
        <p>@ViewBag.Values</p>
    }
</div>

Crate form control according to above mentioned code. When we click on Submit button then value of all control will display on paragraph using ViewBag variable. Now code generate the following output:

Design ASP.NET MVC form using ViewModel class
© Copyright 2013 Computer Programming | All Right Reserved