Using Session variables in InsertCommand attribute of asp:LinkButton - asp.net

I would like to use a Session variable created in the code-behind, in an actual tag, primarily within the InsertCommand="" attribute:
Here is my code-behind (VB):
Protected Sub RegSubmitButton_Click(sender As Object, e As EventArgs) Handles RegSubmitButton.Click
For Me.i = 0 To UNPWListBox.Items.Count
If (RegUNTextBox.Text = UNPWListBox.SelectedItem.Text) Then
MsgBox("Username is unavailable. Please choose another username.")
With RegUNTextBox
.Text = ""
.Focus()
End With
Else
username = RegUNTextBox.Text
password = RegPWTextBox.Text
UNPWListBox.Items.Insert(UNPWListBox.SelectedIndex + 1, RegUNTextBox.Text)
'UNPWListBox.Items.Add(username)
UNPWListBox.SelectedItem.Text.Equals(username)
UNPWListBox.SelectedItem.Value.Equals(password)
Session(username) = username
Exit For
End If
Next
Dim newConnection = CreateObject("ADODB.Connection")
Dim createTable = "CREATE TABLE [" + Session(username) + "] (ID int, Artist varchar(50), Title varchar(50), Label varchar(25), PressNumber varchar(15), YearReleased varchar(15), NMValue double, Notes string);"
newConnection.Open("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\allengatorpie\Documents\VBIIT1_DB.accdb")
newConnection.Execute(createTable)
Response.Redirect("AddVinyl.aspx")
Below is the ASP.NET source:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\allengatorpie\Documents\VBIIT1_DB.accdb"
ProviderName="System.Data.OleDb" SelectCommand="SELECT * FROM
[allengatorpie]" InsertCommand="INSERT INTO [Session(username)] ([Artist], [Title], [Label], [PressNumber], [YearReleased],
[NMValue], [Notes]) VALUES (?, ?, ?, ?, ?, ?, ?)">
The Session(username) variable work perfectly in the code behind, but I need to use it in the ASP control so that SQL knows which table to insert the data into.
Thanks in advance.

You can use inset parameters More details
Example
<asp:sqldatasource
id="SqlDataSource1"
runat="server"
connectionstring="<%$ ConnectionStrings:MyNorthwind %>"
......>
<insertparameters>
<asp:formparameter name="CoName" formfield="CompanyNameBox" />
<asp:formparameter name="Phone" formfield="PhoneBox" />
</insertparameters>
</asp:sqldatasource>

Related

ASP.NET Listbox Multiple Items passed to SQL Server then passed to Gridview

