-->

Thursday, March 22, 2018

Save and Display Binary Images from Database in DataGridView in Windows Forms

In this article, I am going to show you, How to show images in DataGridView in Windows forms c#. Its easy to bind the DataGridView with the database table which is contain binary image. You can check this code to bind the DataGridView with the image using Entity Framework.


using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace BankingApplication_Tutorial
{
    public partial class Form4 : Form
    {
        public Form4()
        {
            InitializeComponent();
        }

        private void Form4_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.ColumnCount = 2;
            dataGridView1.Columns[0].Name = "Id";
            dataGridView1.Columns[0].HeaderText = "Image Id";
            dataGridView1.Columns[0].DataPropertyName = "Id";

            dataGridView1.Columns[1].Name = "Name";
            dataGridView1.Columns[1].HeaderText = "Name";
            dataGridView1.Columns[1].DataPropertyName = "Name";

            DataGridViewImageColumn Imagecolumn = new DataGridViewImageColumn();
            Imagecolumn.Name = "Data Image";
            Imagecolumn.DataPropertyName = "Data";
            Imagecolumn.HeaderText = "Image Show";
            Imagecolumn.ImageLayout = DataGridViewImageCellLayout.Normal;
            dataGridView1.Columns.Insert(2, Imagecolumn);
            dataGridView1.RowTemplate.Height = 100;
            dataGridView1.Columns[2].Width = 100;
            this.bindDataGridView();





        }

        private void bindDataGridView()
        {
            // throw new NotImplementedException();
            banking_dbEntities1 dbe = new banking_dbEntities1();
            var items = dbe.DataGridImages.ToList();
            dataGridView1.DataSource = items;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            banking_dbEntities1 dbe = new banking_dbEntities1();
            using (OpenFileDialog dialog =  new OpenFileDialog())
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string filename = dialog.FileName;
                    byte[] bytes = File.ReadAllBytes(filename);
                 
           
            DataGridImage img = new DataGridImage();
                    img.Name = Path.GetFileName(filename);
                    img.Data = bytes;
                    dbe.DataGridImages.Add(img);
                    dbe.SaveChanges();
                     
                     
                     
                        }

            }
            bindDataGridView();
        }
    }
}

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 :

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


Saturday, April 16, 2016

BackgroundWorker Example in WPF C#

Background Worker is used to do processing in background.  I mean to say that if you have two work and you want to do complete both task at same time then must to use BackgroundWorker class. You can do two task at same time , like in gmail, attach a file with writing some text in the Text. Use this example and see more things about BackgroundWorker class.


XAML Code: 

<Grid>
        <Button Content="Run BackGround Work" HorizontalAlignment="Left" Margin="38,32,0,0" VerticalAlignment="Top" Width="209" Click="Button_Click"/>

        <Label Content="" HorizontalAlignment="Left" Margin="38,68,0,0" VerticalAlignment="Top" Name="processlbl"/>

        <Label Content="" HorizontalAlignment="Left" Margin="217,68,0,0" VerticalAlignment="Top" Name="Completelbl"/>

        <Button Content="Other Task" HorizontalAlignment="Left" Margin="48,157,0,0" VerticalAlignment="Top" Width="199" Click="Button_Click_1"/>

        <TextBox Name="t1" HorizontalAlignment="Left" Height="23" Margin="48,198,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="199"/>

        <Label Content="" HorizontalAlignment="Left" Margin="60,226,0,0" VerticalAlignment="Top" Name="outputlbl"/>

    </Grid>

Code Behind Code:

using System.ComponentModel;
using System.Windows;

