How do I get the datasourceID of the datasource that is firing the onSelecting event?
I have a couple different sqldatasources on an asp.net page that all fire the same onSelecting Event Handler. The reason for this is because the same code in the event handler can be applied to all datasources (which essentially generates filters in the queries dynamically). However, now I have another datasource that can still use most of the code, but needs to be handled slightly differenty. I could do this very easily if I could reference the datasource's ID that is firing the event (which I've tried), but this doesn't seem to be possible. Here is what I initially attempted to do:
protected void sdsTable_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
SqlDataSource sds = sender as SqlDataSource;
string dsID = sds == null ? "" : sds.ID;
if (dsID == "aDataSourceID")
{
//do this
}
else
{
//do that
}
//more code
}
This didn't work because sender is of type SqlDataSourceView and trying to cast sender as SqlDataSource returns null. So, I changed it to SqlDa开发者_运维技巧taSourceView:
protected void sdsTable_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
SqlDataSourceView sds = sender as SqlDataSourceView;
string dsID = sds == null ? "" : sds.Name; //Tried Name property because ID isn't available
if (dsID == "aDataSourceID")
{
//do this
}
else
{
//do that
}
//more code
}
But this still doesn't work. SqlDataSourceView doesn't seem to have a property available that gives the datasourceID of the datasource that is currently firing the event. There is a SqlDataSourceView.Name property, but this is something different. Does anyone know if it is possible to get the ID of the DataSource firing the Selecting event when that event is being handled? If so, can you provide an example on how to do this?
Thanks!
I'm have not tried this but SqlDataSource has GetViewNames() method and maybe you can get the ViewNames of your DataSources and check to see which one has the current SqlDataSourceView.Name
.
This is a bit hackish, but it works. Give each of the SqlDataSources a otherwise unused SelectParameter with the same name, but different default values. For example one might have:
<asp:Parameter DefaultValue="Value1" Name="sdsName" Type="String" />
And another might have:
<asp:Parameter DefaultValue="Value2" Name="sdsName" Type="String" />
Then on the selecting event you can do something like this:
switch (e.Command.Parameters["@sdsName"].Value.ToString())
{
case "Value1":
//Do something!
break;
case "Value2":
//Do something!
break;
}
Here's hoping someone has a better solution.
精彩评论