Monday 14 April 2014

WPF DataGrid : Insert Edit Update And delete operation

Hellow Friends !!
In  This article I will Explain you How to build simple WPF application to View ,Update, Insert and Delete Data.
Here I am using Data Grid to display, edit, add and delete data from SQL server database.
The Data Grid Control similar to ASP.NET Grid control. Data Grid Control is the powerful Control to available to developer and it has various collections to bind and provides various events to work with.
For Implementing Insert,Edit,Update and Delete Operation in WPF application,
I have created One table in database.

Table name is “dsh_wpfCRUD”.


Next Step 
1.Open Visual Studio
2.Create a new Project (WPF Application) name it “WpfCRUD” (You   can Also change Project name as you need.)


Next Step
3.In this Application  create appropriate GUI using XAML code. I have taken four textbox 
Two radio button, two Combo Box, two Button and one Data Grid Control to perform Operation of view ,edit and delete data.
I do this like below code.

MainWindow.xaml
<Window x:Class="WpfCRUD.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="378.358" Width="550.373">
    <Grid Margin="0,0,-31,-218">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="37*"/>
            <ColumnDefinition Width="154*"/>
        </Grid.ColumnDefinitions>
        <DataGrid x:Name="datagrid1" x:Uid="datagrid1" SelectionMode="Single"  HorizontalAlignment="Left" Margin="62,263,0,214" ItemsSource="{Binding}" AutoGenerateColumns="False" Width="475" Grid.ColumnSpan="2">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding id}" Header="ID" x:Name="id" IsReadOnly="True" Width="Auto"></DataGridTextColumn>
                <DataGridTextColumn Binding="{Binding name}" Header="Name" x:Name="name" Width="Auto"></DataGridTextColumn>
                <DataGridTextColumn Binding="{Binding address}" Header="address" x:Name="address" Width="Auto"></DataGridTextColumn>
                <DataGridTextColumn Binding="{Binding gender}" Header="gender" x:Name="gender" Width="Auto"></DataGridTextColumn>
                <DataGridTextColumn Binding="{Binding country}" Header="country" x:Name="country" Width="Auto"></DataGridTextColumn>
                <DataGridTextColumn Binding="{Binding state}" Header="state" x:Name="state" Width="Auto"></DataGridTextColumn>
                <DataGridTextColumn Binding="{Binding city}" Header="city" x:Name="city" Width="Auto"></DataGridTextColumn>
                <DataGridTextColumn Binding="{Binding contactno}" Header="contactno" x:Name="contactno" Width="Auto"></DataGridTextColumn>
                <DataGridTemplateColumn Header="Edit">
                    <DataGridTemplateColumn.CellTemplate >
                        <DataTemplate>
                            <Button Content="Edit" Click="Button_Click_2" CommandParameter="{Binding id}"></Button>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="delete">
                    <DataGridTemplateColumn.CellTemplate >
                        <DataTemplate>
                            <Button Content="Delete" Click="Button_Click_3" ></Button>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
        <TextBox Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Margin="143,34,0,0" Name="txtname"/>
        <Label Grid.ColumnSpan="2" Content="Name:" HorizontalAlignment="Left" Margin="48,34,0,0" VerticalAlignment="Top"  Target="{Binding ElementName=txtname}"/>
        <Label Grid.ColumnSpan="2" Content="Address:" HorizontalAlignment="Left" Margin="48,65,0,0" VerticalAlignment="Top"  Target="{Binding ElementName=txtaddress}"/>
        <TextBox Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Margin="143,68,0,0" x:Name="txtaddress"/>
        <Label Grid.ColumnSpan="2" Content="Gender:" HorizontalAlignment="Left" Margin="48,96,0,0" VerticalAlignment="Top"  Target="{Binding ElementName=txtgender}"/>
        <Label Grid.ColumnSpan="2" Content="Country:" HorizontalAlignment="Left" Margin="52,127,0,0" VerticalAlignment="Top"  Target="{Binding ElementName=cmbcountry}" RenderTransformOrigin="0.649,1.909"/>
        <ComboBox x:Name="combobox1" Grid.ColumnSpan="2" HorizontalAlignment="Left" Margin="143,127,0,0" VerticalAlignment="Top" Width="120" SelectionChanged="ComboBox_SelectionChanged_1"/>
        <Label Grid.ColumnSpan="2" Content="State:" HorizontalAlignment="Left" Margin="52,153,0,0" VerticalAlignment="Top"  Target="{Binding ElementName=cmbstate}" RenderTransformOrigin="0.649,1.909"/>
        <ComboBox x:Name="combobox2" Grid.ColumnSpan="2" HorizontalAlignment="Left" Margin="143,153,0,0" VerticalAlignment="Top" Width="120"   />
        <Label Grid.ColumnSpan="2" Content="City:" HorizontalAlignment="Left" Margin="52,179,0,0" VerticalAlignment="Top"  Target="{Binding ElementName=txtcity}"/>
        <TextBox Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Margin="143,182,0,0" x:Name="txtcity"/>
        <Label Grid.ColumnSpan="2" Content="ConatactNO:" HorizontalAlignment="Left" Margin="52,210,0,0" VerticalAlignment="Top"  Target="{Binding ElementName=txtcontactno}" RenderTransformOrigin="0.545,1.5"/>
        <TextBox Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Margin="143,213,0,0" x:Name="txtcontactno"/>
        <RadioButton x:Name="rdfemale" Grid.ColumnSpan="2" Content="Female" HorizontalAlignment="Left" Margin="143,106,0,0" VerticalAlignment="Top"/>
        <RadioButton x:Name="rdmale" Grid.ColumnSpan="2" Content="Male" HorizontalAlignment="Left" Margin="221,106,0,0" VerticalAlignment="Top"/>
        <Button x:Name="btnsubmit" Grid.ColumnSpan="2" Content="Submit" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="109,241,0,0" Click="Button_Click_1"/>
        <Button Grid.ColumnSpan="2" Content="Cancel" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="188,241,0,0"/>
    </Grid>
