What is DataGrid in SilverLight?

DataGrid

DataGrid control is one of the most important control in Silverlight to develop Line-of-Business (As per Wiki - Line of business (LOB) is a general term which often refers to a set of one or more highly related products which service a particular customer transaction or business need.) applications and is mostly used to List the records in tabular format.
Apart from listing the records, it also provides option to sort, re-arrange columns, resize columns, edit data etc.

How to list the records in the DataGrid?
    *** Code ***

<grid x:name="LayoutRoot" background="White">
<StackPanel>
<Button x:Name="Button1" Content="FillData" Click="Button1_Click" Height="30" Width="75" Margin="20, 10, 0, 20"/>
<sdk:DataGrid x:Name="DataGrid1" AutoGenerateColumns="True" />
</StackPanel>
</grid>

In the above code, we have a Button control; on click of the button we are executing Button1_Click server side method.
Next, we have DataGrid control with AutoGenerateColumns attribute set to true that automatically generates the columns based on the properties found in the data source.


Code behind
private void Button1_Click(object sender, RoutedEventArgs e)
{
FillData();
}
private void FillData()
{
IList<Person> list = new List<Person>();
Person p = new Person
{
Age = 1,
FirstName= "Joe",
LastName ="Elan",
IsActive =true
};
Person p1 = new Person
{
Age = 15,
FirstName= "Mike",
LastName ="Bull",
IsActive =true
};
Person p2 = new Person
{
Age = 51,
FirstName= "Mukul",
LastName ="Alwa",
IsActive =true
};
Person p3 = new Person
{
Age = 31,
FirstName= "Sheo",
LastName ="Narayan",
IsActive =true
};
list.Add(p);
list.Add(p1);
list.Add(p2);
list.Add(p3);
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public bool IsActive { get; set; }
}

In the above code snippet, in the Button1_Click method we are calling FillData method. In the FillData method, we have instantiated the Person class and set its value and added to the Generic collection.
At last we have set the ItemsSource of the DataGrid to the generic list collection.

Output



 

How to customize the DataGrid’s columns data?

DataGrid has several columntypes to customize the look and feel of the DataGrid columns.
DataGridTextColumn
It allows keeping the textfield type value in the DataGrid. Sorting of this column is inherited out ofthe box.
DataGridCheckBoxColumn
It allows keeping the Booleanfield type value in the DataGrid. Sorting of this column is inherited out ofthe box.
DataGridTemplateColumn
It allows keeping type of datathat can’t be kept in above two column type, eg. Images, it also allows keepingcustom data along with other field type value in the DataGrid. Sorting of thiscolumn is NOT inherited out of the box, you need to write your own logic tosupport sorting of this column.
Code
<sdk:datagrid x:name="DataGrid1"autogeneratecolumns="False" margin="10 10 10 10">
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn Header="Full Name">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FirstName}" x:Name="t1"/>
<TextBlock Text="{Binding LastName}" x:Name="t2"/>
</StackPanel>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
<sdk:DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
<sdk:DataGridCheckBoxColumn Header="Is Active?" Binding="{Binding IsActive}"/>
</sdk:DataGrid.Columns>
</sdk:datagrid>





In the above code snippet, we have set DataGrid’s AutoGenerateColumns property to false so its column will not beautomatically generated based on the properties of the DataSource.
We have used DataGridTemplateColumn with its CellTemplate that let us specify the template for thedata in read only mode. We will see how to specify template for edit mode lateron. In the CellTemplate, wehave specified the DataTemplate for FirstName and LastName (TextBlocks inthe StackPanel, you can’t keep TextBlock directly inside the DataTemplate.
To display the Age data, wehave specified DataGridTextColumn and to display Active data we havespecified DataGridCheckBoxColumn column type.
Codebehind
public DataGridCustomColumn()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(DataGridCustomColumn_Loaded);
}
void DataGridCustomColumn_Loaded(object sender, RoutedEventArgs e)
{
FillData();
}
private void FillData()
{
IList<Person> list = new List<Person>();
Person p = new Person
{
Age = 1,
FirstName= "Joe",
LastName ="Elan",
IsActive =true
};
Person p1 = new Person
{
Age = 15,
FirstName= "Mike",
LastName ="Bull",
IsActive =true
};
Person p2 = new Person
{
Age = 51,
FirstName= "Mukul",
LastName ="Alwa",
IsActive =true
};
Person p3 = new Person
{
Age = 31,
FirstName= "Sheo",
LastName ="Narayan",
IsActive =true
};
list.Add(p);
list.Add(p1);
list.Add(p2);
list.Add(p3);
DataGrid1.ItemsSource= list;
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public bool IsActive { get; set; }
} 
In the above code snippet, wehave attached DataGridCustomColumn_Loaded method to the Loaded event of the page. Inthis method we have called FillData.
In the FillData method, we havecreated a Generic list collection and added Person object and then set theItemSource property of the DataGrid to the generic list collection.

