user1800674
user1800674

Reputation: 233

How to cast DataView to DataSource

is there any way to convert DataView to DataSource?

I'm trying to sort my gridview columns on click. Here is the code:

internal static string sort(object _sender, GridViewSortEventArgs _e, string _viewStateSortExpression, string _viewStateSortDirection)
        {
            string expression = _e.SortExpression;
            string direction = getSortDirection(expression, _viewStateSortExpression, _viewStateSortDirection); //ascending by default

            GridView gvSrc = (GridView)_sender;

            DataView dv = new DataView();
            gvSrc.DataSource = dv;
            gvSrc.DataBind();



            dv = (DataView)((SqlDataSource)gvSrc.DataSource).Select(DataSourceSelectArguments.Empty);


            dv.Sort = expression + " " + direction;
            return direction;
        }

I get this error when I click the column to do the sorting:

Unable to cast object of type 'System.Data.DataView' to type 'System.Web.UI.WebControls.SqlDataSource'.

Upvotes: 0

Views: 7084

Answers (2)

Kapil
Kapil

Reputation: 1931

Try this,

 DataTable m_DataTable = gvSrc.DataSource as DataTable;

   if (m_DataTable != null)
   {
      DataView m_DataView = new DataView(m_DataTable);
      m_DataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

      gvSrc.DataSource = m_DataView;
      gvSrc.DataBind();
   }

Upvotes: 0

Dev
Dev

Reputation: 1130

Convert DataView to DataTable:

there is a method named ToTable to convert DataView to DataTable

DataTable dt=dv.ToTable();// this method may expects parameters

Convert DataTable to DataView:

DefaultView is a property that returns DataView of a DataTable

DataView dv=dt.DefaultView

Upvotes: 4

Related Questions