Parameter error when trying to build a selectcommand - asp.net

I'm passing a value thru a querystring, I want that value to be part of my selectcommand to build my GridView. But I'm getting the following error. Any ideas how to fix?
Error: Conversion failed when converting the nvarchar value '<%=QueryString2%>' to data type int.
C#:
protected void Page_Load(object sender, EventArgs e)
{
QueryString=Convert.ToInt32(Request.QueryString["tourid"]);
}
private int _querystring;
public int QueryString
{
get
{
return _querystring;
}
set
{
_querystring = value;
}
}
ASPX:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ChinatowndbConnString %>"
SelectCommand="SELECT * FROM [vwSchedule] Where TourId=#tid">
<SelectParameters>
<asp:Parameter DefaultValue="<%=QueryString%>" Name="tid" />
</SelectParameters>
</asp:SqlDataSource>

You can't use <%= ... %> to assign the value of a server-control property. As a result, your DefaultValue is being set to the literal string "<%=QueryString%>", which is not a valid integer.
Try using a QueryStringParameter instead:
<SelectParameters>
<asp:QueryStringParameter
Name="tid"
DbType="Int32"
QueryStringField="tourid"
/>
</SelectParameters>

Related

FilterExpression Does Not work when one of the parameters is DateTime

I'm having an issue with getting FilterExpression to work properly in a SqlDataSource. The Date Column in the SqlDatabase, NewsDate, is a DateTime. The text column, NewsSubject, in the SqlDataBase is a varchar. Here is the FilterExpression:
FilterExpression="[NewsSubject] LIKE '%{0}%' AND [NewsDate] = '{1}'"
And the control parameters are shown below:
<FilterParameters>
<asp:ControlParameter ControlID="txtNewsSubjectFilter" Name="NewsSubject" Type="String" ConvertEmptyStringToNull="False" />
<asp:ControlParameter ControlID="txtNewsDateFilter" Name="NewsDate" Type="DateTime" PropertyName="Text" />
</FilterParameters>
The Expected Results are it to filter on both columns. It is only filtering on the date.
If I Take the Date ControlParameter out and change the filter expression to only filter on NewsSubject, it works fine on the NewsSubject (see filter expression below:)
FilterExpression="[NewsSubject] LIKE '%{0}%'"
Anybody have any ideas? or is this a bug in Microsoft WebForms?
We ended up setting the FilterExpression in the OnFiltering Event in the code behind of this page. We removed the part of the expression that dealt with the date and the parameter if the date filter textbox was not populated (see FormFilteringExpressionforDate).
protected void NewsDataSource_OnFiltering(object sender, SqlDataSourceFilteringEventArgs e)
{
var newsDateClause = FormFilteringExpressionforDate(e, "NewsDate");
var firstConnector = FormConjunction(newsDateClause);
var newsSubjectClause = FormFilteringExpressionForString(e, "NewsSubject");
var filterExpression = string.Format("{0}{1}{2}", newsDateClause, firstConnector, newsSubjectClause);
var sqlDataSourceView = sender as SqlDataSourceView;
if (sqlDataSourceView == null)
return;
sqlDataSourceView.FilterExpression = filterExpression;
}
private string FormConjunction(string clause)
{
return clause == string.Empty ? "" : " AND ";
}
private string FormFilteringExpressionForString(SqlDataSourceFilteringEventArgs e, string columnName)
{
return string.Format("{0} LIKE '%{1}%' ", columnName, e.ParameterValues[columnName]);
}
private string FormFilteringExpressionforDate(SqlDataSourceFilteringEventArgs e, string columnName)
{
var columnValue = e.ParameterValues[columnName];
if (columnValue == null)
{
e.ParameterValues.Remove(columnName);
return string.Empty;
}
var convertedColumnValue = ((DateTime)columnValue).ToString("MM/dd/yyyy");
var dateClause = string.Format("{0} = '{1}'", columnName, convertedColumnValue);
return dateClause;
}
Here's the markup code (we did have to keep the FilterExpression defined in the SqlDataSource as a placeholder... the convert did not work):
<asp:SqlDataSource ID="NewsDataSource" runat="server" OnFiltering="NewsDataSource_OnFiltering"
ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [News]"
FilterExpression="CONVERT([NewsDate], 'System.String') LIKE '%{0}%' AND [NewsSubject] LIKE '%{1}%'"
OldValuesParameterFormatString="original_{0}"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" >
<FilterParameters>
<asp:ControlParameter ControlID="txtNewsDateFilter" Name="NewsDate" Type="DateTime" />
<asp:ControlParameter ControlID="txtNewsSubjectFilter" Name="NewsSubject" Type="String" ConvertEmptyStringToNull="False" />
</FilterParameters>

asp.net insertCommand resulting in NULL values