Output

 



DataGrid

DataGrid control is one of the most important control in Silverlight to develop Line-of-Business (As per Wiki - Line of business (LOB) is a general term which often refers to a set of one or more highly related products which service a particular customer transaction or business need.) applications and is mostly used to List the records in tabular format.
Apart from listing the records, it also provides option to sort, re-arrange columns, resize columns, edit data etc.

How to list the records in the DataGrid?
    *** Code ***

<grid x:name="LayoutRoot" background="White">
<StackPanel>
<Button x:Name="Button1" Content="FillData" Click="Button1_Click" Height="30" Width="75" Margin="20, 10, 0, 20"/>
<sdk:DataGrid x:Name="DataGrid1" AutoGenerateColumns="True" />
</StackPanel>
</grid>

In the above code, we have a Button control; on click of the button we are executing Button1_Click server side method.
Next, we have DataGrid control with AutoGenerateColumns attribute set to true that automatically generates the columns based on the properties found in the data source.


Code behind
private void Button1_Click(object sender, RoutedEventArgs e)
{
FillData();
}
private void FillData()
{
IList<Person> list = new List<Person>();
Person p = new Person
{
Age = 1,
FirstName= "Joe",
LastName ="Elan",
IsActive =true
};
Person p1 = new Person
{
Age = 15,
FirstName= "Mike",
LastName ="Bull",
IsActive =true
};
Person p2 = new Person
{
Age = 51,
FirstName= "Mukul",
LastName ="Alwa",
IsActive =true
};
Person p3 = new Person
{
Age = 31,
FirstName= "Sheo",
LastName ="Narayan",
IsActive =true
};
list.Add(p);
list.Add(p1);
list.Add(p2);
list.Add(p3);
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public bool IsActive { get; set; }
}

In the above code snippet, in the Button1_Click method we are calling FillData method. In the FillData method, we have instantiated the Person class and set its value and added to the Generic collection.
At last we have set the ItemsSource of the DataGrid to the generic list collection.

Output



 

How to customize the DataGrid’s columns data?

DataGrid has several columntypes to customize the look and feel of the DataGrid columns.
DataGridTextColumn
It allows keeping the textfield type value in the DataGrid. Sorting of this column is inherited out ofthe box.
DataGridCheckBoxColumn
It allows keeping the Booleanfield type value in the DataGrid. Sorting of this column is inherited out ofthe box.
DataGridTemplateColumn
It allows keeping type of datathat can’t be kept in above two column type, eg. Images, it also allows keepingcustom data along with other field type value in the DataGrid. Sorting of thiscolumn is NOT inherited out of the box, you need to write your own logic tosupport sorting of this column.
Code
<sdk:datagrid x:name="DataGrid1"autogeneratecolumns="False" margin="10 10 10 10">
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn Header="Full Name">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FirstName}" x:Name="t1"/>
<TextBlock Text="{Binding LastName}" x:Name="t2"/>
</StackPanel>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
<sdk:DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
<sdk:DataGridCheckBoxColumn Header="Is Active?" Binding="{Binding IsActive}"/>
</sdk:DataGrid.Columns>
</sdk:datagrid>





