-->

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;
        }
    }
}

© Copyright 2013 Computer Programming | All Right Reserved