how to set passing variable in SelectCommand Asp.net - c#

i try this example but not working.
<%string id = Request.QueryString["id"]; %>// get value and set in one variable
<%=id%>// display successfully variable's value
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [id], [name], [image], [old_price], [new_price] FROM [product] where [id]= "'<%=id%>'"" ></asp:SqlDataSource>
a problem in SelectCommand how to set variable in query i try like <%=id%>

Use the codebehind, for example in the Selecting event:
<asp:SqlDataSource ID="SqlDataSource1" ... OnSelecting="Product_Selecting">
Codebehind:
protected void Product_Selecting(object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters[0].Value = Request.QueryString["id"];
}

Related

Changing SqlDataSource SelectCommand and SelectParameter with a button

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString9 %>" ProviderName="<%$ ConnectionStrings:ConnectionString9.ProviderName %>" SelectCommand="SELECT * FROM [Orders] WHERE ([oStatus] = ?)">
<SelectParameters>
<asp:Parameter DefaultValue="CheckedOut" Name="oStatus" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Above is the code for the SqlDataSource. What I am trying to do is to add a button which will help me add an additional WHERE condition into SelectCommand and add the SelectParameters for the added condition.
Button
<asp:Button runat="server" text="filter record" ID="filterbutton" OnClick="filterbutton_Click"/>
What I want the SelectCommand to look like when button is clicked
SelectCommand="SELECT * FROM [Orders] WHERE ([oStatus] = ?) AND ([oDelivery_Status] = ?)">
Question is it is possible to add more than 1 SelectParameters? And is it possible to do so with a button OnClick method? If not, are there any other solutions/methods? Thank you in advance.
You need to set both Parameters which you want in your SelectCommand like this:
protected void filterbutton_Click(object sender, EventArgs e)
{
string stroStatus = "";
string stroDelivery_Status = "";
SqlDataSource1.SelectParameters["oStatus"].DefaultValue = stroStatus;
Parameter pm = SqlDataSource1.SelectParameters["oDelivery_Status"];
if (!SqlDataSource1.SelectParameters.Contains(pm))
{
SqlDataSource1.SelectParameters.Add("oDelivery_Status",
stroDelivery_Status);
}
SqlDataSource1.SelectCommand = "SELECT * FROM [Orders] WHERE ([oStatus] = #oStatus) AND ([oDelivery_Status] = #oDelivery_Status)"
}

Asp.Net GridView Datasource in aspx page

In default.aspx.cs , i defined a public variable. = my_id
And i can use this variable in my aspx page.
But i can't use in GridView DataSourceQuery.
My gridview's datasource code : ( in aspx )
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:aspnetdbConnectionString %>" SelectCommand="SELECT [mus_ad], [marka], [model], [durum] FROM [servis_kayitlari] WHERE [kullanici_id] LIKE '<%= my_id ;%>'">
</asp:SqlDataSource>
After this datasource query , gridview comes null. What is the problem in this query ?
You should use parameterized query(see Using Parameters with the SqlDataSource Control for reference) and assign parameter value in SqlDataSource.Selecting event:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:aspnetdbConnectionString %>"
SelectCommand="SELECT [mus_ad], [marka], [model], [durum] FROM [servis_kayitlari] WHERE [kullanici_id] LIKE #my_id"
OnSelecting="SqlDataSourceSelectingEventHandler">
<SelectParameters>
<asp:Parameter Name="my_id" Type="Int32" DefaultValue="0" />
</SelectParameters>
</asp:SqlDataSource>
And event handler:
public void SqlDataSourceSelectingEventHandler(object sender, SqlDataSourceSelectingEventArgs e)
{
SqlDataSource1.SelectParameters["my_id"].DefaultValue = this.my_id;
}
As suggested in other answer, you should rather choose to use parametrized query but per your posted query, the issue is in binding variable with LIKE. You need to remove the ; in <%= my_id ;%>. Your query should look like
SELECT [mus_ad], [marka], [model], [durum] FROM [servis_kayitlari] WHERE [kullanici_id] LIKE '<%= my_id %>'"

dropdown list on showing selected item from list

I have a dropdownList and it currently should be showing two items on list- when i am selecting the second one it goes back and shows the first item in the dropdown list.
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDown.DataTextField = "DisplayName";
DropDown.DataValueField = "ID";
DropDown.DataBind();
}
}
<asp:DropDownList ID="DropDown" runat="server"AutoPostBack="True" DataSourceID="Sections">
</asp:DropDownList>
<asp:SqlDataSource ID="Sections" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnection %>" SelectCommand="SELECT e.DisplayName, e.ID , e.GUID
FROM .. e
INNER JOIN .. re
ON e.ID = re.anID
AND re.otherID = 1">
</asp:SqlDataSource>
Remove binding from design and try below code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDown.DataSourceID = Sections;
DropDown.DataTextField == "DisplayName";
DropDown.DataValueField = "ID";
DropDown.DataBind();
}
}
Thanks,
Hitesh
Just set your Dropdown Auto AutoPostBack to False.
<asp:DropDownList ID="DropDown" runat="server" DataTextField="DisplayName" DataValueField="ID" AutoPostBack="False" DataSourceID="Sections">
</asp:DropDownList>
<asp:SqlDataSource ID="Sections" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnection %>" SelectCommand="SELECT e.DisplayName, e.ID , e.GUID
FROM .. e
INNER JOIN .. re
ON e.ID = re.anID
AND re.otherID = 1">
</asp:SqlDataSource>
Check this Url based on your new query: Populate one dropdownlist based upon action of another dropdownlist
Best Regards