</Window>

After write code the design will look like in below picture.


In the above code , I am using DataGridTemplateColumn, Edit and Delete button are added.

MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
namespace WpfCRUD
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string sqlstring = "Data Source=SQLDB;Initial Catalog=Demo;Persist Security Info=True;User ID=demoh;Password=Demo1@";
        static int PK_ID;
        public MainWindow()
        {
            InitializeComponent();
            fillcombobox();
            filldatagrid();
        }
//Method for accessing data and fill datagrid
        private void filldatagrid()
        {
            SqlConnection con = new SqlConnection(sqlstring);
            con.Open();
            string sqlquery = "select * from dsh_wpfCRUD";
            SqlCommand cmd = new SqlCommand(sqlquery, con);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            datagrid1.ItemsSource = dt.DefaultView;
            con.Close();
        }
//Method for Fill Combobox after change selected item of another combobox.
        private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            int cnname1 = combobox1.SelectedIndex;
            int cname2 = cnname1 + 1;
            SqlConnection con = new SqlConnection(sqlstring);
            con.Open();
            string sqlquery = "select * from dsh_wpfCRUD_State where Countryname='" + cname2 + "'";
            SqlCommand cmd = new SqlCommand(sqlquery, con);
            SqlDataReader sdr = cmd.ExecuteReader();
            if (sdr.Read())
            {
                string cnname = sdr.GetString(2);
                combobox2.Items.Add(cnname);
            }
            con.Close();
        }
