-->

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 :


© Copyright 2013 Computer Programming | All Right Reserved