Monday, February 24, 2014

Set GridView Lines and Pager background color in ASP.NET 4.5

Usually, in ASP.NET 2.0, setting the GridView lines through property should work. However in 4.5, it doesn't seem to render correctly. One blog pointed out to set the gridlines through it's row data bound property as demonstrated on the code below:
Aspx Markup
 <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" BorderColor="Black" BorderStyle="Solid"   
     PageSize="2" AllowPaging="True" OnRowDataBound="GridView1_RowDataBound" BackColor="White"   
       CellPadding="3">  
       <FooterStyle BackColor="White" ForeColor="#000066" />  
       <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
       <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Justify" Wrap="True" />  
       <RowStyle ForeColor="#000066" />  
       <SelectedRowStyle BorderColor="Red" BackColor="#669999" Font-Bold="True" ForeColor="White">  
       </SelectedRowStyle>  
       <SortedAscendingCellStyle BackColor="#F1F1F1" />  
       <SortedAscendingHeaderStyle BackColor="#007DBB" />  
       <SortedDescendingCellStyle BackColor="#CAC9C9" />  
       <SortedDescendingHeaderStyle BackColor="#00547E" />  
   </asp:GridView>  
   <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:GridviewConnectionString3 %>"   
     SelectCommand="SELECT * FROM [TempEmployees]">  
   </asp:SqlDataSource>  
Code Behind
Code:
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
            {
                foreach (TableCell tc in e.Row.Cells)
                {
                    tc.Attributes["style"] = "Border: 1px solid LightGray;";
                }
            }
            else
            {
                if (e.Row.RowType == DataControlRowType.Pager)
                {
                    e.Row.Cells[0].Attributes["style"] = "Border: 1px solid LightGray; background-color: #ded7d7;";
                }
            }
        }

Saturday, February 22, 2014

Add Connection on Data Source Controls not loading SQL Server 2012 server/instance name.

After installing SQL Server 2012 Developer Edition SP1 on my other laptop, I tried creating an ASP.NET app using SQL DataSource control as the datasource control of the GridView. But to no avail, the mssql server instance doesn't load on the server name dropdown contol as shown below:
The hardware specifications are as follows: Windows 8 Pro, Visual Studio 2008/2010/2012 and SQL Server 2012 Developer Edition SP1. However, on my other laptop which has a Windows 8.1 OS, the server names were loaded on the Server Name dropdown control. After experimenting for a few hours, I discovered a simple solution which is to Turn Off The Windows Firewall. After that, my sql server instance is loaded on the control as shown below:

Cheers!

'Microsoft.VisualStudio.Editor.Implementation.EditorPackage' package did not load correctly (Visual Studio 2012)

After installing updates for my Windows 8 laptop, I did a restart and opened a Visual Studio 2012 instance. Surprisingly, an error pops-up as stated by the title of this  Post. I did some search on Microsoft Knowledge Base and found a patch for it which is available for download. See the link below:
Update for Microsoft Visual Studio 2012 (KB2781514)
Greg

Tuesday, February 18, 2014

Linear Gradients not working in IE9 but working in Firefox and Chrome

I came across with linear gradients not working correctly in IE 9. One solution suggested by a popular forum is to utilize an image as the background of a particular element. Since I'm not a graphic designer, I searched for other solution. I came up with an alternative which is to embed an svg file instead of an image file as an element's background. The css code below won't work in IE 9.
 body   
 {  
    background-image: -ms-linear-gradient(top, #000, #666);  
 }  
Here's a solution using .svg file:
 <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">  
  <linearGradient id="g762" gradientUnits="userSpaceOnUse" x1="0%" y1="0%" x2="0%" y2="100%">  
   <stop stop-color="#000000" offset="0"/><stop stop-color="#666666" offset="1"/>  
  </linearGradient>  
  <rect x="0" y="0" width="1" height="1" fill="url(#g762)" />  
 </svg>  
Usage:
 body   
 {  
    background-image: url('./gradient.svg');   
 }  

Monday, February 17, 2014

Creating and consuming custom control events in C#

In my autocomplete textbox control, I have a listbox that shows the suggested items based on user input. However, as a requirement I want to create an event that will trigger once a selection has been done in the listbox and this event will be consumed in the calling program (Main Form). To do that, you must define a custom event.
After googling for a while, here are the references that made me accomplish the task:
Creating Custom Events in C#
Quick and Easy Custom Events
Cheers!

Thursday, February 13, 2014

Change WPF DataGridCell background color using IVMultiValueConverter

In a post by codefornothing in which He demonstrate the use of IMultiValueConverter using DataTable: The WPF Datagrid and Me, I decided to create a similar post in which the binding source is of type collection (Observable Collection). I encountered a few issues like how to replace the Binding Path values from binding to a strongly type class instead of DataTable. To get things started, here are the snippets:
Observable Class
Code:
public class StudentList : ObservableCollection<Student>
    {
        public StudentList()
        {
            Add(new Student{ID = 1, Age = 29, Name ="Jerby", Address="Cebu"});
            Add(new Student{ID = 2, Age = 28, Name ="Renz", Address="Cebu"});
            Add(new Student{ID = 3, Age = 23, Name ="Aya", Address="Leyte"});
            Add(new Student{ID = 4, Age = 33, Name ="Jeff", Address="Leyte"});
            Add(new Student{ID = 5, Age = 32, Name ="Greg", Address="Cebu"});
            Add(new Student{ID = 6, Age = 28, Name ="Idsel", Address="Bohol"});
            Add(new Student { ID = 7, Age = 27, Name = "Harold", Address = "Bohol" });
        }
    }

IMulticonverter Class
Code:
    public class DataGridCellHighlighter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
      var cell = (DataGridCell)values[0];
            
            if (cell.Column.SortMemberPath.Equals("Name"))
            {
                if (System.Convert.ToInt32(values[1]) >= 30)
                {
                    return new SolidColorBrush(Colors.CadetBlue);
                }
                else
                {
                    return new SolidColorBrush(Colors.Transparent);
                }
            }

            return new SolidColorBrush(Colors.Transparent);
        } 

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new SystemNotImplementedException();
        }
    }