//Method for fill combobox
        void fillcombobox()
        {
            SqlConnection con = new SqlConnection(sqlstring);
            con.Open();
            string sqlquery = "select * from dsh_wpfCRUD_Country";
            SqlCommand cmd = new SqlCommand(sqlquery, con);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            combobox1.DataContext = dt;
            if (dt.Rows.Count > 0)
            {
                combobox1.Items.Add(dt.Rows[0]["name"].ToString());
                combobox1.Items.Add(dt.Rows[1]["name"].ToString());
            }
            con.Close();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (btnsubmit.Content == "Update")
            {
//Code for updating data
                SqlConnection con = new SqlConnection(sqlstring);
                con.Open();
                string sqlquery = "update dsh_wpfCRUD set name=@name,address=@address,gender=@gender,country=@country,state=@state,city=@city,contactno=@contactno where id='" + PK_ID + "'";
                SqlCommand cmd = new SqlCommand(sqlquery, con);
                cmd.Parameters.AddWithValue("@name", txtname.Text);
                cmd.Parameters.AddWithValue("@address", txtname.Text);
                string d1 = rdfemale.Content.ToString();
                string d2 = (Convert.ToBoolean(rdmale.IsChecked) ? rdmale.Content.ToString() : d1);
                cmd.Parameters.AddWithValue("@gender", d2);
                cmd.Parameters.AddWithValue("@country", combobox1.SelectedValue);
                cmd.Parameters.AddWithValue("@state", combobox2.SelectedValue);
                cmd.Parameters.AddWithValue("@city", txtcity.Text);
                cmd.Parameters.AddWithValue("@contactno", txtcontactno.Text);
                cmd.ExecuteNonQuery();
                filldatagrid();
               clearcontrol();
            }
            else
            {
//Code for inserting data
                SqlConnection con = new SqlConnection(sqlstring);
                con.Open();
                string sqlquery = "insert into dsh_wpfCRUD (name,address,gender,country,state,city,contactno) values (@name,@address,@gender,@country,@state,@city,@contactno)";
                SqlCommand cmd = new SqlCommand(sqlquery, con);
                cmd.Parameters.AddWithValue("@name", txtname.Text);
                cmd.Parameters.AddWithValue("address", txtaddress.Text);
                string d1 = rdfemale.Content.ToString();
                string d2 = (Convert.ToBoolean(rdmale.IsChecked) ? rdmale.Content.ToString() : d1);
                cmd.Parameters.AddWithValue("@gender", d2);
                cmd.Parameters.AddWithValue("@country", combobox1.SelectedValue);
                cmd.Parameters.AddWithValue("@state", combobox2.SelectedValue);
                cmd.Parameters.AddWithValue("@city", txtcity.Text);
                cmd.Parameters.AddWithValue("@contactno", txtcontactno.Text);
                cmd.ExecuteNonQuery();
                filldatagrid();
                clearcontrol();
            }
        }
//Method for clear data from control
        private void clearcontrol()
        {
            txtname.Text = string.Empty;
            txtaddress.Text = string.Empty;
            txtcity.Text = string.Empty;
            txtcontactno.Text = string.Empty;
        }
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
         
     var id1 = (DataRowView)datagrid1.SelectedItem; //get specific ID from          DataGrid after click on Edit button in DataGrid  
            PK_ID = Convert.ToInt32(id1.Row["id"].ToString());
            SqlConnection con = new SqlConnection(sqlstring);
            con.Open();
            string sqlquery = "select * from dsh_wpfCRUD where id='" + PK_ID + "' ";
            SqlCommand cmd = new SqlCommand(sqlquery, con);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                txtname.Text = dt.Rows[0]["name"].ToString();
                txtaddress.Text = dt.Rows[0]["address"].ToString();
                if (dt.Rows[0]["gender"].ToString() == "Male")
                {
                    rdmale.IsChecked = true;
                }
                else
                {
                    rdfemale.IsChecked = true;
                }
                combobox1.SelectedValue = dt.Rows[0]["country"].ToString();
                combobox2.SelectedValue = dt.Rows[0]["state"].ToString();
                txtcity.Text = dt.Rows[0]["city"].ToString();
                txtcontactno.Text = dt.Rows[0]["contactno"].ToString();
            }
            btnsubmit.Content = "Update";
        }
//Code for Deleting data
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
    var id1 = (DataRowView)datagrid1.SelectedItem;  //Get specific ID From                DataGrid after click on Delete Button.
       
            PK_ID = Convert.ToInt32(id1.Row["id"].ToString());
            SqlConnection con = new SqlConnection(sqlstring);
            con.Open();
            string sqlquery = "delete from dsh_wpfCRUD where id='" + PK_ID + "' ";
            SqlCommand cmd = new SqlCommand(sqlquery, con);
            cmd.ExecuteNonQuery();
            filldatagrid();
        }
    }
}
Output:




1 comment:

  1. that cool but i would like you to make the program again without any text box ok!.

    ReplyDelete

Popular Posts

Recent Posts

Sample Text

Stats

Powered by Blogger.

Popular Posts

Popular Posts

Join US on Facebook