Pregunta

I have an SqlDatasource for which I programmatically create the SelectCommand. In general, the SqlDataSource works fine, but when I give it FilterParameters and a FilterExpression, things go awry. Below are two examples, the first returning 0 records, the second returning all the records (15,000). Neither example returns the subset of records that I'm looking for (2,839). I'm completely befuddled as to how I'm supposed to set up the FilterParameters and FilterExpression to get the records I'm looking for. I've been researching this for two days now with no luck.

<asp:SqlDataSource ID="dsIAMS" runat="server" ConnectionString="<%$ ConnectionStrings:ReportsConnectionString %>" />

dl = (DropDownList)tFilters.Controls[0];
// dl.ID = dlPASUBTYPENAME 
cp = new ControlParameter();
cp.Name = "cp" + dl.ID.Substring(2);
cp.ControlID = dl.ID;
cp.PropertyName = "SelectedValue";

//Attempt 1:  Returns 0 records
cp.ConvertEmptyStringToNull = false;
dsIAMS.FilterParameters.Add(cp);
if (dl.SelectedItem.Text == "") {
  dsIAMS.FilterExpression = dl.ID.Substring(2) + "='' ";
}
else {
  dsIAMS.FilterExpression = dl.ID.Substring(2) + "='{0}'";
}

//Attempt #2:  Returns all the records (15,000)
cp.ConvertEmptyStringToNull = true;
dsIAMS.FilterParameters.Add(cp);
if (dl.SelectedItem.Text == "") {
  dsIAMS.FilterExpression = "ISNULL("+dl.ID.Substring(2) + ", 'null')='null' ";
}
else {
  dsIAMS.FilterExpression = dl.ID.Substring(2) + "='{0}'";
}

Here is the SQL query that I run against the database itself:

SELECT * FROM IAMS
WHERE PASUBTYPENAME IS NULL

Returns 2,839 rows.

¿Fue útil?

Solución

I gave up. In addition toFilterExpression and FilterParameters, I tried SelectParameters with the same results. I decided to just hard code the whole SelectCommand every time. Parameters just don't work. I've always hated them because they simply to not handle NULLs well. During my diagnosis, I even ran SQL Server Profiler to trace communication from Visual Studio and when the parameter wasn't used (i.e. the "ISNULL" part was used), the query was never even submitted to the SQL server. I ended up using the following code instead:

<asp:SqlDataSource ID="dsIAMS" runat="server" ConnectionString="<%$ ConnectionStrings:ReportsConnectionString %>" />

dl = (DropDownList)tFilters.Controls[0];
// dl.ID = dlPASUBTYPENAME 
if (dl.SelectedItem.Text == "") {
  dsIAMS.SelectCommand+=dl.ID.Substring(2) + " IS NULL";
}
else {
  dsIAMS.SelectCommand+=dl.ID.Substring(2) + "='" + dl.SelectedItem.Text + "'";
}

Otros consejos

You don't appear to be doing a databind() following any FilterExpression setting for these Datasets or DropDownLists. You need to do this to invoke a requery.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top