Window Resource XAML
 <Window.Resources>  
     <src:DataGridCellHighlighter x:Key="DataGridCellHighlighter" />  
     <src:StudentList x:Key="StudentListData" />  
     <Style x:Key="HighlightCellStyle" TargetType="{x:Type DataGridCell}">  
       <Setter Property="DataGrid.Background">  
         <Setter.Value>  
           <MultiBinding Converter="{StaticResource DataGridCellHighlighter}" >  
             <MultiBinding.Bindings>  
               <Binding RelativeSource="{RelativeSource Self}"/>  
               <Binding Path="Age"/>  
             </MultiBinding.Bindings>  
           </MultiBinding>  
         </Setter.Value>  
       </Setter>  
     </Style>  
   </Window.Resources>  

Datagrid XAML
  <DataGrid Grid.Row="0"   
          Grid.Column="0"  
          Grid.RowSpan="3"   
          AutoGenerateColumns="False"   
          CanUserAddRows="False"   
          SelectionMode="Single"  
          SelectionUnit="Cell"  
          ItemsSource ="{Binding Path=StudentItems}"   
          CellStyle="{StaticResource HighlightCellStyle}"  
          Name="dgStudents">  
       <DataGrid.Columns>  
         <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" Width="120" IsReadOnly="True" />  
         <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}" MinWidth="100" IsReadOnly="True" />  
         <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" MinWidth="150" IsReadOnly="True" />  
         <DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" MinWidth="150" IsReadOnly="True" />  
       </DataGrid.Columns>  
     </DataGrid>  
Cheers!

Thursday, February 6, 2014

Change WPF DataGridCell background color using IValueConverter

Here's a solution in painting a specific DataGridCell using IValueConverter. The datagrid set's it's ItemSource property either using List object or Datatable object.
Resource markup:
  <Window.Resources>  
      <src:BorderBrushConverter x:Key="BorderBrushConverter" />  
   </Window.Resources>    
XAML markup:
 <DataGrid AutoGenerateColumns="False" CanUserAddRows="False" Grid.Row="2" Grid.Column="0" Name="dgStudents1">  
       <DataGrid.Columns>  
         <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" Width="120" IsReadOnly="True" />   
         <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}" MinWidth="100" IsReadOnly="True">  
           <DataGridTextColumn.CellStyle>  
             <Style TargetType="DataGridCell">  
              <Setter Property="Background" Value="{Binding Path=Age, Converter={StaticResource BorderBrushConverter}, ConverterParameter = 30, UpdateSourceTrigger=PropertyChanged}" />  
             </Style>  
           </DataGridTextColumn.CellStyle>  
         </DataGridTextColumn>  
         <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" MinWidth="150" IsReadOnly="True" />  
         <DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" MinWidth="150" IsReadOnly="True" />   
       </DataGrid.Columns>  
     </DataGrid>  
Converter class:
Code:
 public class BorderBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.GlobalizationCultureInfo culture)
        {
            if (Int32.Parse(value.ToString()) >= (System.Convert.ToInt32(parameter)))
                return new SolidColorBrush(Colors.Gray);
            else
                return new SolidColorBrush(Colors.Transparent);            
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.GlobalizationCultureInfo culture)
        {
            throw new SystemNotImplementedException();
        }
    }
Datagrid window:
Cheers!

Change WPF DataGridRow background color using IValueConverter

There are several ways in painting a wpf datagrid. One option would be to use the IValueConverter interface. Firstly, you have to define a class that implements the interface. And add contracts to Convert() and ConvertBack() methods. Assuming in your form load, you bind a List object to the datagrid's ItemSource property. T could be a pre-defined class.
Here's the Resource code:
  <Window.Resources>  
     <src:AgeTargetConverter x:Key="AgeTargetConverter" />  
   </Window.Resources>    
