Displaying posts made by user that is logged in - c#, asp.net - c#

I have converted the session into a string in the .cs file,
String username = Session["SELLER"].ToString();
This is my code for the .aspx file.
<asp:SqlDataSource ID="ViewAdvertisement" runat="server" ConnectionString='<%$ ConnectionStrings:ElmtreeConnection %>'
SelectCommand="SELECT Products.Name, Products.Price, Products.Description, Products.DatePosted, Products.CategoryId, Products.Image, Products.Username
FROM Products
WHERE Products.Username = #username">
<SelectParameters>
<asp:QueryStringParameter Name="username" QueryStringField="Username" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
So how do I display the posts of the user logged in, as clearly my code isn't right at all.

If you are storing the current user name in session (That's the SELLER variable purpose?), if that understanding is correct, use the asp:SessionParameter:
<asp:SessionParameter Name="username" SessionField="SELLER" Type="String" />

Related

What this usage of '#' in ASP.NET mean

I am learning ASP.NET(C#) and came across this code:
<asp:DropDownList
id="ddlMovieCategory"
DataSourceID="srcMovieCategories"
DataTextField="Name"
DataValueField="Id"
Runat="server" />
<asp:Button
id="btnSelect"
Text="Select"
Runat="server" />
<asp:GridView
id="grdMovies"
DataSourceID="srcMovies"
CssClass="gridView"
Runat="server" />
<asp:SqlDataSource
id="srcMovieCategories"
SelectCommand="SELECT Id, Name FROM MovieCategories"
ConnectionString="<%$ ConnectionStrings:Movies %>"
Runat="server" />
<asp:SqlDataSource
id="srcMovies"
SelectCommand="SELECT Title,Director FROM Movies
WHERE CategoryId=#Id"
ConnectionString="<%$ ConnectionStrings:Movies %>"
Runat="server">
<SelectParameters>
<asp:ControlParameter
Name="Id"
ControlID="ddlMovieCategory"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
I am wondering How the # symbol in the last control's SelectCommand work. It works as expected but I don't understand how it gets the value following the # i.e. if it is to use a variable which is escaped in ASP tag then how does it know that Id refers to the DropDownList's currently selected item.
Edit: I think I might have found the solution. I think it's from this bit of code, Am I correct:
<asp:ControlParameter
Name="Id"
ControlID="ddlMovieCategory"
PropertyName="SelectedValue" />
</SelectParameters>
The following string
"SELECT Title,Director FROM Movies WHERE CategoryId=#Id"
represents a parameterized sql query. The value of parameter Id, #Id, would be assigned to CategoryId, before this query is sent to database, in order to be executed.
Parameterized queries are the first thing we use, in order we avoid SQL injections.

ObjectDataSource calling multiple times in nested gridview

I have nested GridView. When I expand row of external it shows internal GridView. Both gridviews are inside UpdatePanel and uses ObjectDataSource to populate data.
When I click on expand, I'm doing a post back by clicking a button via JQuery. Here, ObjectDataSource1 which is for external grid calls SelectMethod multiple times. I checked UpdatePanel UpdateMode is Conditional.
How can I prevent ObjectDataSource from fetching data multiple times?
ASPX:
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectCountMethod="GetDevicesCount" SelectMethod="GetDevices" TypeName="Flows" SortParameterName="sortExpression" EnablePaging="True">
<SelectParameters>
<asp:ControlParameter ControlID="txtSearch" Name="searchTerm" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="hdnFieldFromDate" Name="fromDate" PropertyName="Value" Type="String" />
<asp:ControlParameter ControlID="hdnFieldToDate" Name="toDate" PropertyName="Value" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:ObjectDataSource ID="ObjectDataSource2" runat="server" SelectCountMethod="GetFlowDetailsCount" SelectMethod="GetFlowDetails" OnSelecting="ObjectDataSource2_Selecting" TypeName="Flows" EnablePaging="True">
<SelectParameters>
<asp:ControlParameter ControlID="HiddenDeviceId" Name="deviceId" PropertyName="Value" Type="String" />
<asp:ControlParameter ControlID="hdnFieldFromDate" Name="fromDate" PropertyName="Value" Type="DateTime" />
<asp:ControlParameter ControlID="hdnFieldToDate" Name="toDate" PropertyName="Value" Type="DateTime" />
</SelectParameters>
</asp:ObjectDataSource>
I have handled this in two ways.
1: In the ASPX side of your page set select method to SelectMethod = "" and assign it if the page is postback.
if (Page.IsPostBack)
{
//Always set the select methods.
SetSelectMethods();
}
else
{
ODSGetOptionSearchDataCS.SelectMethod = string.Empty;
ODSWatchlistCS.SelectMethod = string.Empty;
}
private void SetSelectMethods()
{
ODSGetOptionSearchDataCS.SelectMethod = "GetOptionCondors";
ODSWatchlistCS.SelectMethod = "GetOptionWLCondors";
}
I really do not care for how I handled this above, so going forward in my select method I cache the data for 10 seconds (longer if I need to) I allow that method to run again, but returned the cached data vs. hitting the database again.

Parameter with ObjectDataSource

I have a asp GridView in my page.I am using asp ObjectDataSource to bind data to my grid.I am calling a method from data layer to get the data.method have a parameter(userid).I want to pass the parameter from ObjectDataSource.user id is in session variable.How can i pass the parameter in ObjectDataSource?
code
<asp:ObjectDataSource ID="_allSitesDataMgr" runat="server" ConvertNullToDBNull="True"
OldValuesParameterFormatString="{0}" SelectMethod="GetAllSitesByUser" TypeName="PWRWebData.SiteCreation.SitesDataMgr">
</asp:ObjectDataSource>
Take a <SelectParameters> in your object data source
<SelectParameters>
<asp:SessionParameter Name="MyUserID" Type="Int32" SessionField="UserID" />
</SelectParameters>
Update:
<asp:ObjectDataSource ID="_allSitesDataMgr" runat="server" ConvertNullToDBNull="True"
OldValuesParameterFormatString="{0}" SelectMethod="GetAllSitesByUser" TypeName="PWRWebData.SiteCreation.SitesDataMgr">
<SelectParameters>
<asp:SessionParameter Name="MyUserID" Type="Int32" SessionField="UserID" />
</SelectParameters>
</asp:ObjectDataSource>

Formview EditItemTemplate in asp.net c#

I have a product table that am updating. the fields updated are category_id, prod_name, prod_desc, prize, status. I am using a formview to do that updating. however i am having problems with the category_id. the category_id is a databound dropdownlist using a sqldatasource to fetch id and name from category table in the database. When a product has no category_id value, a null value is entered by default by sql.
The problem comes when i go to edititemtemplate mode in formview, the dropdownlist cannot show a null value from db so it throws an exception of:
'category_idDropdown' has a SelectedValue which is invalid because it
does not exist in the list of items. Parameter name: value
this is my code in the updateprod.aspx page:
<asp:DropDownList ID="category_idDropdown" runat="server"
AppendDataBoundItems="True"
AutoPostBack="True"
DataSourceID="catnames"
DataTextField="category_name"
DataValueField="category_id" ViewStateMode="Enabled"
SelectedValue='<%# Bind("category_id") %>' >
<asp:ListItem Text="-- Choose Category--" Value="0" Selected="True">
</asp:ListItem>
</asp:DropDownList>
this is my sqldatasource code the dropdownlist is databound to:
<asp:SqlDataSource ID="catnames" runat="server"
ConnectionString="<%$ ConnectionStrings:cloud_Kewl.Properties.Settings.conString %>"
SelectCommand="SELECT [category_id], [category_name] FROM [category]">
</asp:SqlDataSource>
& finally this is the sqldatasource used to update the product details:
<asp:SqlDataSource ID="productUpdate" runat="server"
ConnectionString="<%$ ConnectionStrings:cloud_Kewl.Properties.Settings.conString %>"
SelectCommand="SELECT prod_id, category_id, prod_name, prod_desc, prod_price, img_name, img_contenttype, prod_img, status FROM product WHERE (prod_id = #prod_id)"
UpdateCommand="UPDATE product SET category_id = #category_id, prod_name = #prod_name, prod_desc = #prod_desc, prod_price = #prod_price, status = #status WHERE (prod_id = #prod_id)">
<SelectParameters>
<asp:QueryStringParameter Name="prod_id" QueryStringField="prod_id" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="category_id" Type="Int32" DefaultValue="0" />
<asp:Parameter Name="prod_name" Type="String" />
<asp:Parameter Name="prod_desc" Type="String" />
<asp:Parameter Name="prod_price" Type="Decimal" />
<asp:Parameter Name="status" Type="String" />
<asp:Parameter Name="prod_id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
i looked up in the questions regarding the formview and edititemtemplate in this site, but none came close to give me any idea on how to approach this problem.
I tried to solve it programatically but not success in cracking this problem. Please help me, i looked for the solution for 3 weeks. no success :(
Try rebinding your datasource prior to the null value being set:
protected void myFormView_OnItemEditing(object sender, ListViewEditEventArgs e)
{
DropDownList category_idDropdown = (DropDownList)(myFormView.FindControl("category_idDropDown"));
category_idDropdown.DataBind();
category_idDropdown.Items.Add(0, new ListItem("Select", null));
}
The problem likely isn't that you're trying to select a value that doesn't exist, but rather that you're trying to bind a DropDownList that already has a null value to a datasource that doesn't contain that value.

Deleting is not supported in my data source? How can i activate that?

I just got this message from Visual Studio 2005, when I clicked on the delete command I added to my gridview using the interface for configuring the grid:
Deleting is not supported by data
source 'transactionsSqlDataSource'
unless DeleteCommand is specified.
How can I activate that? I want my user to be able to delete a row when they click on the button Delete.
I already changed the property DeleteCommandType of my SQLDataSource to StoredProcedure.
What else do I need to do?
UPDATE
This is what I did, but I am missing something, I can't compile:
This is what I did at .cs:
public string DeleteCommand { get; set; }
How can I fix that, it says that the get is missing the body. I am not use to ASP.NET. Could you help me fixing this part of my code?
This is what I did at .aspx:
<asp:SqlDataSource ID="transactionsSqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:membershipsDBConnectionString %>"
SelectCommand="SELECT [brukerId], [kjoptekvoten], [pengeneutbetalt], [fyringsolje], [biltype], [kjoptid] FROM [Informasjon]" DeleteCommandType="StoredProcedure"
DeleteCommand="DELETE FROM [Informasjon] WHERE fyringsolje='Kull: 2,42 kg';">
</asp:SqlDataSource>
Is the configuration for the datasource correct? Dont worry if you see that the delete command does not use parameters like the one above, it is just for a homework(I only need the query to pass).
UPDATE 2
I keep trying but i cant fix it. I am really newbie in ASP.NET and I am not very familiar with all the terminology. What exactly is happening here? How can I know the name of my store procedure?:
CS:
public string DeleteCommand { get { return DeleteCommand; } set { DeleteCommand = "";}
Aspx:
<asp:SqlDataSource ID="SqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:membershipsDBConnectionString %>"
DeleteCommandType="StoredProcedure" SelectCommand="SELECT [id], [kjoptekvoten], [pengeneutbetalt], [fyringsolje], [biltype], [kjoptid] FROM [Informasjon]"
DeleteCommand="StoredProcedureName">
</asp:SqlDataSource>
When I click on Delete that row needs to be erased from table Informasjon
DeleteCommand="<your stored proc>"
is needed in your SqlDataSource along with any parameters you want, for instance:
<DeleteParameters>
<asp:Parameter Name="myParameter" Type="Int32" />
</DeleteParameters>
which needs to be added in the SqlDatasource tag.
You can either call a stored procedure if you have created one like below :
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
// in the select command or your case delete you just input the name instead of a query
SelectCommand="SELECT * FROM [Table] WHERE [Column1]=#Parameter1 AND [Column2]=#Parameter2 AND [Column3]=#Parameter3;"
DeleteCommand="StoredProcedureName"
// Then ofcourse put the commandtype on storedprocedure but you already have that
DeleteCommandType="StoredProcedure">
// And you can declare the parameters like below
<SelectParameters>
<asp:Parameter Name="Parameter1" Type="String" />
<asp:Parameter Name="Parameter2" Type="Boolean" />
<asp:Parameter Name="Parameter3" Type="String" />
<asp:Parameter Name="Parameter4" Type="Boolean" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="Parameter1" Type="String" />
</DeleteParameters>
</asp:SqlDataSource>
For more information about storedprocedures please read : What is a stored procedure?
Or you can directly call a query like in the example below :
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [informasjon];"
DeleteCommand="DELETE FROM [informasjon] WHERE [id]=#id;">
<DeleteParameters>
<asp:Parameter Name="id" Type="Int" />
</DeleteParameters>
</asp:SqlDataSource>
The connection string is something you will have to provide for yourself. For more info on the connectionstring please read : https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring%28v=vs.110%29.aspx

Categories