Click here to Skip to main content
15,902,112 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
//This is the .cs code

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.SqlClient;
using System.Configuration;
using System.Data;

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

        string dataconnection = ConfigurationManager.ConnectionStrings["CustomerConnectionString"].ConnectionString;

        public void BindGrid()
        {
            SqlConnection con = new SqlConnection(dataconnection);
            con.Open();
            SqlDataAdapter adapt = new SqlDataAdapter("Select * from Customers",con);
            DataSet binding = new DataSet();
            adapt.Fill(binding, "DataBind");
            dataGrid1.DataContext = binding;
            con.Close();
        
        }

        private void Add_Btn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SqlConnection con = new SqlConnection(dataconnection);
                con.Open();

                
                string custoid = customerid.Text;
                string custoname = customername.Text;
                string cit = city.Text;
                string sdate = datePicker1.DisplayDate.ToShortDateString();


                SqlCommand cmd = new SqlCommand("Insert into Customers (CustomerId,CustomerName,City,SDate) values('" + custoid + "','" + custoname + "','" + cit + "','" + sdate + "')",con);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();

                MessageBox.Show("One Record Inserted");
                customerid.Text = string.Empty;
                customername.Text = string.Empty;
                city.Text = string.Empty;
                datePicker1.Text = string.Empty;
               

                this.BindGrid();
                
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void Del_Btn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SqlConnection con = new SqlConnection(dataconnection);
                con.Open();
               
                string _DelCmd = @"Delete from Customers
                              Where CustomerId='" + customerid.Text + "'";

                SqlCommand _CmdDelete = new SqlCommand(_DelCmd,con);

               
                _CmdDelete.ExecuteNonQuery();

                MessageBox.Show("One Record Deleted");
                customerid.Text = string.Empty;
                customername.Text = string.Empty;
                city.Text = string.Empty;
                datePicker1.Text = string.Empty;
                

                this.BindGrid();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void Update_Btn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SqlConnection con = new SqlConnection(dataconnection);
                con.Open();

                string sdate = datePicker1.DisplayDate.ToShortDateString();

                
                string _UpdateCmd = @"Update Customers Set 
                                    CustomerName = '" + customername.Text + "',SDate = '" + sdate.ToString() + "',City = '" + city.Text + "' where CustomerId = '" + customerid.Text + "'";

               
                SqlCommand _CmdUpdate = new SqlCommand(_UpdateCmd,con);

               
                _CmdUpdate.ExecuteNonQuery();

                MessageBox.Show("One Record Updated");
                customerid.Text = string.Empty;
                customername.Text = string.Empty;
                city.Text = string.Empty;
                datePicker1.Text = string.Empty;
               

                this.BindGrid();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void New_Btn_Click(object sender, RoutedEventArgs e)
        {
            
            /*SqlConnection con = new SqlConnection(dataconnection);
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.ExecuteNonQuery();

            cmd.CommandText = "SELECT MAX(CustomerId) FROM Customers ";
            SqlDataReader dr = cmd.ExecuteReader();
            int pro1 = 0;
            while (dr.Read())
            {
                pro1 = Convert.ToInt32.(dr["CustomerId"].ToString());

                pro1++;
                 
            }
            dr.Close();
            
            con.Close();*/

            /*int c;
            int custoid;
            SqlCommand cmd2 = new SqlCommand("SELECT MAX(CustomerId) FROM Customers ", con);
            cmd2.CommandType = CommandType.Text;
            var rd = cmd2.ExecuteReader();
            c = 0;
            while (rd.Read())
            {
                c = Convert.ToInt32(rd["CustomerId"].ToString());

            }
            rd.Close();
            c++;
            custoid = c;
            //MessageBox.Show(c.ToString());*/
            
            /*var query = "Select MAX(CustomerId) from Customers";
            SqlCommand q = new SqlCommand();
            q.Connection = con;
            q.CommandText = query;
            SqlDataReader dr= q.ExecuteReader();
            //int id = 0;
            while (dr.HasRows)
            {
                dr.Read();
                Int32 count = Convert.ToInt32(q.ExecuteScalar());
                //id = Convert.ToInt32(dr["CustomerId"]);
                //customerid.Text = dr.GetString("customerid");
            }*/
            //id = Convert.ToInt32(dr["CustomerId"]);//.Read[0];// bin.Row[0].ToString();
            // how to read/show a single/max value from database using C# ADO.NET
            //customerid.Text = id.ToString();
            //dataGrid1.DataContext = binding;
            //con.Close();*/

            

            customerid.Text = string.Empty;
            if (customerid.IsEnabled != true)
            {
                customerid.IsEnabled = true;
            }
            customername.Text = string.Empty;
            city.Text = string.Empty;
            datePicker1.Text = string.Empty;
            

        }

        

        private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            datePicker1.Text = DateTime.Today.ToString();            
            
        }

        private void dataGrid1_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                this.BindGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }


       

        private void dataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            try
            {
                DataRowView _DataView = dataGrid1.CurrentCell.Item as DataRowView;

                if (_DataView != null)
                {
                    customerid.Text = _DataView.Row[0].ToString();
                    customerid.IsEnabled = false;
                    customername.Text = _DataView.Row[1].ToString();                    
                    city.Text = _DataView.Row[2].ToString();
                    datePicker1.Text = _DataView.Row[3].ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void customerid_TextChanged(object sender, TextChangedEventArgs e)
        {
            /*SqlConnection con = new SqlConnection(dataconnection);
            con.Open();
            string s = "select max(CustomerId)+1 from Customers";
            SqlCommand csm = new SqlCommand(s, con);
            csm.ExecuteNonQuery();
            SqlDataReader dd = csm.ExecuteReader();
            while (dd.Read())
            {
                int n = dd.GetInt32(0);
                customerid.Text = n.ToString();
            }

            con.Close();*/
            
        }
    }
}