I have two listboxes whose values are sent into a TableC via a button.
<asp:SqlDataSource ID="sql1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionDataBase %>"
SelectCommand="SELECT [Name] + ' (' + [CNbr] + ')' AS FullName, [CNbr] AS CNum FROM [TableA] ORDER BY [Name]">
</asp:SqlDataSource>
<asp:ListBox ID="lst1" runat="server" DataSourceID="sql1" DataTextField="FullName" DataValueField="CNum" AutoPostBack="true">
</asp:ListBox>
<asp:SqlDataSource ID="sql2" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionDataBase %>"
InsertCommand="INSERT INTO [TableB] ([CNbr], [RDate]) VALUES (#CNbr, #RDate)"
<InsertParameters>
<asp:Parameter Name="CNbr" Type="String" />
<asp:Parameter Name="RDate" Type="DateTime" />
</InsertParameters>
<asp:ImageButton ID="ibnCheckOutBtn" runat="server"
ImageUrl="./images/vidCheckOutButton.png" onclick="ibnCheckOutBtn_Click" />
ASPX.CS file:
protected void ibnBtn_Click(object sender, ImageClickEventArgs e)
{
sql2.Insert();
}
I don't really know C# and my class doesn't cover most C#, so I am looking for a solution that doesn't use a lot of behind-code. The error I get is:
Cannot insert the value NULL into column 'CNbr', table 'TableB'; column does not allow nulls. INSERT fails. The statement has been terminated.
However, nulls should not occur because the values are taken from a fully populated listbox. Help?
You will need to assign the values to sql2 insert parameters in a similar way as follows:
protected void ibnBtn_Click(object sender, ImageClickEventArgs e)
{
sql2.InsertParameters["CNbr"].DefaultValue = this.FindControl("lst1").SelectedValue;
sql2.InsertParameters["RDate"].DefaultValue = DateTime.Now.ToString();
sql2.Insert();
}

how can i access string variable value of .aspx.cs file in .aspx file

i m getting a string value regression as regression = (Session["Regression"]).ToString(); in .aspx.cs file then i want to use this value in .aspx file in SelectCommand of SqlDataSource property as below
SelectCommand="SELECT [issue_oid], [issue_num], [regression],
[status], [tested_by], [tested_on], [patch_name], [arrived_on], [previous_info], [comment], [is_duplicate] FROM [itt_monthly_patch_issue_list] where status='Not Tested' and `regression='<%#regression%>'"`
.aspx.cs file page_load method is as below
protected void Page_Load(object sender, EventArgs e)
{
if ((Session["UserName"].ToString()) == string.Empty)
{
Server.Transfer("regressionType.aspx");
}
regression = (Session["Regression"]).ToString();
usrname = (Session["UserName"]).ToString();
DataBind();
}
please suggest me how can i do this?
thanks in advance...
You can you Session Variable's value in your SQLDatasource. Like this Example.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testDatabaseConnectionString %>"
SelectCommand="SELECT * FROM [UserTable] WHERE ([userID] = #UserID)">
<SelectParameters>
<asp:SessionParameter Name="UserID" SessionField="UserID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
let us know any other concerns on this..
add Session paramter to your sql Datasource like this
<asp:SqlDataSource SelectCommand="SELECT [issue_oid], [issue_num], [regression],
[status], [tested_by], [tested_on], [patch_name], [arrived_on], [previous_info], [comment], [is_duplicate] FROM [itt_monthly_patch_issue_list] where status='Not Tested' and `regression='<%#regression%>'"`>
<SelectParameters>
<asp:SessionParameter SessionField="Regression" Name="ParameterName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Try this:
SelectCommand="SELECT [issue_oid], [issue_num], [regression],
[status], [tested_by], [tested_on], [patch_name], [arrived_on], [previous_info], [comment], [is_duplicate] FROM [itt_monthly_patch_issue_list] where status='Not Tested' and `regression='<%=ReturnRegression()%>'"`
In codebehind:
string regression=null;//Before Page_Load
protected string ReturnRegression()
{
//Write logic here to prevent null being returned
return regression;
}
try this:
public StringBuilder regression = new StringBuilder();
regression.Append((Session["Regression"]).ToString());
Then in the .aspx page (in the selct command), you can use "regression" as:
<% =regression %>

Error in parameter that i use in update command in sqlDataSource

I use below code :
.aspx
<asp:SqlDataSource ID="SqlDataSource1" ConnectionString="<%$ConnectionStrings:Con %>" runat="server"
SelectCommand="select * from DorePayvar" OnSelecting="selecting"
UpdateCommand="update DorePayvar set Name=#name" OnUpdating="SqlDataSource1_Updating">
<UpdateParameters>
<asp:Parameter Type="String" Name="name" DefaultValue="Sajjad" />
</UpdateParameters>
</asp:SqlDataSource>
.cs
protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters["name"].Value = "bvhjbjh";
}
but when i press update button occur below error
An SqlParameter with ParameterName 'name' is not contained by this
SqlParameterCollection.
You are missing the # symbol.
The following should work :
protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters["#name"].Value = "bvhjbjh";
}
For more information on using parameters with sqldatasource check this out.
The problem could be that there is not a parameter in your parameter list with the name "name".
Try:
e.Command.Parameters.Add(new SqlParameter("name", "bvhjbjh"));

ASP.NET [Object data source]

I send id of my class object from one page to second this way :
NavigateUrl='<%# "ItemDetail.aspx?itemId=" + (string)Eval("Id") %>'
Then I get the object with ObjectDataSource and function this way :
<asp:ObjectDataSource ID="ObjectDataSourceItem" runat="server" SelectMethod="GetItem"
TypeName="Catalog">
<SelectParameters>
<asp:QueryStringParameter Name="itemId" QueryStringField="itemId" Type="string" DefaultValue="" />
</SelectParameters>
</asp:ObjectDataSource>
So how to use this item in my new page code :
this.ObjectDataSourceItem.?????
You need to subscribe to the ObjectDataSource's Selected event, access the ObjectDataSourceStatusEventArgs ReturnValue property (e.ReturnValue), and cast it to the appropriate type. Something like:
protected void ObjectDataSourceItem_Selected(object source, ObjectDataSourceStatusEventArgs e)
{
var myDataSet = (DataSet)e.ReturnValue;
}

Resources