Click here to Skip to main content
14,299,038 members
Rate this:
Please Sign up or sign in to vote.
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:
<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

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
Rate this:
Please Sign up or sign in to vote.

Solution 4

and Update your codebehind as follows

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:

<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>
   
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
prapaug 11-Jul-13 4:55am
   
Thanx..its working now.
but now i have another error.it says :
'xmlns:x' is a duplicate attribute name. Line 3, position 9.' XML is not valid.
what should i do..???
Raman Midha 11-Jul-13 5:01am
   
why u have written xmlns:x="unknown" ?
Raman Midha 11-Jul-13 5:03am
   
you dont need to write xmlns:x
prapaug 11-Jul-13 5:24am
   
now i have the error:
Error 6 The name 'textbox2' does not exist in the current context
and
The name textbox1 doen not exist in the current context.
please help
prapaug 11-Jul-13 5:29am
   
That error is cleared.Now i have only one more error.That is:

Error 1 The type 'WpfApplication13.MainWindow' already contains a definition for 'datagrid1'

Please help me fast.
prapaug 11-Jul-13 5:40am
   
this is my modified .cs file:



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;


namespace WpfApplication13
{
public partial class MainWindow: Window
{
DataGrid datagrid1 = new DataGrid();
public MainWindow()
{

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 Window_Loaded(object sender, RoutedEventArgs e)
{

}

private void textbox1_TextChanged(object sender, TextChangedEventArgs e)
{

}

private void textbox2_TextChanged(object sender, TextChangedEventArgs e)
{

}

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

private void datagrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{

}

}
}

and following is my xaml code:


<window x:class="WpfApplication13.MainWindow"
="" 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="Window3" height="300" width="300">
<grid>
<textbox height="23" horizontalalignment="Left" margin="12,12,0,0" x:name="textbox1" verticalalignment="Top" width="120" textchanged="textbox1_TextChanged">
<textbox height="23" horizontalalignment="Right" margin="12,12,0,0" x:name="textbox2" verticalalignment="Top" width="120" textchanged="textbox2_TextChanged">
<datagrid autogeneratecolumns="False" x:name="datagrid2" selectionchanged="datagrid1_SelectionChanged" datacontext="{Binding DGSource}" canuseraddrows="{Binding ElementName=datagrid1}" canuserdeleterows="{Binding ElementName=datagrid1}" minrowheight="1" margin="12,41,12,79" 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">


<Button Name="btn" Content="ADD" Margin="33,0,29,20" Height="35" Click="button1_Click" VerticalAlignment="Bottom"/>






BUT I CANT ADD MY FIELDS TO DATAGRID STILL.WHAT WILL BE THE PROBLEM???
please help me.
Raman Midha 11-Jul-13 5:46am
   
i posted xaml so y u are creating datagrid object from codebehind

Remove Line DataGrid datagrid1=new DataGrid();

Just copy my xaml and cs file .........
prapaug 11-Jul-13 5:58am
   
its working.................
THANK YOU FOR YOUR HELP.
looking forward for more helpls
THANK you AGAIN
prapaug 11-Jul-13 6:01am
   
Can you please explain how its working???
Rate this:
Please Sign up or sign in to vote.

Solution 1

Just write following code on button click event

#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
   
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
Rate this:
Please Sign up or sign in to vote.

Solution 2

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;
        }
   
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?
Rate this:
Please Sign up or sign in to vote.

Solution 3

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

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

<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
public MainWindow()
        {
            InitializeComponent();
           // DGSource = new DataGridSource();
            //DGSource.DGItemsSource = new ObservableCollection<userinfo>();      
            datagrid1.DataContext = new DataGridSource();
             SetInitialValues();
        }


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)
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100