namespace WpfApplication11
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        BackgroundWorker worker = new BackgroundWorker();
        public MainWindow()
        {
            InitializeComponent();
            worker.DoWork += worker_Dowork;
            worker.RunWorkerCompleted += worker_RunworkerCompleted;
        }

        private void worker_RunworkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                Completelbl.Content = "Complete Backgroung Work";
            }
            else
            {
                Completelbl.Content = "Fail";
            }
        }
        private delegate void mydelegate(int i);
        private void displayi(int i)
        {
            processlbl.Content = "Background work:" + i.ToString();
        }
        private void worker_Dowork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 20; i++)
            {
                System.Threading.Thread.Sleep(2000);
                if(worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                mydelegate deli = new mydelegate(displayi);
                processlbl.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, deli, i);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            worker.RunWorkerAsync();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            outputlbl.Content = t1.Text;
        }
    }
}

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 :


Wednesday, March 9, 2016

Bind TreeView with Country state and city | multiple table in ASP.NET C#

In this article i will show you how to bind TreeView at 2 level, you can say that Bind tree view with country , state and city table. Country table data bind at 0 level , state data bind at 1 level and last city data bind at 2 level. So first of all create three table, Sql Script mentioned below:


Database Table : (Country)

CREATE TABLE [dbo].[Country] (
    [Id]   INT           IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

Database Table : (State)

CREATE TABLE [dbo].[state] (
    [Id]   INT           NOT NULL,
    [Name] NVARCHAR (50) NULL,
    [cid]  INT           NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

Database Table : (City)

CREATE TABLE [dbo].[city] (
    [Id]   INT           NOT NULL,
    [Name] NVARCHAR (50) NULL,
    [sid]  INT           NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

Now, add the tree view in web form. Now, your source page looking like this.

Source Code :

<asp:TreeView ID="TreeView1" runat="server">
        </asp:TreeView>


Code Behind Code :

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 Default6 : System.Web.UI.Page
{
    static int count = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = this.GetData("SELECT Id, Name FROM [Country]");
            this.PopulateTreeView(dt, count, null);
        }
    }
    private void PopulateTreeView(DataTable dtParent, int parentId, TreeNode treeNode)
    {
        foreach (DataRow row in dtParent.Rows)
        {
            TreeNode child = new TreeNode
            {
                Text = row["Name"].ToString(),
                Value = row["Id"].ToString()
            };
            if (parentId == 0)
            {
                TreeView1.Nodes.Add(child);
                DataTable dtChild = this.GetData("SELECT Id, Name FROM [state] WHERE cid = " + child.Value);
                count =1;
                PopulateTreeView(dtChild,count , child);
            }
            else if (parentId == 1)
            {
                treeNode.ChildNodes.Add(child);
                DataTable dtChild = this.GetData("SELECT Id, Name FROM [city] WHERE sid = " + child.Value);
                count =2;
                PopulateTreeView(dtChild,count, child);
            }
            else
            {
                treeNode.ChildNodes.Add(child);

            }
         
        }
    }

    private DataTable GetData(string query)
    {
        DataTable dt = new DataTable();
        string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    sda.Fill(dt);
                }
            }
            return dt;
        }
    }
}

In this code First to bind DataTable with the Country table, for each country , retrieved State name and for each state name , retrieved city name. Here, we have recursion technique. In the Populate TreeView method parent id define the level of the tree view.

Now, Code Generates the following output:
Bind TreeView with Country state and city | multiple table in ASP.NET C#


Tuesday, March 8, 2016

Default Membership Provider must be specified

Create User Wizard control is used to store information of the user or visitor into the database table. ASP.net provide the control through this we can store limited information of the client into the database table. But we can change its user interface. You can say customization of Grid View. When we drag it on design window then its look like:

Customization of CreateUserWizard Control

Select Create User Step link by using "show smart tag". After that you can make some changes in fields. Like if You want to remove "Security Answer" and Security Question. Suppose you have to remove it then your interface look like:

 remove "Security Answer" and Security Question.

But when you run it then you get error like :

Default Membership Provider must be specified.

[Solution]
Add tags in web. config file.
<system.web>
<membership>
      <providers>       
        <clear />
      <add requiresQuestionAndAnswer="false" name="AspNetSqlmembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="DefaultConnection" applicationName="Application"/>
      </providers>
    </membership>
