How to use controls value in mysql query - c#

I have a database with the tables and columns:
persons: id, first_name, last_name
addresses: id, city, street_number, persons_id
I'm trying to make a search engine in asp.net.
I have controls: TextBox1, DropDownList1, Button1, GridView1 with SqlDataSource1.
The DropDownList1 code:
<asp:DropDownList ID="DropDownList1" runat="server"
DataValueField="first_name" AutoPostBack="false">
<asp:ListItem Value="first_name">First name</asp:ListItem>
<asp:ListItem Value="last_name">Last name</asp:ListItem>
<asp:ListItem Value="city">City</asp:ListItem>
</asp:DropDownList>
In the SqlDataSource control: in the SelectCommand I'm trying to make something like this:
SelectCommand="SELECT first_name, last_name, city FROM persons, addresses WHERE persons.id = addresses.persons_id AND (? LIKE '%'??'%')">
In the ? and ?? I want to put the values from DropDownList1 and TextBox1. Any suggestions ?

You will need two asp:ControlParameter's in your SqlDataSource1 like this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="YourConnectionString"
SelectCommand="SELECT first_name, last_name, city FROM persons, addresses WHERE persons.id = addresses.persons_id AND (#FirstLastCity LIKE '%#SearchString%')">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="FirstLastCity" PropertyName="SelectedValue" />
<asp:ControlParameter ControlID="TextBox1" Name="SearchString" PropertyName="Text" />
</SelectParameters>
</asp:SqlDataSource>
This should be the first step. I am pretty sure that '%#SearchString%' in the SelectCommand will not work. But there must be a way to concatinate %, #SearchString and % in the markup code.
Alternatively you can set parameter values in code behind like this:
SqlDataSource1.SelectParameters.Add("#SearchString", "%" + TextBox1.Text + "%");

Related

Trying to list all the usernames if a userName value is not provided.

<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="true" DataSourceID="dataSource1">
</asp:GridView>
<asp:SqlDataSource runat="server" ID="dataSource1" SelectCommand="select UserName from aspnet_Users where UserName = COALESCE(#userName,UserName)" ConnectionString="<%$ ConnectionStrings:MySqlProviderConnection %>">
<SelectParameters>
<asp:QueryStringParameter Name="userName" DbType="String" Direction="Input" QueryStringField="userName" DefaultValue="" ConvertEmptyStringToNull="true" />
</SelectParameters>
</asp:SqlDataSource>
Above is my code. I am trying to list all the usernames if the default is an empty string. But it doesn't give me the result with all the usernames.
Am I missing something here?
If I run the below query in sql server management studio I do get the result I expect.
select UserName from aspnet_Users where UserName = COALESCE(null,UserName)
what am I missing here?
Use this instead.
WHERE UserName = #userName or #userName is null
Or if you are passing an empty string into #userName
WHERE UserName = #userName or #userName =''
Your last query, select UserName from aspnet_Users where UserName = COALESCE(null,UserName), would return all rows where the UserName isn't null which probably isn't what you were thinking it would do.

DataSourceID ASP.NET

Greetings i have this Gridview, ASP.NET has a Wizard to bind Data to Gridview, it gives you the TSQL query in an asp.net tag, but i was wondering how to do it in C# in code-behind.
HTML:
<asp:SqlDataSource ID="SqlDataSourceMain" runat="server"
ConnectionString="<%$ ConnectionStrings:Laptop %>" SelectCommand="SELECT [fCodeProducts],
[fCodeGroup], [fName], [fPrice], [fImageName],
[fDesc], [fMojoodi], [Namayesh],
[FileAddress] FROM tProducts WHERE (fCodeGroup = 12)
OR (fCodeGroup = #fCodeGroup) AND (Namayesh = 'True')
ORDER BY fCodeGroup">
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" DefaultValue="200" Name="fCodeGroup" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
If you need to change the SqlDataSource on code behind, you can do it like this:
SqlDataSourceMain.SelectCommand = "Select * from tProducts where Id=#MyParameter";
SqlDataSourceMain.SelectParameters["MyParameter"].DefaultValue = 1;
SqlDataSourceMain.DataBind();
You use it the exact same way, just bind it and bind it to your control.
Here is an Example that goes into more depth.

Return all values from table if one field in query string is empty and its in String format

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.

DropDownList, getting DataValueField returned in C#

I have a drop down list that pulls data from a database to show some of its options:
<asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="SqlDataSource1"
DataTextField="Name" DataValueField="PK_Task" AppendDataBoundItems="true" CssClass="dropDownList">
<asp:ListItem Selected="True">General Support</asp:ListItem>
<asp:ListItem>Vacation</asp:ListItem>
<asp:ListItem>Sick Leave</asp:ListItem>
<asp:ListItem>Something Else</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [PK_Task], [Name] FROM [Task] WHERE ([PointPerson] LIKE '%' + #PointPerson + '%') AND [Status] NOT LIKE 'Done'">
<SelectParameters>
<asp:QueryStringParameter Name="PointPerson" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
As you can see, I only display the [Name] column:
DataTextField="Name"
But I am also getting the primary key SELECT [PK_Task], [Name] FROM:
DataValueField="PK_Task"
How do I get access to this primary key based on user selection. If a user selects a specific 'name' from the drop down menu, what C# can I use to get the corresponding primary key returned to me so I can save it in a variable?
The closest I have gotten is this, but all it does is return the string "PK_Task":
String taskID = DropDownList3.DataValueField;
You can use the SelectedValue property:
// to set
DropDownList3.SelectedValue = "1";
// to read
string value = DropDownList3.SelectedValue;
try this
String taskID = DropDownList3.SelectedItem.Value;
any way you can use
either
dropdown3.selectedvalue
or
dropdown3.selecteditem.value

asp.net dropdownlist selected value

When I select a value from the dropdownlist, I like that value to be save in the #TimeZone value that is needed for
InsertCommand="INSERT INTO [Companies] ([TimeZone]) VALUES ( #TimeZone)"
I am not sure how to do this.
Here is my code:
Within my page load, I have the following code that assigns value to the drop down:
ddlTimeZone.DataSource = from p in TimeZoneInfo.GetZones()
select new { p.Id };
ddlTimeZone.DataTextField = "Id";
ddlTimeZone.DataValueField = "Id";
ddlTimeZone.DataBind();
Next, within my .aspx file, I have the following:
<EditItemTemplate>
<asp:DropDownList ID="ddlTimeZone" runat="server">
</asp:DropDownList>
</EditItemTemplate>
..... .....
InsertCommand="INSERT INTO [Companies] ([TimeZone]) VALUES ( #TimeZone)"
<InsertParameters>
<asp:Parameter Name="TimeZone" Type="String" />
</InsertParameters>
Again, what I need to know is how to I bind the selected value from the dropdownlist (ddlTimeZone) to #TimeZone
I tried:
<asp:DropDownList ID="ddlTimeZone" SelectedValue='<%# Bind("TimeZone") %>' runat="server">
</asp:DropDownList>
But that did not work. NOTE THAT I AM USING THE DROPDOWNLIST WITHIN A GRIDVIEW.
Try this way
var command = new SqlCommand("INSERT INTO [Companies] ([TimeZone]) VALUES ( #TimeZone)", connection);
command.Parameters.Add(new SqlParameter("#TimeZone", valuetopass));

Categories