Silverlight / WPF - how to eliminate the entry of string within the silverlight datagrid

Asked By Ramachandran on 25-Jun-12 02:22 AM
Earn up to 40 extra points for answering this tough question.
I am using silverlight datagrid in this only integer numbers and decimal numbers to be entered and string values are to be eliminated how to do i have tried on stringformat { ###.##} on the datagrid value field.... this is my xaml code.



 <sdk:DataGridTextColumn Header="Jan" Binding="{Binding Jan,Mode=TwoWay,StringFormat=\{0:d\}}"  CanUserReorder="True" CanUserResize="True" CanUserSort="True" Width="80">
                  <sdk:DataGridTextColumn.CellStyle  >
                    <Style TargetType="sdk:DataGridCell" >
                      <Style.Setters>
                        <Setter Property="HorizontalAlignment" Value="Right" />
                      </Style.Setters>
                    </Style>
                  </sdk:DataGridTextColumn.CellStyle>
                </sdk:DataGridTextColumn>
Jitendra Faye replied to Ramachandran on 26-Jun-12 12:56 AM
Try to use DataGridTemplateColumn.

Here you can use  NumericTextBox in DataGridTemplateColumn.CellEditingTemplate.



Try this and let me know.
Jitendra Faye replied to Ramachandran on 26-Jun-12 12:57 AM
Or if you want to do it by code then refer this links-

http://social.msdn.microsoft.com/Forums/hi-IN/wpf/thread/02099f48-7673-4fd0-a74d-605769e21a7d

Here you will get example for it.


Vikram Singh Saini replied to Ramachandran on 26-Jun-12 09:16 AM
Hello Ramachandran,

For your requirement, I created demo application and tested the solution by picking code guidance from http://social.msdn.microsoft.com/Forums/hi-IN/wpf/thread/02099f48-7673-4fd0-a74d-605769e21a7d. But the code line

txt.CaretIndex = txt.Text.Length; // TextBox doesn't contains definition for 'CaretIndex'

didn't worked successfully. I researched and tried lot for it but no luck. So the concerned code failed upto some extent.  So I created alternative solution for same using idea from there for objective 2.

Objectives Achieved:

(1) Remove string values on data bind.
If your database column contains string and numeric value both such as 9s.

(2) Only numeric values are allowed during editing.
When user type some text in TextBox they are can type both numeric and string values but only numeric values are returned to them in TextBox. In short, the TextBox behave as Numeric TextBox.

**************   REMOVE STRING VALUES ON DATA BIND **************

Before I start dwelling in actual code, allow me to share with you .xaml file structure for better understanding. Here:

<UserControl x:Class="SL_DataGrid_WCF.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"

    mc:Ignorable="d"

    d:DesignHeight="300" d:DesignWidth="400">

 

    <sdk:DataGrid AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="341,21,0,0" Name="myDataGrid"

          VerticalAlignment="Top" LoadingRow="myDataGrid_LoadingRow">

      <sdk:DataGrid.Columns>

        <sdk:DataGridTemplateColumn Header="ItemNumber" Width="Auto">

          <sdk:DataGridTemplateColumn.CellTemplate>

            <DataTemplate>

              <TextBox Text="{Binding ItemNumber}" Foreground="Green" VerticalAlignment="Center" x:Name="tb"

                   Loaded="tb_Loaded" TextChanged="tb_TextChanged"/>

            </DataTemplate>

          </sdk:DataGridTemplateColumn.CellTemplate>

          <sdk:DataGridTemplateColumn.CellEditingTemplate>

            <DataTemplate>

              <TextBox Text="{Binding ItemNumber, Mode=TwoWay}" />

            </DataTemplate>

          </sdk:DataGridTemplateColumn.CellEditingTemplate>

        </sdk:DataGridTemplateColumn>

        <sdk:DataGridTextColumn CanUserReorder="True" CanUserSort="True" Width="Auto" Binding="{Binding ItemDescription}"

          Header="ItemDescription"/>

        <sdk:DataGridTextColumn CanUserReorder="True" CanUserSort="True" Width="Auto" Binding="{Binding Quantity}"

          Header="Quantity"/>

      </sdk:DataGrid.Columns>

    </sdk:DataGrid>

</UserControl>

 


The first column ItemNumber contains text values as 9S, AI2 and so on. As you can notice we have used Loaded event handler, that would run after controls have been initialized and loaded. So in same we would check TextBox values & extract numbers from it. Code here (in .xaml.cs):

      // Fires after control loaded

      private void tb_Loaded(object sender, RoutedEventArgs e)

      {

        TextBox txtBox = sender as TextBox;      

 

        string numbers = ExtractNumbers(txtBox.Text.ToString());

 

        if (!String.IsNullOrEmpty(numbers))        

          txtBox.Text = numbers;

      }       

 

      // Returns integer or double (no string)

      static string ExtractNumbers(string input)

      {

        string numberInText = null;

        numberInText = string.Join(null, System.Text.RegularExpressions.Regex.Split(input, "[^.\\d]"));

        return numberInText;

      }


Now the first column in DataGrid would show only numeric values.

**************   ONLY NUMERIC VALUES ARE ALLOWED DURING EDITING **************

For this objective we have used the suggestion from the link: http://social.msdn.microsoft.com/Forums/hi-IN/wpf/thread/02099f48-7673-4fd0-a74d-605769e21a7d as shared by Vickey F.

But the code part that was used for refusing string values in the link code has been modified by me as it was not working. We have used TextChanged event handler of TextBox (See .xaml code above). Here is the TextChanged EventHandler code:

private void tb_TextChanged(object sender, TextChangedEventArgs e)

      {

        TextBox txt = sender as TextBox;

        if (txt != null)

        {

          txt.Text = ExtractNumbers(txt.Text);

        }

      }     

 

      // Returns integer or double (no string)

      static string ExtractNumbers(string input)

      {

        string numberInText = null;

        numberInText = string.Join(null, System.Text.RegularExpressions.Regex.Split(input, "[^.\\d]"));

        return numberInText;

      }


So now whenever user types in the first column of the DataGrid, he/she would only see numeric values (no string values).

Do let us know if left any questions or doubts.


help
hi all, i want to add rows in wpf datagrid. top row of the grid i want to give the provision for adding new rows can anyone help to do this? Thanks. . Arif To programatically add a row: DataGrid.Items.Add(new DataItem()); To programatically add a column: DataGrid.Columns.Add(new DataGridTextColumn()); Check out this post on the WPF DataGrid discussion board for more information. http: / / wpf.codeplex.com / Thread / View.aspx?ThreadId = 34065 keywords Silverlight, Silverlight WPF, DataGrid, WPF, Thread, Check, rows description: add rows in wpf Datagrid hi all
hello frnd how to get chech box checked or not in datagrid . i want info to when i change the the checked or uncheked of check box in datagrid, . how can i do this operations and which event. Try like this- CheckBox chk = myDataGrid Try this and let me know. You have to use datagridcheckboxcolumn like thi s < data:DataGrid Name = "myGrid" AutoGenerateColumns = "False" > < data:DataGrid.Columns > < data:DataGridCheckBoxColumn Binding = "{Binding Chosen, Mode = TwoWay}" / > < data:DataGridTextColumn Binding = "{Binding Name}" / > < / data:DataGrid.Columns > < / data:DataGrid > Refer this link http: / / forums.silverlight.net / t / 36172.aspx / 1?Datagrid
i hav a silverlight data gird control in which i hav datagridtemplate column. as < Data : DataGridTextColumn Width = "25" Binding = "{ Binding UserName }" > and <data:DataGridTemplateColumn Header = "Role" Width = "138"> <data:DataGridTemplateColumn.CellTemplate not like windows gridview. http: / / www.codeproject.com / KB / WPF / WPFDataGridExamples.aspx thank you keywords: Silverlight, WPF description: access value from datagrid i hav a silverlight data gird control in which i hav datagridtemplate column. asand &n. . . 28-Oct-12 08
Hello Everybody, Can anybody help me?How to import data from excel file to silverlight datagrid? Thanks & Regards Toral Shah private string ReadUserXMLFile() { OpenFileDialog dlg = new OpenFileDialog (); dlg.Multiselect = false ; dlg var xml = reader.ReadToEnd(); return xml; } http: / / www.c-sharpcorner.com / UploadFile / mgold / 1133 / Hi, Silverlight cannot visit excel files directly. If you want to show the excel data to Grid / DataGrid, we'd better first get the data from WCF. WCF / WebService can fetch the data and organize them into a return object. Now we can call the WCF on Silverlight and bind the return object. or try this ExcelLite an open source C# library for
Hi, I am now blank with this issue doing mistake…all the rows been filled in grid are showing blank. . Grid definition…. . . . . . . . . . . . . . . . . < sdk : DataGrid Name = "dgrIncidents" AutoGenerateColumns = "False" HeadersVisibility = "All" RowBackground = "Cornsilk" AlternatingRowBackground = "LemonChiffon" IsReadOnly = "True" CanUserResizeColumns = "True" GridLinesVisibility = "All"> < sdk : DataGrid.Columns > < sdk : DataGridTextColumn CanUserReorder = "True" CanUserResize = "True" CanUserSort = "True" Width = "Auto" Header = "Reported Date" Binding = "{ Binding Reported_Date }" / > < sdk DataGridTextColumn CanUserReorder = "True" CanUserResize = "True" CanUserSort = "True" Width = "Auto" Header = "Incident ID" Binding = "{ Binding Incident_ID }" / > < sdk : DataGridTextColumn CanUserReorder = "True" CanUserResize = "True" CanUserSort = "True" Width = "Auto" Header = "Closed Date" Binding = "{ Binding Closed_Date }" / > < sdk
Hi, I have successfully managed to bind a silverlight datagrid to a web service which works fine. However, I have decided to build the datagrid programatically in order for the user to add multiple datagrids by clicking a button. I ve attached my code below, you can see an additional datagrid is being populated by Private Sub mService_GetContactsCompleted However, I won't know what the datagrid name is so this needs to be made dynamic. I guess the ultimate answer would
The WPF DataGrid is meant for showing a large amount of data. Due to this, it is confusing first way to set alternate row colors is by setting the AlternatingRowBackground property of the DataGrid. < DataGrid AutoGenerateColumns = "False" AlternatingRowBackground = "LightBlue" Loaded = "DataGrid_Loaded"> <DataGrid.Columns> < DataGridTextColumn Header = "Column" Binding = "{Binding}" / > < / DataGrid.Columns> < / DataGrid > I used the Loaded event of the DataGrid to fill it up with
I have filled the itemsource with List of class whose variables are same as datagrid columns. But after assigning itemsource to datagrid, grid is showing total rows but there is not data in that rows(infact empty because sometime it happens the text is displaying with background color. . No. its simple default datagrid Its nice one gives a lots of data on topic also give more data on metioned everything needed here. . whet else you want. . Here are more details. . Grid definition. . < sdk : DataGrid Name = "dgrIncidents" AutoGenerateColumns = "False" IsReadOnly = "True" > < sdk : DataGrid.Columns > < sdk : DataGridTextColumn CanUserReorder = "True" CanUserResize = "True" CanUserSort = "True" Width = "Auto" Header = "Reported Date" Binding
Hello all, I was earlier looking fora way to build a hierarchical datagrid that groups the rows based on one of the column values. . With some of your suggestions and the help of the following links i had built a hierarchical datagrid. www.Wpftutorial.com and http: / / blog.smoura.com / wpf-toolkit-datagrid-part-iv-templatecolumns-and-row-grouping / Now that i have achieved 50% of the requirement i need your help to improve my grid. this is how the datagrid looks. the improvement needed is the expander header is empty but i want it to goes as follows < CollectionViewSource x : Key = "Details"> < CollectionViewSource.GroupDescriptions > < PropertyGroupDescription PropertyName = "Column1" / > < / CollectionViewSource.GroupDescriptions > < / CollectionViewSource > < DataGrid.GroupStyle > < GroupStyle > < GroupStyle.ContainerStyle > < Style TargetType = "{ x : Type GroupItem }"> < Setter Property = "Template"> < Setter.Value > < ControlTemplate Text > < / TextBlock > < / StackPanel > < / Expander.Header > < ItemsPresenter / > < / Expander > < / ControlTemplate > < / Setter.Value > < / Setter > < / Style > < / GroupStyle.ContainerStyle > < / GroupStyle > < / DataGrid.GroupStyle > The code behind is this: Public Sub New () ' This call is required by the