</system.web>
Code Generates the following output
Customization of CreateUserWizard Control in ASP.NET C#

Sunday, March 6, 2016

GridView BoundField Example in ASP.NET C#

In this article i will show you, How to use BoundField of GridView in ASP.NET C#. Actually, BoundField is the Default field of GridView Control, used for DataBinding purpose. In my previous article i have already use this field with SQL DataSource control. Check mentioned below link:

[Video Contain BoundField + SQLDataSource + ADO.NET]


Now, Learn, How to create BoundField manually also bind them using ADO.NET Technology with Database table. First to create a database table, insert some data into table. Prepare BoundField like this:

  <asp:GridView ID="g1" runat="server" AutoGenerateColumns="false">
        <Columns>

            <asp:BoundField DataField="Id" HeaderText="Identification No" />
            <asp:BoundField DataField="Name" HeaderText="Name of User" />

        </Columns>
   </asp:GridView>

Code Behind Code:

using System;
using System.Web.UI;
using System.Data.SqlClient;
using System.Configuration;

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

    private void bindGrid()
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        con.Open();
        SqlCommand cmd= new SqlCommand();
        cmd.CommandText = "select * From [usertable]";
        cmd.Connection =con;
        SqlDataReader rd= cmd.ExecuteReader();
        g1.DataSource =rd;
        g1.DataBind();
    }
}

Code Generates the following output:

GridView BoundField Example in ASP.NET C#

Thursday, March 3, 2016

Edit Update GridView Row using Command Name

In this article, I will show you how to update GridView row. By using edit button we can update GridView row. But the question is, how to design "Edit" button for delete. If you follow me then i am sure you can delete rows from GridView.
Mentioned Following steps are:
Step-1 : Add a GridView Control on source window by using html code. Now, in the source page you have.
<asp:GridView ID="g1" runat="server">
</asp:GridView>

Step-2: Add these mentioned properties in the GridView:
AutoGenerateColumns="false"
 OnRowCancelingEdit="g1_RowCancelingEdit"
 OnRowEditing="g1_RowEditing"
 OnRowUpdating="g1_RowUpdating"

 Here, we have AutoGenerateColumns="false" means you design GridView columns manually. OnRowCancelingEdit is a event through this you can cancel the process of editing. OnRowEditing is also a event through this you can edit new Index. By using OnRowUpdating event you can update rows with new Data. 

 Step-3 : Suppose we have two fields in Database table then you can design GridView for this way. Now, the complete code of GridView is:

Source Code:


  <asp:GridView ID="g1" runat="server" AutoGenerateColumns="false" OnRowCancelingEdit="g1_RowCancelingEdit" OnRowEditing="g1_RowEditing" OnRowUpdating="g1_RowUpdating">
            <Columns>
                <asp:TemplateField HeaderText="Controls">
                    <ItemTemplate>
                        <asp:Button Text="Edit" ID="Editbutton" runat="server" CommandName="Edit" />
                    </ItemTemplate>
                    <EditItemTemplate>
                         <asp:Button Text="Update" ID="updatebutton" runat="server" CommandName="Update" />
                         <asp:Button Text="Cancel" ID="cancelButton" runat="server" CommandName="Cancel" />
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Id">
                    <ItemTemplate>
                        <asp:Label ID="idlbl" runat="server" Text='<%# Eval("Id") %>' />
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="namelbl" runat="server" Text='<%# Eval("Name") %>' />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="nametext" runat="server" Text ='<%# Eval("Name") %>' />
                    </EditItemTemplate>
                </asp:TemplateField>

            </Columns>
        </asp:GridView>    