What I'm trying to do is to select multiple countries from listbox, then hit select, then a gridview would pull out data from a table based on the countries selected. my problem is that I don't know how to pass the string where country in (A,B,C,...) into a SQL Server stored procedure. Any advice on this would be great!
My listbox is
<asp:ListBox ID="Country" cssclass="LBox" runat="server" SelectionMode="Multiple">
<asp:ListItem Text="A" Value="A" />
<asp:ListItem Text="B" Value="B" />
<asp:ListItem Text="C" Value="C" />
<asp:ListItem Text="D" Value="D" />
..............
</asp:ListBox>
My select button is
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim li As ListItem
Dim myString As String = ""
Dim myString2 As String = ""
For Each li In ListBoxComp.Items
If li.Selected = True Then
If myString = "" Then
myString = "'" & li.Text & "'"
Else
myString = myString & ", " & "'" & li.Text & "'"
End If
End If
Next
myString2 = myString2
Session("Selected") = myString2
from
http://forums.asp.net/t/1618260.aspx?code+SQL+to+retrieve+records+from+multiple+random+selection+list+box
My gridview is
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" BackColor="White"
BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" DataSourceID="SqlDataSource1" ForeColor="Black"
GridLines="Vertical">
......
</asp:GridView>
Datasource is
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="usp_select" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:SessionParameter Name="myString2" SessionField="Selected" />
</SelectParameters>
</asp:SqlDataSource>
SQL Server stored procedure is
ALTER PROCEDURE [dbo].[usp_select]
#myString2 varchar(5000)
AS
BEGIN
SELECT *
FROM dbo.table
WHERE country IN (#myString2)
END
My problem is that I don't know how to pass the string where country in (A,B,C,...) into the SQL Server stored procedure. Any advice on this would be great!
In the example you got your code from, you must use dynamic sql in your stored proc. Something like:
Declare #sqlstring varchar(max);
Set #sqlstring = 'Select * from dbo.table where country in (' + #myString2 + ')';
Execute sp_executesql #sqlstring;
Otherwise you're trying to use IN with just a string, which is causing your problems I think.
But honestly, I stay away from dynamic sql when possible. You might consider finding a good split string function that turns your string into a table or cte. Then you could use these rows in a join or a "where exists" clause. I like to pass stuff like this in as xml and use an xml function to create a similar cte. A final alternative is to create a user-defined table type with just rows of strings and pass this into your stored proc from a datatable on the front end, but that's probably overkill.
You could try this:
Define an StrList data type in SQL Server:
USE [YourDB]
GO
CREATE TYPE [dbo].[StrList] AS TABLE(
[Value] [varchar](100) NULL
)
GO
Alter your stored procedure to accept that kind of parameter instead of the string:
ALTER PROCEDURE [dbo].[usp_select]
#countryList AS StrList READONLY
AS
BEGIN
SELECT *
FROM dbo.table
WHERE country IN (SELECT Value FROM #countryList)
END
Pass the country names as a StrList instead of a string. I am not sure how to do it with the SessionParameter, however. In code-behind, I do it like this:
Dim tbl As new DataTable()
tbl.Columns.Add("Value", System.Type.GetType("System.String"));
For Each li In ListBoxComp.Items
If li.Selected = True Then
tbl.Rows.Add(li.Text)
End If
Next
Dim prm As new SqlParameter("#countryList", SqlDbType.Structured)
prm.Direction = ParameterDirection.Input
prm.Value = tbl
I hope that this can give you some idea, and that my translation from C# to VB.NET is correct...

Concurrency check when updating using GridView

With this SqlDataSource, How can i be sure that the data I'm going to update is not modified in the meantime when i fetched data and when i'm about to make the update.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ChartDatabaseConnectionString %>"
SelectCommand="SELECT * FROM [Student]"
UpdateCommand="UPDATE [Student] SET [StudentName] = #StudentName, [DOB] = #DOB, [Age] = #Age, [Course] = #Course, [City] = #City, [MobileNo] =
#MobileNo WHERE [StudentID] = #StudentID">
Is there any GridView method Or Any Parameter I can use ?
There is a propery on SqlDataSource named ConflictDetection. Setting that property to CompareAllValues may do the trick for you.

not being able to display the current user details using sql in vb.net

I have used an sql statement where I want to display the details of the current user that is logged in. But when I run this command it
ConnectionString = "<%$ ConnectionStrings:Details %>"
SelectCommand = "SELECT * FROM member WHERE username = 'User.Identity.Name'"
it does not show any details but when I run
SelectCommand = "SELECT * FROM member WHERE username = 'david'"
the username david exists in the database and displays the details of only david in the web form. I even did Response.Write on the User.Identity.Name and that statement displays the current user that is logged in the page.
The issue is you're passing the actual User.Identity.Name as string instead of its value.
SelectCommand = String.Format("SELECT * FROM member WHERE username = '{0}'", User.Identity.Name)
But the better (and safer) practice would be something like
SelectCommand = "SELECT * FROM member WHERE username = #UserName"
SelectCommand.Parameters.AddWithValue("#UserName", User.Identity.Name)
This will prevent SQL injection.
EDIT:
Since you are defining this in your page, you can use the following template:
<asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:Details %>" SelectCommand="SELECT * FROM members WHERE ([username] = #UserName)">
<SelectParameters>
<asp:Parameter Name="UserName" Type="String" DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>
Then set the default value to User.Identity.Name on the server side:
SqlDataSource1.SelectParameters.Item(0).DefaultValue = User.Identity.Name
The easier way to do this is by using the Configure Data Source wizard, which is available by clicking the right arrow beside the SqlDataSource object in design view.

How do I get the SQL Where clause to handle TWO StringVariables?

I pass TWO StringQueries to new page: /Find.aspx?Color=Blue&Shape=Round
In my Products.aspx I have a GridView with a SelectCommand:
SelectCommand="SELECT DISTINCT [Name], [Price], [ProductNo]
FROM [MSD_Store] WHERE ([Color] = ?)"
How do I get the Where clause to handle TWO StringVariables?
Just add necessary part of the SQL query and define another query string parameter:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
SelectCommand="SELECT DISTINCT [Name], [Price], [ProductNo] FROM [MSD_Store] WHERE ([Color] = ?) AND ([Shape] = ?)">
<SelectParameters>
<asp:QueryStringParameter QueryStringField="Color" Name="color" />
<asp:QueryStringParameter QueryStringField="Shape" Name="shape" />
</SelectParameters>
</asp:SqlDataSource>
Simply doing
SelectCommand: SelectCommand="SELECT DISTINCT [Name], [Price], [ProductNo] FROM [MSD_Store] WHERE ([Color] = ? AND [Shape = ?])
and then you add another parameter definition, reading your querystring value
Do you mean this
SELECT DISTINCT [Name], [Price], [ProductNo]
FROM [MSD_Store] WHERE ([Color] = ?) AND ([Shape] = ?)
by "two" string variables?

How to get session value into an ASP Parameter tag?

I have following code
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
UpdateCommand="UPDATE [gMeter] SET ... [userId] = #userId ...
I need to parametr #userId assign session variable Session["userId"], any ideas? I tried
[userId] = <%= Session["userId"]%>
But it does not works.
Try this inside your asp:SqlDataSource
<asp:SessionParameter Name="userId" SessionField="userId" Type="Int32" />

Resources