//this is the xml code

XML
<window x:class="Project1.MainWindow" xmlns:x="#unknown">
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Customer Details" Name="CustomerDetails" Height="380" Width="521"  ResizeMode="CanMinimize" WindowStartupLocation="CenterScreen" WindowStyle="SingleBorderWindow" Loaded="Window_Loaded"&gt;
    <window.background>
        <lineargradientbrush endpoint="1,0.5" startpoint="0,0.5">
            <gradientstop color="#FF656C88" offset="0" />
            <gradientstop color="#FFB55454" offset="1" />
        </lineargradientbrush>
    </window.background>
    <grid>
        <grid.rowdefinitions>
            <rowdefinition height="41" />
            <rowdefinition height="41" />
            <rowdefinition height="41" />
            <rowdefinition height="41" />
            <rowdefinition height="231*" />
        </grid.rowdefinitions>
        &lt;Label Content="Customer ID" Height="28" HorizontalAlignment="Left" Margin="12,9,0,0" Name="custid" VerticalAlignment="Top" Width="96" FontFamily="Century Gothic" FontSize="12" FontWeight="Bold" Background="{x:Null}"&gt;
            &lt;Label.Foreground&gt;
                <lineargradientbrush endpoint="1,0.5" startpoint="0,0.5">
                    <gradientstop color="#FFFFC996" offset="0" />
                    <gradientstop color="#FFCB8551" offset="1" />
                </lineargradientbrush>
            &lt;/Label.Foreground&gt;
        &lt;/Label&gt;
        <textbox height="23" horizontalalignment="Left" margin="139,12,0,0" name="customerid" verticalalignment="Top" width="187" visibility="Visible" isenabled="True" textchanged="customerid_TextChanged" />
        &lt;Label Content="Customer Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="13,6,0,0" Name="custname" VerticalAlignment="Top" Width="111" FontFamily="Century Gothic" FontWeight="Bold"&gt;
            &lt;Label.Foreground&gt;
                <lineargradientbrush endpoint="1,0.5" startpoint="0,0.5">
                    <gradientstop color="#FFFFC996" offset="0" />
                    <gradientstop color="#FFCB8551" offset="1" />
                </lineargradientbrush>
            &lt;/Label.Foreground&gt;
        &lt;/Label&gt;
        <textbox grid.row="1" height="23" horizontalalignment="Left" margin="139,9,0,0" name="customername" verticalalignment="Top" width="187" />
        &lt;Label Content="Date" Grid.Row="2" Height="28" HorizontalAlignment="Left" Margin="14,8,0,0" Name="sdate" VerticalAlignment="Top" Width="94" FontFamily="Century Gothic" FontWeight="Bold"&gt;
            &lt;Label.Foreground&gt;
                <lineargradientbrush endpoint="1,0.5" startpoint="0,0.5">
                    <gradientstop color="#FFFFC996" offset="0" />
                    <gradientstop color="#FFCB8551" offset="1" />
                </lineargradientbrush>
            &lt;/Label.Foreground&gt;
        &lt;/Label&gt;
        <datepicker grid.row="2" height="25" horizontalalignment="Left" margin="139,10,0,0" name="datePicker1" verticalalignment="Top" width="187" />
        &lt;Label Content="City" Grid.Row="3" Height="28" HorizontalAlignment="Left" Margin="14,8,0,0" Name="City" VerticalAlignment="Top" Width="94" FontFamily="Century Gothic" FontWeight="Bold"&gt;
            &lt;Label.Foreground&gt;
                <lineargradientbrush endpoint="1,0.5" startpoint="0,0.5">
                    <gradientstop color="#FFFFC996" offset="0" />
                    <gradientstop color="#FFFFC996" offset="1" />
                    <gradientstop color="#FFCB8551" offset="1" />
                </lineargradientbrush>
            &lt;/Label.Foreground&gt;
        &lt;/Label&gt;
        <combobox grid.row="3" height="23" horizontalalignment="Left" margin="138,9,0,0" name="city" verticalalignment="Top" width="188" removed="White">
            <comboboxitem name="dhaka" content="Dhaka" />
            <comboboxitem name="chittagong" content="Chittagong" />
            <comboboxitem name="rajshahi" content="Rajshahi" />
        </combobox>
        &lt;Button Content="Add" Grid.Row="4" Height="23" HorizontalAlignment="Right" Margin="0,14,299,0" Name="Add_Btn" VerticalAlignment="Top" Width="70" Click="Add_Btn_Click" FontFamily="Terminator Two"&gt;
            &lt;Button.Background&gt;
                <lineargradientbrush endpoint="0.5,1" startpoint="0.5,0">
                    <gradientstop color="#FF176F80" offset="0" />
                    <gradientstop color="#FFD8A6A6" offset="1" />
                </lineargradientbrush>
            &lt;/Button.Background&gt;
        &lt;/Button&gt;
        &lt;Button Content="Delete" Grid.Row="4" Height="23" HorizontalAlignment="Left" Margin="231,13,0,0" Name="Del_Btn" VerticalAlignment="Top" Width="82" Click="Del_Btn_Click" FontFamily="Terminator Two"&gt;
            &lt;Button.Background&gt;
                <lineargradientbrush endpoint="0.5,1" startpoint="0.5,0">
                    <gradientstop color="#FF26829D" offset="0" />
                    <gradientstop color="#FFE5B0B0" offset="1" />
                </lineargradientbrush>
            &lt;/Button.Background&gt;
        &lt;/Button&gt;
        &lt;Button Content="Update" Grid.Row="4" Height="23" HorizontalAlignment="Right" Margin="0,13,101,0" Name="Update_Btn" VerticalAlignment="Top" Width="75" Click="Update_Btn_Click" FontFamily="Terminator Two"&gt;
            &lt;Button.Background&gt;
                <lineargradientbrush endpoint="0.5,1" startpoint="0.5,0">
                    <gradientstop color="#FF4C9ABA" offset="0" />
                    <gradientstop color="#FFD4AC9E" offset="1" />
                </lineargradientbrush>
            &lt;/Button.Background&gt;
        &lt;/Button&gt;
        &lt;Button Content="New" Grid.Row="4" Height="23" HorizontalAlignment="Left" Margin="48,14,0,0" Name="New_Btn" VerticalAlignment="Top" Width="76" Click="New_Btn_Click" FontFamily="Terminator Two"&gt;
            &lt;Button.Background&gt;
                <lineargradientbrush endpoint="0.5,1" startpoint="0.5,0">
                    <gradientstop color="#FF2395AA" offset="0" />
                    <gradientstop color="#FFEF9999" offset="1" />
                </lineargradientbrush>
            &lt;/Button.Background&gt;
        &lt;/Button&gt;
        <datagrid autogeneratecolumns="False" grid.row="4" height="104" horizontalalignment="Left" margin="12,52,0,0" name="dataGrid1" verticalalignment="Top" width="477" itemssource="{Binding Path=DataBind}" loaded="dataGrid1_Loaded" canuserresizerows="False" selectedcellschanged="dataGrid1_SelectedCellsChanged" selectionchanged="dataGrid1_SelectionChanged" verticalgridlinesbrush="#E652987C" snapstodevicepixels="False" fontweight="Bold" fontfamily="Times New Roman" fontsize="13" rowremoved="#97C9BFDE" foreground="Black">
            <datagrid.borderbrush>
                <lineargradientbrush endpoint="1,0.5" startpoint="0,0.5">
                    <gradientstop color="Black" offset="0" />
                    <gradientstop color="#FFA35D36" offset="1" />
                </lineargradientbrush>
            </datagrid.borderbrush>
            <datagrid.opacitymask>
                <lineargradientbrush endpoint="1,0.5" startpoint="0,0.5">
                    <gradientstop color="Black" offset="0" />
                    <gradientstop color="#FF964545" offset="1" />
                </lineargradientbrush>
            </datagrid.opacitymask>
            <datagrid.columns>
                <datagridtextcolumn binding="{Binding Path=CustomerId}" header="Customer ID" minwidth="100" width="120" isreadonly="True" />
                <datagridtextcolumn binding="{Binding Path=CustomerName}" header="Customer Name" width="120" isreadonly="True" />
                <datagridtextcolumn binding="{Binding Path=City}" header="City" width="120" isreadonly="True" />
                <datagridtextcolumn binding="{Binding Path=SDate}" header="Date" width="120" isreadonly="True" />
            </datagrid.columns>
        </datagrid>
    </grid>
</window>


i need to auto increment the Customer Id field.After clicking new button Customer ID field will be incremented by 1 and will be showed on text field, can anyone help?
Posted
Updated 29-Dec-12 8:54am
v2

1 solution

Why not use IDENTITY in the table instead. Have a look at http://msdn.microsoft.com/en-us/library/aa933196(v=sql.80).aspx[^].

This way you don't have to worry about the problem, what is the next value.

Generally I'd prefer even using uniqueidentifier[^].
 
Share this answer
 
v2
Comments
Espen Harlinn 30-Dec-12 8:11am    
Good points :-D
Wendelius 4-Jan-13 15:12pm    
Thanks :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900