In the First Template field we have two templates i.e ItemTemplate and EditItemTemplate. By using ItemTemplate we can show Edit Button with their "Edit" Command Name Property. When you click on it then open EditItemTemplate, in which we have two buttons in same column i.e Update and Cancel. similarly Design two columns for data. Pick the data from the database table using Embedded code block. 

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

    }

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

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

        SqlDataReader rd = cmd.ExecuteReader();
        g1.DataSource = rd;
        g1.DataBind();
        con.Close();
    }
    protected void g1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        g1.EditIndex = e.NewEditIndex;
        bindgrid();
    }
    protected void g1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        g1.EditIndex = -1;
        bindgrid();
    }
    protected void g1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label l1 = g1.Rows[e.RowIndex].FindControl("idlbl") as Label;
        TextBox t1 = g1.Rows[e.RowIndex].FindControl("nametext") as TextBox;
        SqlConnection con = new SqlConnection();
  con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        con.Open();

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "update [usertable] set Name=@nm where Id=@id1";
        cmd.Parameters.AddWithValue("@id1", l1.Text);

        cmd.Parameters.AddWithValue("@nm", t1.Text);
        cmd.Connection = con;
        cmd.ExecuteNonQuery();

        g1.EditIndex = -1;
        bindgrid();



    }
}

Code Generates the following output

Edit Update GridView Row using Command Name

Edit Update GridView Row using Command Name

Saturday, February 27, 2016

Blood bank System project in ASP.NET C#

Introduction
The blood bank system provides some information about blood bank. A needy person can take some points of blood with their blood groups. By using this system, we provides the information  about donor and takers. These all information are public. Any one  person register in the control panel and after successfully register in the panel. He/She can login in the system. We have a form for donor, in this form, donor fill these mentioned fields.

Donor Id :  Int type
Name :  nvarchar (100)
Blood Group :  nvarchar ( 50)
Contact ( Phone Number)  : nvarchar (50)
Address : nvarchar(max)
Picture:  nvarchar(max)

Blood bank System project in ASP.NET C#


After filling the form, information display on home screen, registered user can see donor information. Project also provide the search facility, through it, registered user can see donor information, according to blood group. It provide the total storage of blood in the bank. Bank takes blood from outer side also vice versa. Total in and out details stored in separate database table.

Software information : Visual Studio 2013
Hardware requirement :  Visual Studio 2013 compatible hardware.

Video : Comming Soon

How to run it: You can run it using video help.

Download/Buy : mail me narenkumar851@gmail.com




Thursday, February 25, 2016

GridView rows details on DetailsView using onSelectedIndexChanged event in ASP.NET C#

Bind Details view using onselectedIndexChanged event of Gridview view. First to Bind the Gridview with select command. By using selectedIndexChanged method you can bind the details view. If you want to bind the DetailsView from Gridview Row then use select command name in GridView's button field name. In the Code behind file, first to bind the Gridview from database table. Retrieve the selected Row data using select command, bind DataTable with Retrieved data.


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

<!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" AutoGenerateColumns="false" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="ID" />
                <asp:BoundField DataField="name" HeaderText="Name" />
                <asp:TemplateField HeaderText="address">
                    <ItemTemplate>

                        <asp:Label ID="addlabel" Text='<%# Eval("address") %>' runat="server" />

                    </ItemTemplate>
             

                </asp:TemplateField>
                <asp:ButtonField Text="select" CommandName="select" />
            </Columns>


        </asp:GridView>
        <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px" AutoGenerateRows="false">
            <Fields>
                <asp:BoundField DataField="Id" HeaderText="ID" />
                <asp:BoundField DataField="name" HeaderText="Name" />
                <asp:BoundField DataField="address" HeaderText="Address" />


            </Fields>


        </asp:DetailsView>
    </div>
    </form>
</body>
</html>

