1

I'm trying to use a switch statement based on the ID of the object (sender).

        protected void SqlDataSource_Selected(object sender, SqlDataSourceStatusEventArgs e)
        {
            int count = e.AffectedRows;
            SqlDataSource sqlds = (SqlDataSource)sender;
            switch (sqlds.ID)
            {
                case "sqldsPTY":
                    lblPTYCount.Text = "(" + count.ToString() + ")";
                    break;
                case "sqldsINC":
                    lblINCCount.Text = "(" + count.ToString() + ")";
                    break;
                ...
            }
         }

but I get the exception:

System.InvalidCastException: Unable to cast object of type 'System.Web.UI.WebControls.SqlDataSourceView' to type 'System.Web.UI.WebControls.SqlDataSource'.

what am I doing wrong?

Stuart
  • 1,544
  • 5
  • 29
  • 45

2 Answers2

0
SqlDataSource sqlds = (SqlDataSource)sender; 

is causing your issue - sender must be a SQLDataSourceView. So try

SQLDataSourceView sqlds = (SQLDataSourceView)sender 

and change the rest of code as appropriate one.

Mehmet Ince
  • 4,059
  • 12
  • 45
  • 65
NDJ
  • 5,189
  • 1
  • 18
  • 27
  • System.Web.UI.WebControls? http://msdn.microsoft.com/en-GB/library/system.web.ui.webcontrols.sqldatasource.aspx – NDJ Apr 11 '13 at 12:46
  • 1
    sorry my mistake I didnt' use InnitCap on SQLDataSourceView. I found it now... But this doesn't seem to have an ID property, so how can I tell which datasource is the sender? – Stuart Apr 11 '13 at 12:47
  • the msdn page says it does have an ID? I'm not sure otherwise to be honest – NDJ Apr 11 '13 at 12:49
0

As was stated by @NDJ sender is SQLDataSourceView. The problem is how to get SqlDataSource.

SqlDataSource is passed to SQLDataSourceView constuctor (MSDN: SqlDataSourceView Constructor). The problem is that it is stored only in private field _owner (referencesource: SqlDataSourceView). So it is necessary to use reflection to get it:

private string GetSqlDataSourceID(object sender)
{
    return (sender.GetType().GetField("_owner", BindingFlags.NonPublic | 
          BindingFlags.Instance).GetValue(sender) as SqlDataSource).ID;
}
IvanH
  • 5,039
  • 14
  • 60
  • 81