Click here to Skip to main content
15,888,301 members
Please Sign up or sign in to vote.
3.22/5 (3 votes)
See more:
i have two textboxes and an add button and a datagrid with 2 coloumns.what i need to do is when i press the button the contents in the textboxes should move into a datagrid. textboxes names are textbox1 and textbox2.the contents in first textbox should move to first coloumn in datagrid,and contents of textbox2 to second coloumn of datagrid.Next contents should move to next row and so on.Someone please help me.Thanks in advance


This is my XAML code:
HTML
<window x:class="WpfApplication9.MainWindow" xmlns:x="#unknown">
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit"
        Title="MainWindow" Height="347" Width="570" DataContext="{Binding}" Loaded="Window_Loaded">
    <grid>
        <textbox height="23" horizontalalignment="Left" margin="34,32,0,0" name="textbox1" verticalalignment="Top" width="120" textchanged="textbox1_TextChanged" />

        <textbox height="23" horizontalalignment="Left" margin="34,205,0,0" name="textbox2" verticalalignment="Top" width="120" textchanged="textbox2_TextChanged" />

        <Button Content="ADD" Height="23" HorizontalAlignment="Left" Margin="193,108,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" >

        <datagrid autogeneratecolumns="False" removed="Gray" height="311" itemssource="{Binding}" horizontalalignment="Right" name="datagrid1" verticalalignment="Center" width="202" selectionchanged="dataGrid1_SelectionChanged" datacontext="{Binding}" canuseraddrows="{Binding ElementName=dataGrid1}" canuserdeleterows="{Binding ElementName=dataGrid1}" minrowheight="1" rowremoved="#FF95FFFF" margin="0,-2,0,0" fontweight="Bold">

           <datagrid.columns>
                <datagridtextcolumn header="Name" width="100" canuserresize="False" binding="{Binding}" canuserreorder="False" />

                <datagridtextcolumn header="ID" width="100" canuserresize="False" binding="{Binding}" canuserreorder="False" />

                </datagrid.columns>
        </datagrid>
    </grid>
</window>






And this is my Xaml.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;
namespace WpfApplication9
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            SetInitialValues();
        }
     
          void SetInitialValues()
           {
            textbox1.Text = "";
			textbox2.Text = "";
           }

            private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {

            }

            private void Window_Loaded(object sender, RoutedEventArgs e)
            {

            }

            private void textbox1_TextChanged(object sender, TextChangedEventArgs e)
            {

            }

            private void textbox2_TextChanged(object sender, TextChangedEventArgs e)
            {

            }

            private void button1_Click(object sender, RoutedEventArgs e)
            {

            }


    }
}
Posted
Updated 10-Jul-13 19:33pm
v5

and Update your codebehind as follows

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.Shapes;
using System.Data;

namespace RowDetailTemplate
{
    /// <summary>
    /// Interaction logic for Window3.xaml
    /// </summary>
    public partial class Window3 : Window
    {
        public Window3()
        {
            InitializeComponent();
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("ID");
            DataRow dr = dt.NewRow();
            dr["Name"] = "Raman";
            dr["ID"] = "Raman";
            dt.Rows.Add(dr);
            datagrid1.ItemsSource = dt.DefaultView;
        }
        private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void textbox1_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void textbox2_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            DataView dv = datagrid1.ItemsSource as DataView;
            DataTable dt = dv.Table;
            DataRow dr = dt.NewRow();
            dr["Name"] = textbox1.Text;
            dr["ID"] = textbox2.Text;
            dt.Rows.Add(dr);
        }
 
    }
}



and update your xaml as:

XML
<window x:class="RowDetailTemplate.Window3" xmlns:x="#unknown">
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:wpf="http://schemas.microsoft.com/wpf/2008/toolkit"
    Title="Window3" Height="300" Width="300"&gt;
    <grid>
        <textbox height="23" horizontalalignment="Left" margin="12,12,0,0" x:name="textbox1" verticalalignment="Top" width="120" textchanged="textbox1_TextChanged" />

        <textbox height="23" margin="0,12,12,0" x:name="textbox2" verticalalignment="Top" textchanged="textbox2_TextChanged" horizontalalignment="Right" width="120" />
        <wpf:datagrid autogeneratecolumns="False" x:name="datagrid1" selectionchanged="dataGrid1_SelectionChanged" datacontext="{Binding DGSource}" canuseraddrows="{Binding ElementName=dataGrid1}" canuserdeleterows="{Binding ElementName=dataGrid1}" minrowheight="1" margin="12,41,12,79" fontweight="Bold" xmlns:wpf="#unknown">
            <wpf:datagrid.columns>
                <wpf:datagridtextcolumn header="Name" width="100" canuserresize="False" binding="{Binding Name}" canuserreorder="False" />
                <wpf:datagridtextcolumn header="ID" width="100" canuserresize="False" binding="{Binding ID}" canuserreorder="False" />
            </wpf:datagrid.columns>
        </wpf:datagrid>
        <button name="btn" content="click" margin="33,0,29,20" height="35" click="button1_Click" verticalalignment="Bottom" />
    </grid>
</window>
 
Share this answer
 