Using A Session Variable In ASP.Net Gridview

I have a session variable which holds the current logged in user's details. I'd like to run a query based on the variable and display it in a Grid view.
I want to replace the default value of the grid view with the session variable but that didn't work.
Can anyone point me in the right direction?
This is what I tried:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:..... %>"
SelectCommand="SELECT [Username], [Password], [CustomerName], [CustomerAddress], [Contact] FROM [Customers] WHERE ([Username] = #Username)">
<SelectParameters>
<asp:Parameter DefaultValue="session[new]" Name="Username" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
You can supply the Session variable value just before the Query is executed by SqlDataSource using the Selecting event of the datasource. Set this event in Markup using OnSelecting property.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:..... %>"
OnSelecting="SqlDataSource1_Selecting"
SelectCommand="SELECT [Username], [Password], [CustomerName], [CustomerAddress], [Contact] FROM [Customers] WHERE ([Username] = #Username)">
<SelectParameters>
<asp:Parameter Name="Username" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
In the Selecting Event Handler, you do as below:
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
if(Session["UserName"]!=null)
{
// do this only when Session Variable stores as a string the Username
e.Command.Parameters["#Username"].Value = Session["UserName"];
}
else
{
// assign the default value if session variable is Null
e.Command.Parameters["#Username"].Value ="DefaultValue";
}
}
In this event handler, you can access the command that’s about to be executed through the
SqlDataSourceSelectingEventArgs.Command property, and modify its parameter values programmatically.
What I ended up doing was kind of similar to FlopScientist's answer. I found that the DataSource actually has an option for selecting a session variable which I did in the design view and it has the code below:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:..... %>"
SelectCommand="SELECT [Password], [CustomerName], [CustomerAddress], [Contact], [Username] FROM [Customers] WHERE ([Username] = #Username)">
<SelectParameters>
<asp:SessionParameter Name="Username" SessionField="mySessionVariable" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Session object in ASP.NET is one of the server side state maintenance variable.
More you can find here.
Session variable simply stores any value that you assign it to. And in simple words, you can access this variable on any other page, even if you created it on some other page.
so suppose on page1.aspx you did:
Session["uniqueName"] = GetGridViewData(); //you can store anything.
where signature of GetGridViewData() is suppose like:
public DataTable GetGridViewData();
then on page2.aspx (or any other page), you can do this:
protected void Page_Load(object sender, EventArgs e)
{
if(Session["uniqueName"]!=null)
{
//typecast it to your datastructure or whatever you assigned into it
DataTable gridDataSource = (DataTable)Session["uniqueName"];
//any custom logic you want to perform on gridDataSource
gridView1.DataSource = gridDataSource;
gridView.DataBind();
}
}
Just make sure, you access the variable only after you have assigned/created earlier in the flow.

How to embed variable value in sqldatasource session parameter in c#

I want to question how to embed variable value in sqldatasource session parameter in c#. This is mycode:
default.aspx:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Ora2011 %>"
ProviderName="<%$ ConnectionStrings:Ora2011.ProviderName %>"
SelectCommand="SELECT ID, CATEGORY_NAME FROM (:INVENT_CATEGORY)">
<SelectParameters>
<asp:SessionParameter Name="INVENT_CATEGORY" SessionField="INVENT_CATEGORY" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
C#:
protected void Page_Load(object sender, EventArgs e)
{
string table = "V_INVENTORY"
Session["INVENT_CATEGORY"] = table;
}
When i run this program, i get error "invalid table name". Why i can't embed variable into sqldatasource from session parameter. Thanks for your help
Your issue isn't with the Session parameter... The problem is that you are trying to specify the table-name via a parameter -- which I'm pretty sure is not supported. You'd have to build the query string yourself in your code-behind to do what you are trying to do.
I'm not sure why you are storing the table name in Session, but an example of setting the sql select in code-behind would be...
Markup:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Ora2011 %>"
ProviderName="<%$ ConnectionStrings:Ora2011.ProviderName %>"
</asp:SqlDataSource>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
string table = (string)(Session["INVENT_CATEGORY"] ?? "V_INVENTORY");
SqlDataSource1.SelectCommand = "SELECT ID, CATEGORY_NAME FROM " + table;
}
You must make sure that the session value for the table name can only contain valid values, or there is a danger of SQL Injection attacks.

Categories

Resources