In the above code snippet, we have set DataGrid’s AutoGenerateColumns property to false so its column will not beautomatically generated based on the properties of the DataSource.
We have used DataGridTemplateColumn with its CellTemplate that let us specify the template for thedata in read only mode. We will see how to specify template for edit mode lateron. In the CellTemplate, wehave specified the DataTemplate for FirstName and LastName (TextBlocks inthe StackPanel, you can’t keep TextBlock directly inside the DataTemplate.
To display the Age data, wehave specified DataGridTextColumn and to display Active data we havespecified DataGridCheckBoxColumn column type.
Codebehind
public DataGridCustomColumn()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(DataGridCustomColumn_Loaded);
}
void DataGridCustomColumn_Loaded(object sender, RoutedEventArgs e)
{
FillData();
}
private void FillData()
{
IList<Person> list = new List<Person>();
Person p = new Person
{
Age = 1,
FirstName= "Joe",
LastName ="Elan",
IsActive =true
};
Person p1 = new Person
{
Age = 15,
FirstName= "Mike",
LastName ="Bull",
IsActive =true
};
Person p2 = new Person
{
Age = 51,
FirstName= "Mukul",
LastName ="Alwa",
IsActive =true
};
Person p3 = new Person
{
Age = 31,
FirstName= "Sheo",
LastName ="Narayan",
IsActive =true
};
list.Add(p);
list.Add(p1);
list.Add(p2);
list.Add(p3);
DataGrid1.ItemsSource= list;
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public bool IsActive { get; set; }
} 
In the above code snippet, wehave attached DataGridCustomColumn_Loaded method to the Loaded event of the page. Inthis method we have called FillData.
In the FillData method, we havecreated a Generic list collection and added Person object and then set theItemSource property of the DataGrid to the generic list collection.

Output

 



How to validate a textbox for range of values,correct date?

How to validate a textbox for range of values,correct date?

In scenarios where we want to validate a textbox for the specific range of values, and ensure that the correct Date to be entered, we can follow this approach.

Validations
Validation controls are used to validate the form fields for valid data when it is submitted to the server.
  • In case we want to validate a textbox for the specific range of values to be entered, we can follow this approach.
ASPX PAGE 

Enter year between 2000 to 2010:
<asp:TextBox ID="txtRange" runat="server" /><br />
<asp:RangeValidator ID="range1" runat="server" ErrorMessage="Sorry, must be
between 2000 and 2010" ControlToValidate="txtRange" MaximumValue="2010" MinimumValue="2000"
Type="Integer" ForeColor="Red" />
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</p> 

In the above code snippet, we have a TextBox that must accept the value in between 2000 and 2010. To validate this range, we can use asp:RangeValidator with MaximumValue as 2010 and MinimumValue as 2000 with Type as “Integer”. This causes the TextBox to accept only values in between 2000 to 2010.
Note: The asp:RangeValitor only works if any data is entered to the TextBox, if no data is entered and button is clicked the form is submitted to the server without validation. To avoid this, we should keep asp:RequiredFieldValidator attached with the TextBox to validate.


Note: Similarly Date, Double, String, Currency values can be validated for specific range.

  • In case we want to validate a textbox value for the correct date, we can follow this approach.

ASPX PAGE

 

Date of birth:
<asp:TextBox ID="txtDOB" runat="server" /><br />
<asp:RequiredFieldValidator ID="req1" runat="server" ErrorMessage="Mandatory !" ControlToValidate="txtDOB"
ForeColor="Red" />
<asp:CompareValidator ID="comp1" runat="server" ErrorMessage="Date must be in
MM/DD/YYYY format" ControlToValidate="txtDOB" Type="Date" Operator="DataTypeCheck" ForeColor="Red" />
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</p> 


In the above code snippet, we have a TextBox that must accept correct date. To do that we can use asp:CompareValidator with Operator as “DataTypeCheck” and Type as “Date”. We have used asp:RequiredFieldValidator to force user to enter some data into the TextBox before the form is submitted to the server.


  • In scenarios where we want to check whether a valid email id has been entered into the TextBox or not, we can follow this approach.

ASPX PAGE

 

Your email:
<asp:TextBox ID="txtEmail" runat="server" Columns="50" />
<br />
<asp:RequiredFieldValidator ID="req1" runat="server" ErrorMessage="Mandatory !" ControlToValidate="txtEmail"
ForeColor="Red" />
<asp:RegularExpressionValidator ID="ReExp1" runat="server" ControlToValidate="txtEmail"
ErrorMessage="eg. abc@domain.com" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-
.]\w+)*"></asp:RegularExpressionValidator>
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="SubmitData" />
</p> 


