Wednesday, September 28, 2016

Change DataGridViewRow FontStyle to Bold in CellFormatting event

Hello,
There was a question raised in the forums on how to change the FontStyle of a DataGridViewRow to Bold in the CellFormatting event. A solution is to set the Font property of a row with a Font object setting it's second parameter to FontStyle.Bold.
private void EmployeeDTRDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
 if (EmployeeDTRDataGridView.Columns[e.ColumnIndex].Name == "OnLeave")
 {
  if (e.Value != System.DBNull.Value)
  {
   if (Convert.ToBoolean(e.Value) == true)
   {
    EmployeeDTRDataGridView.Rows[e.RowIndex].DefaultCellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);
   }
  }
 }
}

Friday, September 23, 2016

Rounded Corner Button Example in WPF

In WPF, you can alter the corner radius of a button using Style class. In Setter class, set the Property value to Template. Inside the Setter class, add a ControlTemplate class that will target the Button control. After that, you can add a Border class and then setting it's CornerRadius property with an integer value of the desired radius. The example below is a user control that has a Button and a Style resource that will alter the Button's corner radius.
User Control
<UserControl x:Class="WPFButtonCornerRadiusXAMLVBForums.UCRoundedButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" d:DesignHeight="45" d:DesignWidth="100">
    <UserControl.Resources>
        <Style x:Key="ButtonRoundedCorner" TargetType="Button">
            <Setter Property="Background" Value="Silver"/>
            <Setter Property="Foreground" Value="White" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border CornerRadius="25" Background="{TemplateBinding Background}" BorderThickness="2">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center">
                            </ContentPresenter>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>
    <Grid>
        <Button Style="{StaticResource ButtonRoundedCorner}" Grid.Column="2" Grid.Row="2" Content="Hello World" 
            Width="100" Height="45" Margin="0,0,0,0" HorizontalAlignment="Center" BorderBrush="#FFF" Name="PasswordButton">
        </Button>
    </Grid>
</UserControl>
To use that user control, simply declare a xml namespace that will reference that object.
<Window x:Class="WPFButtonCornerRadius.RoundedCornerButtonDemo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ucButton="clr-namespace:WPFButtonCornerRadius"
        Title="RoundedCornerButtonDemo" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <ucButton:UCRoundedButton Grid.Column="2" Grid.Row="2"></ucButton:UCRoundedButton>
    </Grid>
</Window>
Output

Saturday, September 17, 2016

Using Bootstrap Typeahead.js Plugin in an ASP.NET MVC Project

Hello all,

Bootstrap has lots of plugins that you can experiment with, and one of them is the Typeahead.js plugin similar to jQueryUI Autocomplete plugin. According to Bootstrap, Typeahead is an extendend plugin for quickly creating elegant typeaheads with any from text input.

So given the description of the widget, I will provide a tutorial that integrates the plugin in an ASP.NET MVC project basing from this article Twitter Bootstrap Typeahead and ASP.NET MVC. The author from the source demonstrates preloaded country values but in my case, I modified it to handle searching through a database.

