<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>dotnet thoughts &#187; Databinding</title>
	<atom:link href="http://www.dotnetthoughts.net/tag/databinding/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dotnetthoughts.net</link>
	<description>a dotnet developer&#039;s technical blog</description>
	<lastBuildDate>Thu, 02 Feb 2012 03:18:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Sortable Binding List for custom data objects</title>
		<link>http://www.dotnetthoughts.net/2011/11/04/sortable-binding-list-for-custom-data-objects/</link>
		<comments>http://www.dotnetthoughts.net/2011/11/04/sortable-binding-list-for-custom-data-objects/#comments</comments>
		<pubDate>Fri, 04 Nov 2011 19:18:20 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[.Net 4.0]]></category>
		<category><![CDATA[BindingList]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Databinding]]></category>
		<category><![CDATA[Generic list]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=1958</guid>
		<description><![CDATA[Binding generic collections to Windows forms Data gridview can be done using DataSource property of Gridview control. But the problem with normal generic lists that it doesn&#8217;t support sorting, by clicking the grid view headers. .Net Framework provides an generic &#8230; <a href="http://www.dotnetthoughts.net/2011/11/04/sortable-binding-list-for-custom-data-objects/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Binding generic collections to Windows forms Data gridview can be done using DataSource property of Gridview control. But the problem with normal generic lists that it doesn&#8217;t support sorting, by clicking the grid view headers. .Net Framework provides an generic abstract class, <a href="http://msdn.microsoft.com/en-us/library/ms132679.aspx" target="_blank">BindingList&lt;T&gt;</a>, which supports virtual methods for Searching and Sorting <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  And here is an implementation, which will helps to sort a gridview control.</p>
<pre class="brush: plain; title: ; notranslate">
public class SortableList : BindingList
{
    protected override bool SupportsSortingCore
    {
        get
        {
            return true;
        }
    }

    protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
    {
        var sortProperty = prop;
        var sortDirection = direction;

        var list = Items as List;
        list.Sort((T item1, T item2) =&gt;
        {
            var item1Value = item1 == null ? null : sortProperty.GetValue(item1);
            var item2Value = item2 == null ? null : sortProperty.GetValue(item2);
            int result;
            if (item1Value == null)
            {
                result = -1;
            }
            else if (item2Value == null)
            {
                result = 1;
            }
            else
            {
                result = Comparer.Default.Compare(item1Value, item2Value);
            }
            if (sortDirection == ListSortDirection.Descending)
            {
                result = -result;
            }
            return result;
        });
    }
}
</pre>
<p>This post I wrote long back and it was in draft mode, and today I thought of publishing it <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Happy Coding <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<div class="betterrelated"><p><strong>Related content:</strong></p>
<ol><li> <a href="http://www.dotnetthoughts.net/2010/12/26/how-to-return-null-from-a-generic-method/" title="Permanent link to How to return null from a generic method">How to return null from a generic method</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2010/08/09/creating-wizard-using-windows-forms/" title="Permanent link to Creating Wizard using Windows Forms">Creating Wizard using Windows Forms</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2011/07/03/image-cropping-control-in-c-for-windows-forms/" title="Permanent link to Image cropping control in C# for Windows Forms">Image cropping control in C# for Windows Forms</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2011/07/02/fluent-email-library-for-c-using-dynamicobject/" title="Permanent link to Fluent email library for c# using DynamicObject">Fluent email library for c# using DynamicObject</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2011/03/03/update-multiple-elements-at-once-using-linq/" title="Permanent link to Update multiple elements at once using LINQ">Update multiple elements at once using LINQ</a>  </li>
</ol></div>]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2011/11/04/sortable-binding-list-for-custom-data-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing Custom Paging in DataRepeater using C# and SQL Server</title>
		<link>http://www.dotnetthoughts.net/2009/10/22/implementing-custom-paging-in-datarepeater-using-c-and-sql-server/</link>
		<comments>http://www.dotnetthoughts.net/2009/10/22/implementing-custom-paging-in-datarepeater-using-c-and-sql-server/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 14:40:23 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Databinding]]></category>
		<category><![CDATA[Repeater]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=558</guid>
		<description><![CDATA[Normally DataRepeater doesn&#8217;t have a paging feature; and you can implement it using LINQ, if you are using .Net 3.5. Here is an implementation which is using SQL Server 2005 feature ROW_NUMBER(). You can get more information about ROW_NUMBER() from &#8230; <a href="http://www.dotnetthoughts.net/2009/10/22/implementing-custom-paging-in-datarepeater-using-c-and-sql-server/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Normally DataRepeater doesn&#8217;t have a paging feature; and you can implement it using LINQ, if you are using .Net 3.5. Here is an implementation which is using SQL Server 2005 feature ROW_NUMBER(). You can get more information about ROW_NUMBER() from <a href="http://msdn.microsoft.com/en-us/library/ms186734.aspx" target="_blank">MSDN</a>.</p>
<p>Stored Procedure &#8211; xsp_GetPersons</p>
<pre class="brush: sql; title: ; notranslate">
CREATE PROCEDURE xsp_GetPersons
@StartIndex INT, @Count INT
AS
BEGIN
DECLARE @EndIndex INT
SET @StartIndex = @StartIndex * @Count
SET @EndIndex = @StartIndex + @Count
SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY UserId DESC) AS SlNo, UserId, FirstName, LastName, Email, ISNULL(DOB, GETDATE()) AS DOB FROM U_MyRegistration)Registration WHERE Registration.SlNo BETWEEN @StartIndex AND @EndIndex
END
</pre>
<p>And I added a DataRepeater control, with Next and Previous buttons in the Footer.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;tr&gt;
    &lt;td colspan=&quot;3&quot; align=&quot;left&quot;&gt;
        &lt;asp:LinkButton CommandName=&quot;Navigation&quot; CommandArgument=&quot;Prev&quot; runat=&quot;server&quot; ID=&quot;linkPrevious&quot;
            Text=&quot;&lt;&lt; Previous&quot; /&gt;
    &lt;/td&gt;
    &lt;td colspan=&quot;3&quot; align=&quot;right&quot;&gt;
        &lt;asp:LinkButton CommandName=&quot;Navigation&quot; CommandArgument=&quot;Next&quot; runat=&quot;server&quot; ID=&quot;linkNext&quot; Text=&quot;Next &gt;&gt;&quot; /&gt;
    &lt;/td&gt;
&lt;/tr&gt;
</pre>
<p>Code behind. As it is a sample code, I am not added any validations.</p>
<pre class="brush: csharp; title: ; notranslate">
int count = 10;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        BindData(); //Binding Data.
    }
}

private void BindData()
{
    int startIndex = Convert.ToInt32(this.hidCurrentIndex.Value);
    Persons p = new Persons();
    this.Repeater1.DataSource = null;
    this.Repeater1.DataSource = p.GetPersons(startIndex, count);
    this.Repeater1.DataBind();
}

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName.Equals(&quot;Navigation&quot;,
StringComparison.CurrentCultureIgnoreCase))
    {
        if (e.CommandArgument.ToString().Equals(&quot;Prev&quot;,
StringComparison.CurrentCultureIgnoreCase))
        {
            this.hidCurrentIndex.Value = (Convert.ToInt32
(this.hidCurrentIndex.Value) - 1).ToString(); //Decrementing the count
            this.BindData();
        }
        else
        {
            this.hidCurrentIndex.Value = (Convert.ToInt32
(this.hidCurrentIndex.Value) + 1).ToString(); //Incrementing the count
            this.BindData();
        }
    }
}
</pre>
<p>And the implementation of Persons class from App_Code</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Collections.Generic;
using System.Data.SqlClient;