CODE BEHIND
 
protected void SubmitData(object sender, EventArgs e)
{

}


In the above code snippet, we want to validate the TextBox for correct format of the email id. For that we have used asp:RegularExpressionValidator with ValidationExpression as “\w+([-+.']\w+)*@\w+([- .]\w+)*\.\w+([-.]\w+)*” that validates the TextBox data for correct email id format (eg. abc@domain.com).
We have used asp:RequiredFieldValidtor to force user to enter some data into the TextBox.

Hope this Post was useful. Thanks for reading.

Keep reading my forth coming Post s. To read my series of articles on ASP.NET,





How to validate a textbox for range of values,correct date?

In scenarios where we want to validate a textbox for the specific range of values, and ensure that the correct Date to be entered, we can follow this approach.

Validations
Validation controls are used to validate the form fields for valid data when it is submitted to the server.
  • In case we want to validate a textbox for the specific range of values to be entered, we can follow this approach.
ASPX PAGE 

Enter year between 2000 to 2010:
<asp:TextBox ID="txtRange" runat="server" /><br />
<asp:RangeValidator ID="range1" runat="server" ErrorMessage="Sorry, must be
between 2000 and 2010" ControlToValidate="txtRange" MaximumValue="2010" MinimumValue="2000"
Type="Integer" ForeColor="Red" />
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</p> 

In the above code snippet, we have a TextBox that must accept the value in between 2000 and 2010. To validate this range, we can use asp:RangeValidator with MaximumValue as 2010 and MinimumValue as 2000 with Type as “Integer”. This causes the TextBox to accept only values in between 2000 to 2010.
Note: The asp:RangeValitor only works if any data is entered to the TextBox, if no data is entered and button is clicked the form is submitted to the server without validation. To avoid this, we should keep asp:RequiredFieldValidator attached with the TextBox to validate.


Note: Similarly Date, Double, String, Currency values can be validated for specific range.

  • In case we want to validate a textbox value for the correct date, we can follow this approach.

ASPX PAGE

 

Date of birth:
<asp:TextBox ID="txtDOB" runat="server" /><br />
<asp:RequiredFieldValidator ID="req1" runat="server" ErrorMessage="Mandatory !" ControlToValidate="txtDOB"
ForeColor="Red" />
<asp:CompareValidator ID="comp1" runat="server" ErrorMessage="Date must be in
MM/DD/YYYY format" ControlToValidate="txtDOB" Type="Date" Operator="DataTypeCheck" ForeColor="Red" />
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</p> 


In the above code snippet, we have a TextBox that must accept correct date. To do that we can use asp:CompareValidator with Operator as “DataTypeCheck” and Type as “Date”. We have used asp:RequiredFieldValidator to force user to enter some data into the TextBox before the form is submitted to the server.


  • In scenarios where we want to check whether a valid email id has been entered into the TextBox or not, we can follow this approach.

ASPX PAGE

 

Your email:
<asp:TextBox ID="txtEmail" runat="server" Columns="50" />
<br />
<asp:RequiredFieldValidator ID="req1" runat="server" ErrorMessage="Mandatory !" ControlToValidate="txtEmail"
ForeColor="Red" />
<asp:RegularExpressionValidator ID="ReExp1" runat="server" ControlToValidate="txtEmail"
ErrorMessage="eg. abc@domain.com" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-
.]\w+)*"></asp:RegularExpressionValidator>
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="SubmitData" />
</p> 


CODE BEHIND
 
protected void SubmitData(object sender, EventArgs e)
{

}


In the above code snippet, we want to validate the TextBox for correct format of the email id. For that we have used asp:RegularExpressionValidator with ValidationExpression as “\w+([-+.']\w+)*@\w+([- .]\w+)*\.\w+([-.]\w+)*” that validates the TextBox data for correct email id format (eg. abc@domain.com).
We have used asp:RequiredFieldValidtor to force user to enter some data into the TextBox.

Hope this Post was useful. Thanks for reading.

Keep reading my forth coming Post s. To read my series of articles on ASP.NET,