So to proceed with, just follow the steps below:
1. Create an ASP.NET MVC Project (C#).
2. Add an ADO.NET Entity model that connects to the AdventureWorks DB and it's CountryRegions table.
3. In your home controller, add the code that search countries based on a given value.
private static AdventureWorks2012Entities _context;

//
// GET: /Home/
public ActionResult Index()
{
 return View();
}

[HttpGet]
public JsonResult GetCountries(string query)
{
 _context = new AdventureWorks2012Entities();

 var result = (from country in _context.CountryRegions.AsEnumerable()
      where country.Name.ToLower().Contains(query)
      select country.Name);

 return Json(result.ToArray(), JsonRequestBehavior.AllowGet);
}
4. In the head section of Index View, add reference to typeaheadjs.css and bootstrap3-typeahead.js files.
<link href="~/Content/typeaheadjs.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap3-typeahead.js"></script>
5. Add the script to utilize the typeahead.js plugin for searching data.
$(document).ready(function () {

  $("#Countries").typeahead({
   source: function (query, process) {
    var countries = [];
    map = {};

    // This is going to make an HTTP get request to the controller
    return $.get('/Home/GetCountries', { query: query }, function (data) {

     // Loop through and push to the array
     $.each(data, function (i, country) {
      map[country] = country;
      countries.push(country);
     });

     // Process the details
     process(countries);
    });
   },
   updater: function (item) {
    var selectedCountry = map[item];

    // Set the text to our selected id
    $("#details").text("Selected : " + selectedCountry);
    return item;
   }
  });
 });
6. In the body section, just add a div element and an input element that will trigger the typeahead event.
<div id="details" class="row"></div>
<div class="row">
 <input type="text" id="Countries" class="form-control" placeholder="Counry Name" />
</div>
Screenshot
ASP.NET MVC VB.NET Version here.

That's it.. :-)

Thursday, September 15, 2016

Find Elements in XML from List Collection

Hello,
Given you have a List object with a number of string elements and you want to check whether the elements in the list are found in the XML file, options are your going to use the for each loop or the List.ForEach() action to traverse the List and perform searching through the XML file. XML File
<?xml version="1.0" encoding="utf-8" ?>
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
    <genre>Computer</genre>
    <price>44.95</price>
    <publish_date>2000-10-01</publish_date>
    <description>
      An in-depth look at creating applications
      with XML.
    </description>
  </book>
  <book id="bk102">
    <author>Ralls, Kim</author>
    <title>Midnight Rain</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-12-16</publish_date>
    <description>
      A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.
    </description>
  </book>
  <book id="bk103">
    <author>Corets, Eva</author>
    <title>Maeve Ascendant</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-11-17</publish_date>
    <description>
      After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.
    </description>
  </book>
  <book id="bk104">
    <author>Corets, Eva</author>
    <title>Oberon's Legacy</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2001-03-10</publish_date>
    <description>
      In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant.
    </description>
  </book>
  <book id="bk105">
    <author>Corets, Eva</author>
    <title>The Sundered Grail</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2001-09-10</publish_date>
    <description>
      The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.
    </description>
  </book>
  <book id="bk106">
    <author>Randall, Cynthia</author>
    <title>Lover Birds</title>
    <genre>Romance</genre>
    <price>4.95</price>
    <publish_date>2000-09-02</publish_date>
    <description>
      When Carla meets Paul at an ornithology
      conference, tempers fly as feathers get ruffled.
    </description>
  </book>
  <book id="bk107">
    <author>Thurman, Paula</author>
    <title>Splish Splash</title>
    <genre>Romance</genre>
    <price>4.95</price>
    <publish_date>2000-11-02</publish_date>
    <description>
      A deep sea diver finds true love twenty
      thousand leagues beneath the sea.
    </description>
  </book>
  <book id="bk108">
    <author>Knorr, Stefan</author>
    <title>Creepy Crawlies</title>
    <genre>Horror</genre>
    <price>4.95</price>
    <publish_date>2000-12-06</publish_date>
    <description>
      An anthology of horror stories about roaches,
      centipedes, scorpions  and other insects.
    </description>
  </book>
  <book id="bk109">
    <author>Kress, Peter</author>
    <title>Paradox Lost</title>
    <genre>Science Fiction</genre>
    <price>6.95</price>
    <publish_date>2000-11-02</publish_date>
    <description>
      After an inadvertant trip through a Heisenberg
      Uncertainty Device, James Salway discovers the problems
      of being quantum.
    </description>
  </book>
  <book id="bk110">
    <author>O'Brien, Tim</author>
    <title>Microsoft .NET: The Programming Bible</title>
    <genre>Computer</genre>
    <price>36.95</price>
    <publish_date>2000-12-09</publish_date>
    <description>
      Microsoft's .NET initiative is explored in
      detail in this deep programmer's reference.
    </description>
  </book>
  <book id="bk111">
    <author>O'Brien, Tim</author>
    <title>MSXML3: A Comprehensive Guide</title>
    <genre>Computer</genre>
    <price>36.95</price>
    <publish_date>2000-12-01</publish_date>
    <description>
      The Microsoft MSXML3 parser is covered in
      detail, with attention to XML DOM interfaces, XSLT processing,
      SAX and more.
    </description>
  </book>
  <book id="bk112">
    <author>Galos, Mike</author>
    <title>Visual Studio 7: A Comprehensive Guide</title>
    <genre>Computer</genre>
    <price>49.95</price>
    <publish_date>2001-04-16</publish_date>
    <description>
      Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.
    </description>
  </book>
</catalog>

C# Code
XDocument doc = XDocument.Load("Books.xml");
List<string> accountNumbers = new List<string>();
accountNumbers.Add("bk108");
accountNumbers.Add("bk110");
accountNumbers.Add("bk112");

accountNumbers.ForEach(number =>
{
 var node = doc.Descendants("book").SingleOrDefault(x => x.Attribute("id").Value == number.ToString());
 if (node != null)
 {
  var author = node.Element("author").Value.ToString();
  if(author != null)
  {
   Console.WriteLine("Book number {0} with author {1} ", number, author);
  }                   
 }               
});

Sunday, September 11, 2016

Read or parse XML using XDocument (LINQ)

Given the XML file below which is a sample popularized my Microsoft, here's how to traverse with that XML file using LINQ to XML XDocument class.
XML File
<?xml version="1.0" encoding="utf-8" ?>
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
    <genre>Computer</genre>
    <price>44.95</price>
    <publish_date>2000-10-01</publish_date>
    <description>
      An in-depth look at creating applications
      with XML.
    </description>
  </book>
  <book id="bk102">
    <author>Ralls, Kim</author>
    <title>Midnight Rain</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-12-16</publish_date>
    <description>
      A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.
    </description>
  </book>
  <book id="bk103">
    <author>Corets, Eva</author>
    <title>Maeve Ascendant</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-11-17</publish_date>
    <description>
      After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.
    </description>
  </book>
  <book id="bk104">
    <author>Corets, Eva</author>
    <title>Oberon's Legacy</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2001-03-10</publish_date>
    <description>
      In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant.
    </description>
  </book>
  <book id="bk105">
    <author>Corets, Eva</author>
    <title>The Sundered Grail</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2001-09-10</publish_date>
    <description>
      The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.
    </description>
  </book>
  <book id="bk106">
    <author>Randall, Cynthia</author>
    <title>Lover Birds</title>
    <genre>Romance</genre>
    <price>4.95</price>
    <publish_date>2000-09-02</publish_date>
    <description>
      When Carla meets Paul at an ornithology
      conference, tempers fly as feathers get ruffled.
    </description>
  </book>
  <book id="bk107">
    <author>Thurman, Paula</author>
    <title>Splish Splash</title>
    <genre>Romance</genre>
    <price>4.95</price>
    <publish_date>2000-11-02</publish_date>
    <description>
      A deep sea diver finds true love twenty
      thousand leagues beneath the sea.
    </description>
  </book>
  <book id="bk108">
    <author>Knorr, Stefan</author>
    <title>Creepy Crawlies</title>
    <genre>Horror</genre>
    <price>4.95</price>
    <publish_date>2000-12-06</publish_date>
    <description>
      An anthology of horror stories about roaches,
      centipedes, scorpions  and other insects.
    </description>
  </book>
  <book id="bk109">
    <author>Kress, Peter</author>
    <title>Paradox Lost</title>
    <genre>Science Fiction</genre>
    <price>6.95</price>
    <publish_date>2000-11-02</publish_date>
    <description>
      After an inadvertant trip through a Heisenberg
      Uncertainty Device, James Salway discovers the problems
      of being quantum.
    </description>
  </book>
  <book id="bk110">
    <author>O'Brien, Tim</author>
    <title>Microsoft .NET: The Programming Bible</title>
    <genre>Computer</genre>
    <price>36.95</price>
    <publish_date>2000-12-09</publish_date>
    <description>
      Microsoft's .NET initiative is explored in
      detail in this deep programmer's reference.
    </description>
  </book>
  <book id="bk111">
    <author>O'Brien, Tim</author>
    <title>MSXML3: A Comprehensive Guide</title>
    <genre>Computer</genre>
    <price>36.95</price>
    <publish_date>2000-12-01</publish_date>
    <description>
      The Microsoft MSXML3 parser is covered in
      detail, with attention to XML DOM interfaces, XSLT processing,
      SAX and more.
    </description>
  </book>
  <book id="bk112">
    <author>Galos, Mike</author>
    <title>Visual Studio 7: A Comprehensive Guide</title>
    <genre>Computer</genre>
    <price>49.95</price>
    <publish_date>2001-04-16</publish_date>
    <description>
      Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.
    </description>
  </book>
</catalog>

C# Code
XDocument document = XDocument.Load("Books.xml");

var bookElements = document.Descendants("book");

foreach (XElement bookItem in bookElements)
{
 Console.WriteLine("Book ID: {0}", bookItem.Attribute("id").Value);
 Console.WriteLine("Author: {0}", bookItem.Descendants("author").FirstOrDefault().Value);
 Console.WriteLine("Title: {0}", bookItem.Descendants("title").FirstOrDefault().Value);
 Console.WriteLine("Genre: {0}", bookItem.Descendants("genre").FirstOrDefault().Value);
 Console.WriteLine("Price: {0}", bookItem.Descendants("price").FirstOrDefault().Value);
 Console.WriteLine("Publish date: {0}", bookItem.Descendants("publish_date").FirstOrDefault().Value);
 Console.WriteLine("Description: {0}", bookItem.Descendants("description").FirstOrDefault().Value);
 Console.WriteLine("======================================");
}

Thursday, September 8, 2016

Using AJAX Control Toolkit AutoCompleteExtender in ASP.NET 4.5

Hello all,
I have posted in VBForums codebank on how to integrate Ajax Toolkit's AutoCompleteExtender control in your ASP.NET 4.5 Web Forms project. The thread is in VB.NET but if your using C# just replace the code behind as described in Step 4 with the snippet below.
Code Behind
private static AdventureWorks2012Entities _context;

[ScriptMethod()]
[WebMethod]
public static List<string> GetCountries(string prefixText, int count)
{
 _context = new AdventureWorks2012Entities();

 var result = (from country in _context.CountryRegions.AsEnumerable()
      where country.Name.ToLower().StartsWith(prefixText, StringComparison.OrdinalIgnoreCase)
      select country.Name).Take(count);

 return result.ToList();
}

[ScriptMethod()]
[WebMethod]
public static object GetCountryInfo(string Country)
{
 _context = new AdventureWorks2012Entities();

 var result = (from country in _context.CountryRegions.AsEnumerable()
      where country.Name.ToLower().Equals(Country.ToLower())
      select new 
      { 
       country.Name, 
       country.CountryRegionCode
      }).FirstOrDefault();

 return result;
}

Screenshot

Tuesday, September 6, 2016

Read or parse XML using XPathDocument

Good day!

In this example, I will show you how to read an XML file using XPathNavigator and XPathDocument classes in .NET. When using these classes, make sure to include the System.Xml and System.Xml.XPath namespaces in your file.
XML File
<?xml version="1.0" encoding="utf-8" ?>
<Invoice  xmlns:inv="http://salesorgchart.abcdefg.com">
  <inv:Customers>
    <inv:TotalSales>134.49</inv:TotalSales>
    -<inv:Customer>
      <inv:Date>2013-11-15</inv:Date>
      <inv:Number>10001</inv:Number>
      <inv:CustomerName>Cherry Pie</inv:CustomerName>
      <inv:PONumber>30002</inv:PONumber>
      <inv:Address>Cebu City Philippines</inv:Address>
      -<inv:Products>
        -<inv:Product>
          <inv:Code>AE445</inv:Code>
          <inv:Category>Liquid Milk</inv:Category>
          <inv:Name>Devondale</inv:Name>
          <inv:Quantity>$100.49</inv:Quantity>
        </inv:Product>
        <inv:Product>
          <inv:Code>AE443</inv:Code>
          <inv:Category>Junk Foods</inv:Category>
          <inv:Name>Pringles</inv:Name>
          <inv:Quantity>$34.00</inv:Quantity>
        </inv:Product>
      </inv:Products>
    </inv:Customer>
  </inv:Customers>
</Invoice>

C# Code
private void ReadXML()
{
 XPathDocument xPath;
 XPathNavigator nav;
 XmlNamespaceManager manager;

 using (StreamReader reader = new StreamReader(xmlPath, UTF8Encoding.Default))
 {
  xPath = new XPathDocument(reader);            
 }

 nav = default(XPathNavigator);
 nav = xPath.CreateNavigator();
 manager = new XmlNamespaceManager(nav.NameTable);
 manager.AddNamespace("inv", "http://salesorgchart.abcdefg.com");
 XPathNodeIterator nodes = nav.Select("//inv:Customers/inv:Customer", manager);

 if (nodes.MoveNext())
 {
  foreach (XPathNavigator child in nodes.Current.SelectChildren(XPathNodeType.All))
  {
   if (child.Name == "inv:Number" || child.Name == "inv:CustomerName")
   {
    Console.WriteLine("{0}: {1}", child.Name, child.Value);
   }
   else
   {
    if (child.HasChildren && child.Name == "inv:Products")
    {
     Console.WriteLine("==============================================");
    
     Console.WriteLine("Products" + "\n");
     foreach (XPathNavigator item in child.SelectChildren(XPathNodeType.All))
     {
      if (item.HasChildren)
      {                                    
       foreach (XPathNavigator product in item.SelectChildren(XPathNodeType.All))
       {
        if (!product.Name.Equals(string.Empty))
        {
         Console.WriteLine("{0}: {1}", product.Name, product.Value);
        }
       }

       Console.Write(Environment.NewLine);
      }                                
     }                                
    }                                                    
   }
  }
 }
}

Show SQL query result as XML using Sql Server FOR XML()

Hello,
Given that you are required to show the results of a query into an XML format, T-SQL has a function called For XML to achieve that output as shown below.
Screenshot
I have created two scripts to achieve the desired result as above. The first script will alias a column name with @AttributeName that signifies an attribute which will then be added to Assigned node using FOR XML Path() function.
Use NorthwindCrudApp
Go
SELECT TOP 3
         ProductID as "@ProductID", 
  ProductName as "@ProductName",
  UnitsInStock as "@UnitsInStock",
  UPPER(ProductName) as [text()] 
FROM Products As Products
 ORDER BY ProductID
FOR XML PATH('Assigned'), Root('DATA');
The second script also creates column alias for each column using the syntax NodeName/@Attribute similar to an XPath expression.
SELECT TOP 3
     ProductID as "Assigned/@ProductID",  
  ProductName as "Assigned/@ProductName",
  UnitsInStock as "Assigned/@UnitsInStock",
  Upper([ProductName]) as "Assigned" 
FROM Products As Products
 ORDER BY ProductID
FOR XML PATH(''),TYPE,ELEMENTS,ROOT('DATA');

Sunday, September 4, 2016

Set DataGridTemplateColumn Control to ReadOnly in WPF

Hi all,
There was a question raised on how to set a control (ex. TextBox) inside the DataGridTemplateColumn of a WPF DataGrid to ReadOnly. The solution to that is to get the DataGridRow followed by accessing the DataGridCell and then get the VisualChild control inside the DataGridCell. By then, you can set the control's property IsReadOnly to true.
XAML Code
<DataGrid x:Name="dgPerson" Grid.Column="2" Grid.Row="2" CanUserDeleteRows="False" 
     AutoGenerateColumns="False" CanUserAddRows="False">
 <DataGrid.Columns>
  <DataGridTemplateColumn Header="ID" Width="150">
   <DataGridTemplateColumn.CellTemplate>
    <DataTemplate >
     <TextBox Name="txtID" Text="{Binding ID, Mode=OneWay}" />
    </DataTemplate>
   </DataGridTemplateColumn.CellTemplate>
  </DataGridTemplateColumn>
  <DataGridTemplateColumn Header="Name" Width="250">
   <DataGridTemplateColumn.CellTemplate>
    <DataTemplate >
     <TextBox Name="txtName" Text="{Binding Name, Mode=OneWay}" />
    </DataTemplate>
   </DataGridTemplateColumn.CellTemplate>
  </DataGridTemplateColumn>
  <DataGridTemplateColumn Header="Department Code" Width="150">
   <DataGridTemplateColumn.CellTemplate>
    <DataTemplate >
     <TextBox Name="txtDept" Text="{Binding Department, Mode=OneWay}" />
    </DataTemplate>
   </DataGridTemplateColumn.CellTemplate>
  </DataGridTemplateColumn>
 </DataGrid.Columns>
</DataGrid>

VB.NET Code
Private Sub Window_Loaded_1(sender As Object, e As RoutedEventArgs)
        
 'set read only DataGridTemplateColumn (3rd column)
 SetReadOnlyDataTemplateColumn(2)
End Sub
 
Private Sub SetReadOnlyDataTemplateColumn(ByVal columnIndex As Integer)
 For index = 0 To dgPerson.Items.Count - 1 Step 1
  Dim txtSequence As TextBox
  Dim row As DataGridRow = dgPerson.GetRow(index)
  Dim sequenceColumn As DataGridCell = TryCast(dgPerson.Columns(columnIndex).GetCellContent(row).Parent, DataGridCell)
  txtSequence = DataGridExtensions.GetVisualChild(Of TextBox)(sequenceColumn)

  If txtSequence IsNot Nothing Then
   txtSequence.IsReadOnly = True
  End If
 Next
End Sub

Extension Methods WPF DataGrid Row and Cells Extension Methods.
Screenshot

Thursday, September 1, 2016

Invalid postback or callback argument in ASP.NET (_doPostBack in jQuery UI Confirmation Dialog)

Hello, I'm currently working with ASP.NET GridView control that shows a confirmation dialog using jQuery UI instead of the classic JavaScript confirm dialog that prompts a user to delete a certain record. However, integrating that with the GridView control was slightly tricky in the sense that I was stuck with Invalid postback or callback argument error. Since this is ASP.NET Webforms, you have to deal with Postback hell issues. :)
jQuery UI Dialog that trigger's postback
buttons: {
 "Yes": function () {
  __doPostBack(btnUniqueID, '');
  $(this).dialog("close");
 },
 "No": function () {
  $(this).dialog("close");
  return false;
 }
}

After doing some research, I came up with two solutions. The first one is to set EnableEventValidation of Page directive to false for page level effect. Or you can set it in web.config for project scope.
Page Directive Solution
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GridViewjQueryUI.Default" EnableEventValidation="false" %>
However, the solution on setting EventValidation will also affect other settings and code in your webform page. The second solution, will isolate the problem by registering the UniqueID of a control that will trigger the PostBack through ClientScript.RegisterForEventValidation() method. This is the preferred one.
PagePage.ClientScript.RegisterForEventValidation Solution
protected override void Render(HtmlTextWriter writer)
{
 foreach (GridViewRow r in gvCustomers.Rows)
 {
  if (r.RowType == DataControlRowType.DataRow)
  {
   LinkButton lbtnSelect = (LinkButton)r.FindControl("lbtnDelete");
   Page.ClientScript.RegisterForEventValidation(lbtnSelect.UniqueID, "Select$" + r.RowIndex);
  }
 }            

 base.Render(writer);
}

Cheers! :)