How dropdownlist bind with slqdatasource retrieve proper value? - c#

Well I want to retrieve the value from the dropdown list to write for my .cs. The sqldatasource returns either Saving Account or Current account depending on what kind of account type does he/she have.
<asp:DropDownList ID="ddlPayBy2" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource2" DataTextField="accountType"
DataValueField="accountType">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:Oakhorizons %>"
SelectCommand="SELECT [accountType] FROM [SavingAccount] WHERE ([custID] = #custID)">
<SelectParameters>
<asp:SessionParameter DefaultValue="OH00002" Name="custID"
SessionField="Session["custID"]" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Well it's been returning me nothing. I've tried this but nothing is returned. I always get the else statement and I tried to debug and it says SelectedValue = ""
if (ddlPayBy.SelectedValue == "Savings"){
account = "Savings";
}
else if (ddlPayBy.SelectedValue == "Current")
{
account = "Current";
}
else
{
Alert.Show("Please choose your account type properly");
}

i haven't used the sqldatasource object in awhile so forgive me, but are you missing something simple like not binding the control to the datasource object.
Perhaps your parameter isn't being set properly. Do you have access to SQL Profiler? Check and see if your query is running and running with the right query ...
also a side note ... this prob isn't it but your dropdown's id ="ddlPayBy2" but you're checking if (ddlPayBy.selected....

Related

SqlDataSource, 3rd dropdown in chain fails

