I have added a "Select All" value in ddlCategory to select all categories when it is selected but I got this error message "Cannot perform '=' operation on System.Int32 and System.String." Any ideas? Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
if (ddlCategory.SelectedItem.Text == "Select All")
{
ProductDataSource.SelectCommand = "SELECT [ProductId], [ProductName], [ImageUrl], [Price], [CategoryId] FROM [Product] WHERE [SystemId] = 1";
}
}
Here is the code to ProductDataSource:
<asp:SqlDataSource
ID="ProductDataSource"
EnableCaching="true"
DataSourceMode="DataSet"
runat="server"
ConnectionString="<%$ ConnectionStrings:ProjectConnectionString1 %>"
SelectCommand="SELECT [ProductId], [ProductName], [ImageUrl], [Price], [CategoryId] FROM [Product] WHERE [SystemId] = 1"
FilterExpression="CategoryId = '{0}'">
<FilterParameters>
<asp:ControlParameter Name="categoryparm" ControlID="ddlCategory" PropertyName="SelectedValue" />
</FilterParameters>
</asp:SqlDataSource>
You added element Select All, but what is the value of your element? I think it is better to you to use SelectedValue. Add to your DropDownList element Select All with value 0, and then your method will looks like
if (ddlCategory.SelectedValue == 0){ /* your query here */}
Also I recommend you to perform this actions on first load of the page, not on postbacks. So your Page_Load method will looks like
if (!IsPostBack){
if (ddlCategory.SelectedValue == 0)
ProductDataSource.SelectCommand = "select * from product where systemid = 1";
}
Related
Problem
I am trying to use a text box txtSearch to filter results from a SqlDataSource.
My query:
SELECT
[id], [username], [name]
FROM
[dbo].[users]
WHERE
#filter IS NULL OR
LEN(#filter) = 0 OR
[name] LIKE ('%'+#filter+'%')
ASPX markup:
<div>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" CausesValidation="False" OnClick="btnSearch_Click" />
</div>
<asp:SqlDataSource ID="SQLDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>"
SelectCommand="SELECT [id], [username], [name] FROM [dbo].[users] WHERE #filter IS NULL OR LEN(#filter) = 0 OR [name] LIKE ('%'+#filter+'%')">
<SelectParameters>
<asp:ControlParameter ControlID="txtSearch" DefaultValue=""
Name="filter" Type="String" PropertyName="Text" />
</SelectParameters>
</asp:SqlDataSource>
C# code-behind:
protected void btnSearch_Click(object sender, EventArgs e)
{
GridView1.DataBind();
}
Table [dbo].[users]:
id name username
---- ---- --------
0 Jack jhenry
1 Jim jcallaway
2 Phillip pmcarthur
I simply get an empty grid, then I tried to set the default value to " " (single space) and modified #filter IS NULL to #filter = ''. This gave me the whole grid as expected but when I enter a value in the textbox and hit Search, nothing happens. How do I get the filter hooked up to the SqlDataSource with least effort?
Dirty fix:
Searching for a space " " instead of NULL works, but I have set ConvertEmptyStringToNull = True
SELECT
[id], [username], [name]
FROM
[dbo].[users]
WHERE
#filter = ' ' OR
LEN(#filter) = 0 OR
[name] LIKE ('%'+#filter+'%')
I would rather use IS NULL to make it clean, is it possible?
Could you add Type="String" to ControlParameter and try with the following query?
SELECT [id], [username], [name]
FROM [dbo].[users]
WHERE LTRIM(RTRIM(#filter)) = ''
OR [name] LIKE '%'+ LTRIM(RTRIM(#filter)) +'%'
<SelectParameters>
<asp:ControlParameter ControlID="txtSearch"
DefaultValue=""
Name="filter"
Type="String"
PropertyName="Text" />
</SelectParameters>
Updated:
You need to rebind datasource instead of Grid.
protected void btnSearch_Click(object sender, EventArgs e)
{
SQLDataSource1.DataBind();
}
Stored procedure:
If you want validation logic, it is better to use a stored procedure.
For example:
CREATE PROCEDURE GetUsers
#Filter NVARCHAR(100) = NULL
AS
BEGIN
DECLARE #SearchFilter BIT
SET #SearchFilter = 1
IF (#Filter IS NULL OR RTRIM(LTRIM(#Filter)) = N'')
SET #SearchFilter = 0
SET #Filter = ISNULL(#Filter, '')
SET #Filter = '%' + RTRIM(LTRIM(#Filter)) + '%'
SELECT [id], [username], [name]
FROM [dbo].[users] WITH (NOLOCK)
WHERE #SearchFilter = 0
OR [name] LIKE #Filter
END
I've searched around for a while and tried all the different solutions but I can't seem to get the database updated.
I've executed the stored procedure on its own through SSMS and it works fine.
Here's my asp settings:
<asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" UpdateCommand="spProofStamp" UpdateCommandType="StoredProcedure">
<UpdateParameters>
<asp:Parameter Name="sID" Type="String" />
<asp:Parameter Name="UserID" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
Button:
<dx:LayoutItem Caption="">
<LayoutItemNestedControlCollection>
<dx:LayoutItemNestedControlContainer ID="LayoutItemNestedControlContainer1" runat="server">
<dx:ASPxButton ID="ASPxFormLayout2_E2" OnClick="Button1_Click" runat="server" Text="Validate" AutoPostBack="false">
<ClientSideEvents Click="function(s,e){validate();}" />
</dx:ASPxButton>
</dx:LayoutItemNestedControlContainer>
</LayoutItemNestedControlCollection>
</dx:LayoutItem>
My code behind (I've tried databind and update separately as well).
I've also traced through the values and they're all there, how can I tell if the Update/DataBind works or not? Other Databinds within my code are working fine:
protected void Button1_Click(object sender, EventArgs e)
{
SqlDataSource5.UpdateCommandType = SqlDataSourceCommandType.StoredProcedure;
SqlDataSource5.UpdateCommand = "spProofStamp";
SqlDataSource5.UpdateParameters["sID"].DefaultValue = selectedValue;
SqlDataSource5.UpdateParameters["UserID"].DefaultValue = login.ToUpper();
SqlDataSource5.Update();
SqlDataSource5.DataBind();
}
StoredProcedure:
ALTER PROCEDURE [dbo].[spProofStamp]
#UserID nvarchar(15),
#sID nvarchar(15)
AS
SET NOCOUNT ON
UPDATE [dbo].[ORDER]
SET [USERID] = #UserID,
[DATE] = CURRENT_TIMESTAMP
WHERE ID = #sID
I would like to recommend you to change your method from sqldatasource to code behind, as it makes your code more clear and it is more effective.
You may use the next method:
protected void UpdateDB(string user_id, string sid){
SqlConnection con = new SqlConnection(your_connection_string);
SqlCommand cmd = new SqlCommand("spProofStamp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#USERID", SqlDbType.NVarChar).Value = user_id;
cmd.Parameters.Add("#SID", SqlDbType.NVarChar).Value = sid;
try{
con.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex){
//process your exception
}
finally{
con.Close();
Response.Redirect(Request.Url.AbsoluteUri); //refresh this page
}
}
And call your method:
UpdateDB(login.ToUpper(), selectedValue);
I have a page that list products from table based on values passed in querystring.
ex:- abc/product.aspx/subcat=Mobile&bnd=Samsung
Here it will display all mobile with brand Samsung
How can i display all mobile irrespective of the brand if bnd is empty or not passed i.e only subcat value is passed.
I need SqlDataSource command to do the same. My current query is as shown below:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:shoppingConnectionString2 %>"
SelectCommand="SELECT * FROM [ProductDetails] WHERE (([Sub_category] = #Sub_category) AND ([Brand] = #Brand OR #Brand IS NULL))"
onselecting="SqlDataSource1_Selecting">
<SelectParameters>
<asp:QueryStringParameter Name="Sub_category" QueryStringField="subcat"
Type="String" DefaultValue="" "" />
<asp:QueryStringParameter Name="Brand" QueryStringField="bnd" Type="String"
DefaultValue="IS NULL" ConvertEmptyStringToNull="True" />
</SelectParameters>
</asp:SqlDataSource>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string subcat = Request.QueryString["subcat"];
string bnd = Request.QueryString["bnd"];
string query = "SELECT * FROM [ProductDetails] WHERE ([Sub_category] = " + subcat + ")";
if (!String.IsNullOrEmpty(bnd))
{
query += " AND ([Brand] = " + bnd + ")";
}
SqlDataSource1.SelectCommand = query;
}
}
HTML markup:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:shoppingConnectionString2 %>"
SelectCommand="SELECT * FROM [ProductDetails]"
onselecting="SqlDataSource1_Selecting">
</asp:SqlDataSource>
(Note the removed SelectParameters)
I've never used a SqlDataSource before, but this is similar to what I'd do for an ObjectDataSource. Would the above code work for your scenario?
EDIT : Please note that this method is open to SQL injection attacks, so you ought to validate/sanitize the querystring parameters first.
i have an application where a user logs in and can edit his/other's data. however, if the user is an admin, he gets a gridview with all user's records which he can edit. if the user is not an admin, he will just get a listview where he can edit his own data.
when a user logs into the page, his userid, which is in itself also stored in the db, is stored as a session variable in Session["ID"]. now i need to populate the listview with the user's data. i thought it would be good to just query the data based on the Session["ID"] parameter. but i am not sure how to do this.
EDIT:
ok i have little code regarding this as i have no idea how to do it but i will post what i have. first is the method where i set the session variable of the userid:
objda = new SqlDataAdapter("[GetIDOfUser]", objcon);
objda.SelectCommand.CommandType = CommandType.StoredProcedure;
objda.SelectCommand.Parameters.Add("#Username", SqlDbType.VarChar).Value = tbUsername.Text;
objda.SelectCommand.Parameters.Add("#UserPassword", SqlDbType.VarChar).Value = tbPassword.Text;
String id = (string)objda.SelectCommand.ExecuteScalar();
Session["ID"] = id;
this is my markup:
<asp:ListView ID="ListView1" Visible="False" runat="server" DataSourceID="SqlDataSource2"></asp:ListView>
this is the code where i enable the listview:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserAuthentication"] == null)
{
Response.Redirect("Login.aspx");
}
if (Session["Benutzerart"].ToString() == Enums.Enumerations.Benutzer.Administrator.ToString())
{
GridView1.Visible = true;
//Set controls for admin
}
if (Session["Benutzerart"].ToString() != Enums.Enumerations.Benutzer.Administrator.ToString())
{
ListView1.Visible = true;
//Set controls for other users
}
}
ok guys i have figured it out:
i just make normal listview as in the code above. only the data source has no selectcommand attribute in the markup. this attribute is set in-code:
if (Session["Benutzerart"].ToString() != Enums.Enumerations.Benutzer.Administrator.ToString())
{
ListView1.Visible = true;
SqlDataSource2.SelectCommand = "SELECT [Titel], [Bezeichnung], [Vorname], [Nachname], [Geburtsdatum], [Geburtsort], [Straße], [Nationalität], [Hausnummer], [PLZ], [Ort], [Land], [Mobil], [UrlaubstageGenommen], [UrlaubstageInsgesamt], [Status], [Benutzerart], [Homepage], [Email], [Festnetz], [Fax], [UrlaubstageRest], [Username], [UserPassword] FROM [Benutzer] WHERE [BenutzerID] = '" + Session["ID"] + "'";
}
markup of datasource:
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ></asp:SqlDataSource>
you are binding listview with SqlDataSource, use sqldatasource SelectParameter
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:yourConnection %>"
SelectCommand="SELECT * FROM yourTable WHERE userid = #userid">
<SelectParameters>
<asp:SessionParameter Name="userid" SessionField="ID" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
To select data from DB you can create sql data source and bind it to ListView:
SqlDataSource ds = new SqlDataSource();
ds.ConnectionString = yourDBconnectionString;
ds.SelectCommand = "SELECT * FROM records_table WHERE user_id=#user_id";
ds.SelectParameters.Add("user_id", Convert.ToInt32(Session["id"]));
ListView1.DataSource = ds;
ListView1.DataBind();
Then to bind records fields to ListView on aspx page use (just an example):
<%# Eval("recort_title") %>
I have placed a checkboxlist in a formview object.
I would like to store and load the results of the checkboxlist in a table of an entity framework.
I filled the cbl with values and labels coming from a table that has 2 columns, using the DataSourceID, DataTextField and DataValueField attributes but I can't seem to find how to bind the cbl to the entity framework object in order to store the checked values when the formview is in "EDIT" mode.
Any help would be appreciate. Thanks!
<asp:FormView ID="formView1" runat="server" DataSourceID="Ods1"
Height="203px" Width="495px"
onpageindexchanging="formView1_PageIndexChanging">
<EditItemTemplate>
<asp:CheckBoxList ID="cblProducts" runat="server" RepeatColumns="3"
Width="782px" DataSourceID="SqlDataSource1" DataTextField="ProductName"
DataValueField="ProductCode">
</asp:CheckBoxList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [ProductCode], [ProductName] FROM [Products]">
</asp:SqlDataSource>
</EditItemTemplate>
</asp:FormView>
<asp:ObjectDataSource ID="Ods1" runat="server"
DataObjectTypeName="WebApplication1.EDM.Emp" DeleteMethod="DeleteEmp"
InsertMethod="CreateNewEmp" OldValuesParameterFormatString="original_{0}"
SelectMethod="GetEmpByEmpId" TypeName="WebApplication1.EDM.EmpLogic"
UpdateMethod="UpdateEmp" OnSelecting="Ods1_Selecting">
<SelectParameters>
<asp:RouteParameter Name="EmpId" RouteKey="EmpId" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:FormView ID="formView1" runat="server"
OnItemUpdating="formView1_ItemUpdating" ...>
protected void formView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
var cblProducts = formView1.FindControl("cblProducts") as CheckBoxList;
foreach (ListItem item in cblProducts.Items)
{
if (item.Selected)
{
// Check if item.Value is not in the db for this employee, if so add it
}
else
{
// Check if item.Value is in the db for this employee, if so delete it
}
}
// save
}
You need to do the following;
foreach (ListItem chk in cblProducts.Items)
{
string productId= chk.Value;
if (IsProductAvailable(productId) // this method will basically goes to database and return true of false
chk.Selected = true;
else
chk.Selected = false;
}
private void IsProductAvailable(string productId)
{
string query = "SELECT [ProductId] FROM [Product] ";
query += "WHERE [ProductId] = #ProductId";
DbCommand comm = new DbCommand();
comm.CommandText = query;
DbParameter param = comm.CreateParameter();
param.ParameterName = "#ProductId";
param.Value = productId;
comm.Parameters.Add(param);
DataTable table = comm.ExecuteCommand();
if (table.Rows.Count > 0)
{
return true;
}
else
return false;
}
please modify query and parameters according to your need.