Code Behind Code

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 Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["myconnection"].ToString();
            con.Open();
            SqlCommand cmd=new SqlCommand();
            cmd.CommandText="select * from [Registration]";
            cmd.Connection=con;
            SqlDataReader rd = cmd.ExecuteReader();
            GridView1.DataSource = rd;
            GridView1.DataBind();

        }

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int id= int.Parse(GridView1.SelectedRow.Cells[0].Text);
        string name = GridView1.SelectedRow.Cells[1].Text;
        string add = (GridView1.SelectedRow.FindControl("addlabel") as Label).Text;
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[] { new DataColumn("ID", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Address", typeof(string)) });
        dt.Rows.Add(id, name, add);
        DetailsView1.DataSource = dt;
        DetailsView1.DataBind();
    }
}

Code Generates the following output
GridView rows details on DetailsView using onSelectedIndexChanged event in ASP.NET C#

Saturday, February 20, 2016

Banking Software Application Project in c#

Introduction
Purchase Banking software project built in window platform. By using this software, we can do banking task easily. In this project,  I have to provide you banking functionality like Create new account, update customer account, deposit money, transfer money etc. I will give you project executable file to run the project. If you want to learn how to design this project then follow these mentioned steps:

[Video Describe full details]



  1. Start from Login screen. If admin username exists in database table then loginIn into the system else give failed message.
banking System Login Failed Screen

2. If login success then enter in main screen.

Banking Software Application Project in c#

3. Similarly all option which is given in the project.


Requirement
Software : Visual Studio 2013. 


How to run you project
Double click on application executable file and run your project.

How to design Banking Software
First to create a login form for Administrator. After successfully login, administrator can do some work in the control panel like:

  1. Add New Customer.
  2. Deposit money to customer bank account.
  3. Transfer money from one account to another account.
  4.  Show list of account which is available in the bank.
  5. Withdrawal amount from account number by the account holder.
  6. Generate balance sheet.
  7. FD form for customers.
Download : mail me : narenkumar851@gmail.com

Tuesday, February 16, 2016

ASP.NET ListBox Insert Multiple selected item into database

In this article, I will show you how to insert multiple selected item in  database table. I have already done one projects on this topic i.e online movie ticket booking system. In this project, i selected multiple tickets by using comma symbol in TextBox. The same article i will do in different manner. In this we have a ListBox with multiple selection mode.
What i do in code behind :

  1. Store the selected of ListBox items to the string type list.
  2. For the each item, i will create a Query statement, Suppose your List contain two items i.e "Apple" and "Mango", Both are selected then use String builder class to Append Query.
  3. Like "insert into [tablename] (fruitname)values('Apple')";  and for second item  "insert into [tablename] (fruitname)values('mango')";

Source Code

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

<!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:ListBox ID="ListBox1" runat="server" Height="100px" SelectionMode="Multiple" Width="174px">
            <asp:ListItem>Apple</asp:ListItem>
            <asp:ListItem>Grapes</asp:ListItem>
            <asp:ListItem>Orange</asp:ListItem>
            <asp:ListItem>Mango</asp:ListItem>
            <asp:ListItem>Pea</asp:ListItem>
        </asp:ListBox>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save" />
    </form>
</body>
</html>

Code Behind Code

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

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        List<string> l1 = new List<string>();
        foreach (ListItem item in ListBox1.Items)
        {
            if (item.Selected)
            {
                l1.Add(item.Text);
            }  
        }
        recordinserted(l1);
    }

  

    private void recordinserted(List<string> l1)
    {
       StringBuilder stringbi = new StringBuilder(string.Empty);
        foreach (string item in l1)
{
const string qry = "insert into [Fruits](FruitName)values";
            stringbi.AppendFormat("{0}('{1}');",qry,item);
}
        //throw new NotImplementedException();
        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionStringtr"].ToString();
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = stringbi.ToString();
        cmd.Connection=con;
        int a= cmd.ExecuteNonQuery();
        if(a>0)
        {
            Response.Write("inserted");
        }
    }
}

Code Generates the following output : 


ASP.NET ListBox Insert Multiple selected item into database

© Copyright 2013 Computer Programming | All Right Reserved