v3
Comments
prapaug 11-Jul-13 3:12am    
i'm not having a datatable keyword.
Raman Midha 11-Jul-13 3:29am    
u can add reference to add datatable keyword System.Data
prapaug 11-Jul-13 3:33am    
how?
prapaug 11-Jul-13 4:45am    
i din't find datatable keyword in wpf.what will i do now??
Raman Midha 11-Jul-13 4:50am    
its not datatable ..... Its DataTable under System.Data namespace

Using System.Data;

then u will have DataTable keyword
Just write following code on button click event

C#
#Fetch grid datasource as datatable and update datatable and bind with grid again

  DataView dv = datagrid1.ItemsSource as DataView;
            DataTable dt = dv.Table;
            DataRow dr = dt.NewRow();
            dr["Column1Name"] = textbox1.Text;
            dr["Column2Name"] = textbox2.Text;
            dt.Rows.Add(dr);

//Again Bind Datatable with grid 
 grid1.ItemsSource = dt.DefaultView;


if you need solution as an example i can forward you ........

If you find this is right answer plese mark it as accepted answer
 
Share this answer
 
v2
Comments
prapaug 11-Jul-13 2:27am    
can you please edit my xaml code and xaml.cs code?I want the full solution.Please do it as soon as possible.Thanks for your reply
C#
DataTable dt = new DataTable();
        public MainWindow()
        {
            InitializeComponent();
           
            dt.Columns.Add("column1");
            dt.Columns.Add("column2");
            dataGrid1.ItemsSource = dt.DefaultView;
        }
 

    private void button1_Click(object sender, RoutedEventArgs e)
        {
            DataRow row = dt.NewRow();
            row[0] = textBox1.Text;
            row[1] = textBox2.Text;
            dt.Rows.Add(row);
            dataGrid1.ItemsSource = dt.DefaultView;
        }
 
Share this answer
 
Comments
prapaug 11-Jul-13 2:28am    
i'm not able to create an object dt of datatable.why is it like that?
Sadique KT 11-Jul-13 3:02am    
Where u have declared datatable?
If you wish to do it with completely binding, (without setting the itemsource in codebehind),find the below solution
Create a class with the properties you required like Name and ID which should implement
INotifyPropertyChanged
C#
public class UserInfo: INotifyPropertyChanged
{
    private string _name;
    public string Name {
        get { return _name; }
        set { _name = value; onPropertyChanged(this, "Name"); }
    }
    public int _ID;
    public int ID {
        get { return _ID; }
        set { _grade = value; onPropertyChanged(this, "ID"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void onPropertyChanged(object sender, string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
        }
    }
}


Create another class which holds the collection of UserInfo and set this class as a DataContext to datagrid

C#
public class DataGridSource : INotifyPropertyChanged
    {
        public DataGridSource()
        {
            DGItemsSource = new ObservableCollection<userinfo>();       
        }
        private ObservableCollection<userinfo> _ItemsSource;
        public ObservableCollection<userinfo> DGItemsSource
        {
            get { return _ItemsSource; }
            set { _ItemsSource = value; onPropertyChanged(this, "DGItemsSource"); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void onPropertyChanged(object sender, string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
            }
        }
    }


Modify your XAML like this

HTML
<datagrid autogeneratecolumns="False" height="311" itemssource="{Binding DGItemsSource}" horizontalalignment="Right" name="datagrid1" verticalalignment="Center" width="202" selectionchanged="dataGrid1_SelectionChanged" DataContext="{Binding DGSource}" CanUserAddRows="{Binding ElementName=dataGrid1}" CanUserDeleteRows="{Binding ElementName=dataGrid1}" MinRowHeight="1" Margin="0,-2,0,0" FontWeight="Bold">
           <datagrid.columns>
               <datagridtextcolumn header="Name" width="100" canuserresize="False" binding="{Binding Name}" canuserreorder="False" />
               <datagridtextcolumn header="ID" width="100" canuserresize="False" binding="{Binding ID}" canuserreorder="False" />
           </datagrid.columns>
       </datagrid>


Modify youe constructor to
C#
public MainWindow()
        {
            InitializeComponent();
           // DGSource = new DataGridSource();
            //DGSource.DGItemsSource = new ObservableCollection<userinfo>();      
            datagrid1.DataContext = new DataGridSource();
             SetInitialValues();
        }


C#
private void button1_Click(object sender, RoutedEventArgs e)
            {
 		(datagrid1.DataContext as DataGridSource).DGItemsSource.Add(new UserInfo() { Name = textbox1.Text, ID = Convert.ToInt32(textbox2.Text) });             
            }
Note:Use exception handling wherever required( converting textbox2.Text to int)
 
Share this answer
 
v3
Comments
prapaug 11-Jul-13 2:44am    
so you want me to add a class like this?
public class INotifyPropertyChanged
{
public string Name;
public string ID;
}
is this enough?
Naz_Firdouse 11-Jul-13 2:52am    
I clearly mentioned the class UserInfo,how it should be.
You can use the same class
prapaug 11-Jul-13 3:02am    
its showin an error like:
Error 4 The type or namespace name 'userinfo' could not be found (are you missing a using directive or an assembly reference?)
Naz_Firdouse 11-Jul-13 5:02am    
where did u added that class???within the same page???

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