Here's the XAML markup:
 <DataGrid Grid.Row="0" Grid.Column="0" AutoGenerateColumns="False" CanUserAddRows="False" Name="dgStudents">        
       <DataGrid.RowStyle>  
         <Style TargetType="{x:Type DataGridRow}">  
           <Style.Triggers>  
             <DataTrigger Binding="{Binding Age, Converter={StaticResource AgeTargetConverter}, ConverterParameter = 30}" Value="True">  
               <Setter Property="Background" Value="Gray"></Setter>  
             </DataTrigger>  
           </Style.Triggers>  
         </Style>          
       </DataGrid.RowStyle>  
       <DataGrid.Columns>  
         <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" Width="120" IsReadOnly="True" />  
         <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}" MinWidth="100" IsReadOnly="True" />  
         <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" MinWidth="150" IsReadOnly="True" />  
         <DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" MinWidth="150" IsReadOnly="True" />  
       </DataGrid.Columns>  
     </DataGrid>  
Here's the Converter Class:
Code:
public class AgeTargetConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.GlobalizationCultureInfo culture)
        {
            int age = System.Convert.ToInt32(value);
            int maxAge = System.Convert.ToInt32(parameter);
            return (age >= maxAge);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.GlobalizationCultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
Here's a running datagrid window: Cheers!

Tuesday, February 4, 2014

Fire TextBox control events defined in a user control from Main Form

In a scenario where in I have created a user control which has a textbox control with private keypress event. I drag and drop the user control to my main form and then I want to fire the keypress event defined in the user control. Assuming in my main form I have this code:
Code:
private void customTextBox1_KeyPress_1(object sender, KeyPressEventArgs e)  
  {  
       //accept letters,numbers, spacebar and backspace key  
       if (char.IsLetterOrDigit(e.KeyChar) || e.KeyChar == '\b' || e.KeyChar == (char)Keys.Space)  
       {  
             e.Handled = false;  
       }  
       else  
       {  
            e.Handled = true;  
       }  
     }  
Note: customTextBox1 is the user control name and customTextBox1_KeyPress_1 is the user control keypress event. In order to trigger the keypress event of the textbox defined in the user control, call Keypress user control in the textbox keypress event handler. See code below:
Code:
     private void textBox1_KeyPress(object sender, KeyPressEventArgs e)  
     {  
       base.OnKeyPress(e);  
     }  
Note: textBox1 is the textbox control and textBox1_KeyPress() as the keypress event of the control defined inside the user control.
Cheers! Reference: StackOverflow

Apply Drop Shadow effect to text using CSS (Cross Browser Compatibility Issue)

Out of boredom, I tried manipulating the drop shadow effect of text in a simple html file. The browsers tested where IE 9, Firefox 12 and Chrome version 32.However, I found some difficulties on controlling the drop shadow effect in IE 9. After doing some research, I found a solution using filter.
Here's my simple html markup:
 <!DOCTYPE html>  
 <html>  
 <head>  
      <meta charset="utf-8" />  
      <title>Chapter 2: Drop shadows on text</title>  
      <link rel="stylesheet" href="textshadowGreg.css" />  
   <!-- http://reference.sitepoint.com/css/conditionalcomments -->  
   <!--[if IE ]>  
      <link href="textshadowIE.css" rel="stylesheet" type="text/css">  
   <![endif]-->  
 </head>  
 <body>  
      <h1>What is CSS?</h1>  
      <p>  
     Cascading Style Sheets (CSS) is a style sheet language used for describing the look and formatting of a document written in a markup language. While most often used to style web pages and interfaces written in HTML and XHTML, the language can be applied to any kind of XML document, including plain XML, SVG and XUL.  
     CSS is designed primarily to enable the separation of document content from document presentation, including elements such as the layout, colors, and fonts.[1] This separation can improve content accessibility, provide more flexibility and control in the specification of presentation characteristics, enable multiple pages to share formatting, and reduce complexity and repetition in the structural content (such as by allowing for tableless web design).  
     CSS can also allow the same markup page to be presented in different styles for different rendering methods, such as on-screen, in print, by voice (when read out by a speech-based browser or screen reader) and on Braille-based, tactile devices. It can also be used to allow the web page to display differently depending on the screen size or device on which it is being viewed. While the author of a document typically links that document to a CSS file, readers can use a different style sheet, perhaps one on their own computer, to override the one the author has specified.  
      </p>  
 </body>  
 </html>  
Here's the css for Chrome and Firefox (textShadowGreg.css)
 h1 {  
  font-size: 250%;  
  color:black;  
  text-shadow: 3px 3px 3px #999;  
 }  
Here's the css for IE 9(textshadowID.css)
 h1   
 {    
   font-size: 250%;  
   color: black;  
      filter: progid:DXImageTransform.Microsoft.Chroma(Color=white)  
             progid:DXImageTransform.Microsoft.Shadow(Color=#9f9b9b, Direction=120, Strength=5);  
 }  
These are the rendered html in:
a. IE 9
b. Mozilla Firefox 12
c. Google Chrome

Reference: useragentman
Cheers!