Registration form
[This is working fine. I had wrong information to test with. I will leave up because it is the way to do cascading DDL's using SQLDataSource albeit outdated]
My primary language is C# but the application is in VB.Net. I have appointment application students sitting for individual and group portraits on college campuses. The registration page has three dropdown lists:
(1) college Campuses, (2) Organizations that belong to a particular Campus, and a (3) Classification schema that belongs to a particular Organization. The Campus and Organization dropdown lists work as expected. The Classification will display the class schema for the first organization on the initial load of the page but will not change after that. A class schema can be [Freshman, Sophomore, Junior, Senior] or [Undergradutre, Masters, Doctoral, Faculty]. There are other class schemas. There is one class schema per organization.
Running the configure on all Datasource components shows them functioning properly. That is the Classification Data Source shows varying schema depending on the organization parameter entered. Here is the set up:
<asp:SqlDataSource ID="CampusSource" runat="server" ConnectionString="<%$ ConnectionStrings:XXXConnectionString %>"
SelectCommand="spCampusSel" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
<asp:SqlDataSource ID="OrgSource" runat="server" ConnectionString="<%$ ConnectionStrings:XXXConnectionString %>"
SelectCommand="spOrgByCampusSel" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="CampusDDL" Name="ParentOrg_ID" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="ClassSource" runat="server" ConnectionString="<%$ ConnectionStrings:XXXConnectionString %>"
SelectCommand="spClassSchemaByOrgSel" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="OrgDDL" DefaultValue="" Name="OrgID" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:DropDownList ID="CampusDDL"
TabIndex="1"
DataSourceID="CampusSource"
DataValueField="Org_ID"
DataTextField="LongName"
AutoPostBack="True"
RunAt="server">
</asp:DropDownList>
<asp:DropDownList ID="OrgDLL"
TabIndex="2"
DataSourceID="OrgSource"
DataTextField="LongName"
DataValueField="Org_ID"
AutoPostBack="True"
RunAt="server">
</asp:DropDownList>
<asp:DropDownList ID="ClassDDL"
TabIndex="8"
DataSourceID="ClassSource"
DataValueField="Class"
DataTextField="Class"
AutoPostBack="False"
runat="server">
</asp:DropDownList>
According the Microsoft Docs, this is all I need. But I have also tried setting the ClassSource's parameter value in code at various palaces including the Selecting event. At least I could see that the OrgDDL has the correct organization values (the primary key of the organization). Thus the correct values were being supplied to the datasource.
Protected Sub DMS_Class_Selecting(ByVal sender As Object, ByVal e As SqlDataSourceSelectingEventArgs) Handles DMS_Class.Selecting
e.Command.Parameters(0).Value = OrgDDL.SelectedValue
End Sub
All SQLDataSources are set to DataSet mode. The Class Schema store procedure returns 1 column with each class on a row. Such as:
Freshman
Sophomore
Junior
Senior

The server tag is not well formed asp.net C#

I'm doing the following query, and trying to use a code that come from a previous query.
But is giving me the following error: The server tag is not well formed.
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:TesteConnectionString %>" SelectCommand="SELECT * FROM [Equipa] where idAssemb=1 and idDept=<%# Eval("idDept") %>"></asp:SqlDataSource>
I'm using C# in Web forms asp.net
Can somebody help me on this?
Eval is used in DataBound controls to evaluate a field value in a row from the data source. You are trying to use it inside a Data Source control itself (SQLDataSource in this case). You should use parameterized query by specifying the value of parameter inside SelectParameters tag like this:-
<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:TesteConnectionString %>"
SelectCommand="SELECT * FROM [Equipa] where idAssemb=1 AND idDept=#DeptId>
<SelectParameters>
<asp:ControlParameter ControlID="lblDeptId" Name="DeptId"
PropertyName="Text" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
Please note, here I have shown the example of a control present inside your WebForm. You can specify where the value of DeptId is coming from via Cookie, QueryString, Form, Session etc.

C# ASP.NET SQL Data Source

How would I use a SQL Data Source to return the value from the select statement into a variable?
<asp:SqlDataSource ID="sdsProfile" runat="server" ConnectionString="<%$ ConnectionStrings:MYDB %>" SelectCommand="SELECT * FROM [UserProfileInformation] WHERE ([UserID] = #UserID)" >
<SelectParameters>
<asp:Parameter Direction="Output" Name="Verified" Type="Int32" />
</SelectParameters>
I have a colum that is called Verified in the database that is a bit. It is either a 0 or a 1. This tells me if the user profile has been verified by the admin. Is there a way to take the return value from the select statement and put it into the Verified parameter? This way I can access that parameter value in the code behind and manipulate the page based on a 0 or a 1? Thanks!
I am pretty sure you cannot do it without code-behind. At least not the way you can respect yourself the next day.

How to pass a value into a SqlDataSource Query?

I'm creating a ListView in ASP.NET and have based mine on the example given by CodeProject here. I want to make the Select Command of the SqlDataSource dynamic so that a value is generated from one provided from the session. Ive tried a fue different possibilities, here is an example of what I want:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TestDatabaseConnectionString %>"
SelectCommand="SELECT * FROM [Contacts] WHERE [Name] = <%# Eval("value") %> " >
</asp:SqlDataSource>
How would I pass such a value using ASP? Ive also tried creating the query in the C# back page and linking to it like SelectCommand = "<%# Eval("Query") %>" and also by using the #value syntax. neither work!
This should do the trick. Define a SessionParameter as follows and make sure Name=Sql parameter name and SessionField is same as your session field. DBType and DefaultValue as required...
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
SelectCommandType="Text"
ConnectionString="<%$ ConnectionStrings:TestDatabaseConnectionString %>"
SelectCommand="SELECT * FROM [Contacts] WHERE [Name] = #ParaName"
<SelectParameters>
<asp:SessionParameter
Name="ParaName"
SessionField="YourSessionFieldName"
DbType="String"
DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>
Replace with
SelectCommand="SELECT * FROM [Contacts] WHERE [Name] = #Name"
And define your #Name as parameter
<SelectParameters>
<asp:Parameter DefaultValue="<%# Eval("Query") %>" Name="Name" DbType="..." />
</SelectParameters>
The solutions provided are very good. It should also be noted that trying to place your "value" directly in the query, you are opening yourself up to SQL injection attacks. Using the select parameters prevents and protects you from this.
I had the same issue and my lazy approach to solving it was to do as follows:
command.CommandText = item.Query.Replace("#Value", Value);
command.ExecuteNonQuery();
Dirty, easy and most likely not the proper way to do it.
I would really recommend against using a SqlDataSource control. A SqlDataSource provides very little in the realm is reuse.
Programatically make the DB call
If you make the call in a separate class (or even better in a DAL) you will be able to use it across multiple pages with ease. Also, when a change occurs to your query you will just have to change it in one place.
Here is a sample below that uses the Entity Framework to access the database
Mark up
<asp:DropDownList ID="ddlTest" runat="server"></asp>
Code Behind
public List<Record> GetAllRecordsByUserName(string credentials)
{
List<Record> recordList;
using (CustomEntities context = new CustomEntities())
{
IQueryable<Record> recordQuery = from records in context.Records
where records.UserName == credentials
select records;
recordList = recordQuery.ToList<Record>();
}
return recordList;
}
public void ValidateAndBind(string username)
{
List<Record> recordList = GetAllRecordsByUserName(username);
// Do validation here
ddlTest.DataSource = recordList;
ddlTest.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
ValidateAndBind("test.username");
}
Another way to achieve your goal without code behind is using an Hidden Field and doing the following:
<asp:HiddenField runat="server" ID="HfieldID" Value='<%# Eval("value")%>'/>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestDatabaseConnectionString %>" SelectCommand="SELECT * FROM [Contacts] WHERE [Name] = #Name">
<SelectParameters>
<asp:ControlParameter Name="Name" PropertyName="Value" ControlID="HfieldID" DbType="String" />
</SelectParameters>
</asp:SqlDataSource>
Be sure to put this before any controls that will use this SqlDataSource.

Using Session data in SQL SELECT parameters

Okay, so I've got the follwing mark up:
Here I have a listbox that is to be populated by some SQL query.
<asp:ListBox ID="MyListBox" runat="server"
DataSourceID="MyDataSource" DataTextField="Field1" DataValueField="ID" ></asp:ListBox>
<asp:SqlDataSource ID="MyDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT [ID], [Field1] FROM [Table1] WHERE ([ID2] = #ID2)">
<SelectParameters>
<asp:SessionParameter Name="ID2"
SessionField="ID2" DbType="Guid"/>
</SelectParameters>
</asp:SqlDataSource>
A few problems that I have:
The list box always is empty and when I try and test the query, it always presents a dialogue box asking for me to input "Type" "DbType" and "Value". I'm not too sure what to pick here.
I've tried running the application, ensuring that there is the needed session data in the correct key. (Session["ID2"] has been given a Guid). However, when I get to the listbox, it's empty even though I can look at the table data and know what should be there.
I have solved this issue. Basically, I assumed that the query should return results when it rightly shouldn't have done. Additionally, the data in Field1 was an empty string. So when it did return results, I wouldn't see anything in the ListBox.

Categories