public class Persons : List&lt;Persons.Person&gt;
{
    public class Person
    {
        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public DateTime DOB { get; set; }
    }

    public Persons GetPersons(int startIndex, int count)
    {
        Persons persons = new Persons();
        using (SqlConnection connection = new SqlConnection (&quot;Server=.\SQLEXPRESS;User Id=sa;Password=sapwd;Database=myDatabase&quot;))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand(&quot;xsp_GetPersons&quot;,

connection))
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.Parameters.AddWithValue(&quot;@StartIndex&quot;, startIndex);
                command.Parameters.AddWithValue(&quot;@Count&quot;, count);
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    persons.Add(new Person()
                    {
                        DOB = Convert.ToDateTime(reader[&quot;DOB&quot;].ToString()),
                        Email = reader[&quot;Email&quot;].ToString(),
                        FirstName = reader[&quot;FirstName&quot;].ToString(),
                        LastName = reader[&quot;LastName&quot;].ToString(),
                        UserId = Convert.ToInt32(reader[&quot;UserId&quot;].ToString()),
                    });
                }
            }
        }
        return persons;
    }
}
</pre>
<p>The core thing is stored procedure, which will return the results based on the given index. Thanks to <strong>Aneesh</strong> for the details of ROW_NUMBER() function.</p>
<div class="betterrelated"><p><strong>Related content:</strong></p>
<ol><li> <a href="http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/" title="Permanent link to How to Store and Retrieve files from SQL Server Database">How to Store and Retrieve files from SQL Server Database</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/10/20/treeview-population-without-recursive-function/" title="Permanent link to TreeView Population without recursive function">TreeView Population without recursive function</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/09/22/adding-and-reading-files-from-sql-server-2008-filestream/" title="Permanent link to Adding and Reading files from SQL Server 2008 Filestream">Adding and Reading files from SQL Server 2008 Filestream</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/09/23/import-export-data-in-ms-excel-using-c/" title="Permanent link to Import / export data in MS Excel using C#">Import / export data in MS Excel using C#</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2011/07/02/fluent-email-library-for-c-using-dynamicobject/" title="Permanent link to Fluent email library for c# using DynamicObject">Fluent email library for c# using DynamicObject</a>  </li>
</ol></div>]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/10/22/implementing-custom-paging-in-datarepeater-using-c-and-sql-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Databinding in ASP.Net dropdownlist</title>
		<link>http://www.dotnetthoughts.net/2007/05/14/databinding-in-aspnet-dropdownlist/</link>
		<comments>http://www.dotnetthoughts.net/2007/05/14/databinding-in-aspnet-dropdownlist/#comments</comments>
		<pubDate>Mon, 14 May 2007 07:55:48 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[Databinding]]></category>
		<category><![CDATA[Hash Table]]></category>
		<category><![CDATA[VB.Net]]></category>

		<guid isPermaLink="false">http://anuraj.wordpress.com/2007/05/14/databinding-in-aspnet-dropdownlist/</guid>
		<description><![CDATA[In many forums, I used to see people asking for code to bind the dropdown list from basic collections. Here is the code to bind a Hash Table to ASP:Dropdown list, and setting the value of the selected item to &#8230; <a href="http://www.dotnetthoughts.net/2007/05/14/databinding-in-aspnet-dropdownlist/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In many forums, I used to see people asking  for code to bind the dropdown list from basic collections. Here is the code to bind a Hash Table to ASP:Dropdown list, and setting the value of the selected item to the Text box. This is in ASP.Net 1.1.</p>
<pre class="brush: vb; title: ; notranslate">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  If Not Page.IsPostBack Then
  Dim students As New Hashtable
  students.Add(&quot;1&quot;, &quot;Student1&quot;)
  students.Add(&quot;2&quot;, &quot;Student2&quot;)
  students.Add(&quot;3&quot;, &quot;Student3&quot;)
  students.Add(&quot;4&quot;, &quot;Student4&quot;)
  students.Add(&quot;5&quot;, &quot;Student5&quot;)
  StudentDropdown.DataTextField = &quot;Value&quot;
  StudentDropdown.DataValueField = &quot;key&quot;
  StudentDropdown.DataSource = students
  StudentDropdown.DataBind()
  End If
End Sub
</pre>
<p>And set the <em>Autopostback</em> property of the StudentDropdown to True. And in the SelectedIndexChanged event, write the code to set the value of the Dropdown to the Textbox.</p>
<pre class="brush: vb; title: ; notranslate">
Protected Sub StudentDropdown_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles StudentDropdown.SelectedIndexChanged
        If uxSample.SelectedIndex  &lt;&gt; -1 Then
            StudentId.Text = StudentDropdown.Items(StudentDropdown.SelectedIndex).Value
        End If
End Sub
</pre>
<div class="betterrelated"><p><strong>Related content:</strong></p>
<ol><li> <a href="http://www.dotnetthoughts.net/2009/10/22/implementing-custom-paging-in-datarepeater-using-c-and-sql-server/" title="Permanent link to Implementing Custom Paging in DataRepeater using C# and SQL Server">Implementing Custom Paging in DataRepeater using C# and SQL Server</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2010/07/15/dropdownlist-findbytext-problem/" title="Permanent link to Dropdownlist FindByText Problem">Dropdownlist FindByText Problem</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2010/06/21/asp-net-default-button-and-master-pages/" title="Permanent link to ASP.Net Default button and Master Pages">ASP.Net Default button and Master Pages</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/" title="Permanent link to How to Store and Retrieve files from SQL Server Database">How to Store and Retrieve files from SQL Server Database</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2011/11/15/how-to-persist-checkbox-state-in-gridview-while-paging/" title="Permanent link to How to persist checkbox state in gridview while paging">How to persist checkbox state in gridview while paging</a>  </li>
</ol></div>]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2007/05/14/databinding-in-aspnet-dropdownlist/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

