ASP.NET SqlDataSource set SessionParameter programmatically - asp.net

I have a StoredProcedure called "usp_posts_getall" and it has 1 parameter called "#thisCategoryID"
in my "thisCategoryID", any values other than 0(zero) will return all the records in my Posts table.
Now I have a category menu items and each time I select, I set the value in my Session name called "SelectedCID".
So, How do I ...
Create a SessionParameter Programmatically in SqlDataSource?
UPDATE:
ok. I got it working now.

If it's a session parameter that's used by the SqlDataSource, then you can set the value in the session, e.g in Page_Load():
Session["thisCategoryID"] = theCategoryId;
(am I misunderstanding the question?)
Ok, update:
I think you can create an event handler for the SqlDataSource.OnSelecting event. In that handler, you can access the Parameters collection of the datasource and can add another Parameter to it. I currently cannot test the following code, so it might not be fully correct, but I hope you see the idea:
SqlDataSource1_OnSelecting(SqlDataSourceSelectingEventArgs args)
{
var param = new Parameter("#thisCatagoryID");
param.DefaultValue = Session["SelectedCID"];
SqlDataSource1.SelectParameters.Add(param);
}
Alternatively, you can set the parameter declaratively in the markup, e.g:
<asp:SqlDataSource ...>
<SelectParameters>
<asp:SessionParameter Name="thisCategoryID" SessionField="SelectedCID"
DefaultValue="0" />
...
</SelectParameters>
</asp:SqlDataSource>

Related

How can I populate an Asp.net dropdown using a sqldatasource which has the connectionstring bound at runtime?

So, I've been fighting with this for more time than I'd like to admit, and can't seem to find info on what I'm doing wrong. So, humbly, I submit this question.
I have 2 dropdowns and datasources as defined here:
<asp:DropDownList ID="ddAdminYear" runat="server" enabled="false" DataTextField="YEAR_ID" DataValueField="YEAR_ID" AutoPostBack="True" AppendDataBoundItems="true">
<asp:ListItem Text="----------" Value="----------" /></asp:DropDownList>
<asp:SqlDataSource ID="sdsAdminDistinctYr" runat="server"
ProviderName="System.Data.SqlClient" SelectCommand="SELECT DISTINCT YEAR_ID FROM PC_YEAR ORDER BY YEAR_ID" DataSourceMode="DataReader"></asp:SqlDataSource>
<asp:DropDownList ID="tbOneUnit" runat="server" AutoPostBack="True"
DataTextField="LONG_DESC" DataValueField="SHORT_DESC_EN" AppendDataBoundItems="True" Enabled="True">
<asp:ListItem Text="----------" Value="----------" /></asp:DropDownList>
<asp:SqlDataSource ID="sdsAdminMunic" runat="server" Onselecting="eventselect" ProviderName="System.Data.SqlClient" SelectCommand="GET_MUNIC_LISTING_VB" SelectCommandType="StoredProcedure" >
<SelectParameters>
<asp:controlparameter DefaultValue="2017" Name="year" controlid="ddAdminYear" propertyname="SelectedValue"/>
<asp:Parameter DefaultValue="default" Name="region" Type="String"/>
<asp:Parameter DefaultValue="default" Name="u_r" Type="String"/>
<asp:Parameter DefaultValue="default" Name="UserGroup" Type="String"/>
</SelectParameters>
</asp:SqlDataSource>
The connectionString for sdsAdminDistinctYr is set when the page loads. The code that runs looks like this:
sdsAdminDistinctYr.ConnectionString = _user.SelectedDBConn
ddAdminYear.DataSourceID = "sdsAdminDistinctYr"
Then, in the select event handler for ddAdminYear, I set the datasource for tbOneUnit as follows:
sdsAdminMunic.ConnectionString = _user.SelectedDBConn
tbOneUnit.DataSourceID = "sdsAdminMunic"
tbOneUnit.DataBind()
The ddAdminYear dropdown populates, however, the tbOneUnit dropdown does not.
How can I get the tbOneUnit dropdown to populate using a stored procedure based on the ddAdminYear value?
EDIT:
I can't post the stored procedure itself, but here's the header:
[dbo].[GET_MUNIC_LISTING_VB] (
#YEAR smallint,
#REGION as varchar(5) = NULL,
#U_R as varchar(2) = NULL,
#USERGROUP as varchar(10) = NULL)
I can verify it returns data.
Let me know if anything else would be helpful.
Edit #2:
The stored procedure is running, but the "default" values are being passed as strings (which I had specified)... So, that's not what I want to do.
Right now the application will pass something like :
exec GET_MUNIC_LISTING_VB #year=N'2017',#region=N'default,N'#u_r=N'default',#UserGroup=N'default'
To the application, whereas I'd like it to pass:
exec GET_MUNIC_LISTING_VB #year=N'2017',#region=default,#u_r=default,#UserGroup=default
I would approach the problem one of two ways depending on how much data you will need for all possible combinations of data for the two drop downs.
If you have a limited number of values for ddAdminYear I would create a tbOneUnit for each value, then I would dynamically show or hide each of these drop downs based on the selected value using some javascript. You would need to create a foreach loop and unique Id or some other identifier so that you could identify each unique drop down.
$(document).ready(function() {
$('#ddAdminYear').change(function() {
var adminYear = $(this).val();
$('.tbOneUnit').hide();
$('#tbOneUnit_' + adminYear).show();
});
});
If you have too much data for solution above, then another solution would be to create an ajax event every time the ddAdminYear changed, and use that to populate the data for tbOneUnit. This of course would require you to write a method on from the server that would return the correct data for tbOneUnit based on the current value of ddAdminYear.
$(document).ready(function() {
$('#ddAdminYear').change(function() {
var adminYear = $(this).val();
var get = $.ajax('/GetTbData', adminYear);
get.done(function(data) {
// take data and add to drop down here
});
});
});
So, it looks like my issue is that I was specifying parameters for executing a stored procedure, when I wanted to use the defaults defined in the stored procedure.
I was able to fix this by commenting out the parameters I had specified, leaving only the ddAdminYear controlParameter. This produced the following code RPC:
exec GET_MUNIC_LISTING_VB #year=N'2017'
Thanks to everyone who posted, and put in an effort.

Repeater in ASP.NET - Trying to connect it with a datasource that calls a SP on SelectCommand, getting multiple errors

I have a stored procedure to list items on my database that receives the 'user_mail' parameter. I want to display the results on a repeater but the combination of declaring a parameter and the loop nature of the repeater is causing me problems.
See I have the following code:
<asp:SqlDataSource ID="SqlLogList" runat="server" ConnectionString="<%$ ConnectionStrings:LocalSqlServer %>"
SelectCommand="ws_log_list">
<SelectParameters>
<asp:Parameter Name="user_mail" DefaultValue="ALL" />
</SelectParameters>
</asp:SqlDataSource>
On code behind if I use the following code, clearing the parameters,I get an error saying there's a parameter that needs to be declared. If I remove the .Clear() I get an error saying the parameter user_mail is being declared multiple times!
SqlLogList.SelectParameters.Clear();
SqlLogList.SelectParameters.Add("user_mail", "bomb#cryo.com.br");
repeater.DataSource = SqlLogList;
repeater.DataBind();
Then don't add it again... just set it:
SqlLogList.SelectParameters.Clear();
SqlLogList.SelectParameters["user_mail"].Value = "bomb#cryo.com.br");
repeater.DataSource = SqlLogList;
repeater.DataBind();
Your syntex is wrong, missing # for parameter name. It should be:
SqlLogList.SelectParameters.Add("#user_mail", "bomb#cryo.com.br");

ASP Master pages: How to pass a value from a child page to a SqlDataSource parameter on a master page

Here's a puzzle. A datasource on a master page refers for its SelectParameter to a label control containing some text on a (grand)child page:
<asp:SqlDataSource ... SelectCommand="SELECT * FROM [tblMyTable] WHERE (([strField] = ?) ">
<SelectParameters>
<asp:ControlParameter Name="strField" ControlID="cphMaster$cphChild$lblGrandchild" propertyname="Text" DbType="String"/>
</SelectParameters>
</asp:SqlDataSource>
but this generates an error ("System.Data.OleDb.OleDbException: Data type mismatch in criteria expression.")
I've checked the obvious (strField really is a string, the ContentPlaceHolder (cph) controls are correctly identified by their IDs). Any ideas?
And is my basic approach of 'ControlParameter reading a control placed in a ContentPlaceholder(s)' a reasonable way of passing a value into a SelectParameter?
I will suggest you to create a public property with type SQLDataSource on your master page class that can be accessed to your child page.
YourMasterPage.vb (class name of master page is YourMasterPage)
Private _mastersqldatasource as SqlDataSource
Public ReadOnly Property MasterSQLDataSource() As SqlDataSource
Get
Return SqlDataSource1
End Get
End Property
Then you can access it to your child page
dim myMasterPage as YourMasterPage
myMasterPage = DirectCast(Me.Page.Master, YourMasterPage)
myMasterPage.MasterSQLDataSource.SelectParameters("strField").DefaultValue = lblGrandChild.Text
Hope this helps, I used to use this way for your case
You can use following code in your child page .cs file .
SqlDataSource ds = this.MasterPage.FindControl("datasourceid");
// now you can custimize this ds according to your problem
It turns out that my method is fine. In my real application I had several criteria, and the problem was that the SelectParameters were not in the same order as the criteria in the WHERE clause. When the order is the same, the method works.
So:
SELECT * FROM [myTable] WHERE [FieldA] = ? AND [FieldB] = ? AND [FieldC] = ?
needs:
<SelectParameters>
<asp:ControlParameter Name="FieldA" ControlID="cphMaster$cphChild$lblGrandChildA .../>
<asp:ControlParameter Name="FieldB" ControlID="cphMaster$cphChild$lblGrandChildB .../>
<asp:ControlParameter Name="FieldC" ControlID="cphMaster$cphChild$lblGrandChildC .../>
</SelectParameters>
ie, not ACB, etc. I've never before come across this behaviour, which may arise from the master/child(/grandchild) structure. Hope this helps others.
Congratulation it seems you able to fix the issue. If you allow your users to use some various browsers (e.g: IE, Firefox, Chrome, Safari).
You might need to check whether cphMaster$cphChild$lblGrandChildA is the same generate ID for your control, in some browser it will rendered as cphMaster_cphChild_lblGrandChildA with underscore, but if you only allow your user to use only one browser, then it will not be an issue.

method invoked when a gridview records from database are null

I have a gridview which uses a stored procedure with session["UserName"] as a parameter to retrieve the records from the database.
Here is the code for that gridview Sqldatasource:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:componentConnString %>"
SelectCommand="SelectUserPreviousHistory" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:SessionParameter Name="userName" SessionField="UserName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
lets say a particular user who has logged in doesn't have any records in that table on which this particular stored procedure is being executed. Then there won't be any records associated with gridview. So in this scenario: is there any method that gets executed or some exception is thrown, so that i can explicitly use that method/exception/property to display a message Label to the user like "No records to show !!"
please help me
BTW i'm using vs 2008, c#, asp.net
Thanks in anticipation
Greetings
Well if i got you right you need to display a text to the user tell them no data found or something
so you can use a property on the grid view called
EmptyDataText = "no Data Found !"
Set it on the HTML like this for example
<asp:GridView ID="myGridView" EmptyDataText="No Data Found !" runat="server" >
</asp:GridView>
Also to set the style of that region of the Empty Data Text Field or div if you play with Visual studio intellsince you can find such like
EmptyDataRowStyle-CssClass
and others too
Please don't forget to sign this answer is correct if its useful to you :)
Regards :)
Handle the Selected event of the SQLDataSource to check the number of records returned. For example:
protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e) {
if(e.AffectedRows == 0)
ClientScript.RegisterStartupScript(typeof(Page), "startUp", "alert(recordset is empty);", true);
}
Well my friend i found a solution but its a server side one when binding the grid or after exactly binding it do the following
//---- just an examply for binding grid with 0 rows [no data found]
myGridView.DataSource = null;
myGridView.DataBind();
//----
myGridView.BorderWidth = ((myGridView.Rows.Count <= 0) ? (new Unit(0)) : (new Unit(1)));
Thanks for your waiting :)

FormView ConvertEmptyStringToNull and binding

I'm using a FormView with an ObjectDataSource and binding using <%# Bind("WhateverProp") %> - and all of my nullable columns are coming back with default values of the type in them.
It appears that the FormView object doesn't have a ConvertEmtpyStringToNull property like the other binding containers do. I've found articles suggesting that this was a bug in VS 2005 / .Net 2.0 - but don't see any saying what the resolution was.
Does anyone have any suggestions as to how I can work around this without just re-capturing all of the fields in the ODS_Inserting event? I'd rather not have to write code to re-bind all of my bound fields on the form just to test for nulls.
Struggled with it too.
For a dropdownlist, I do that:
AppendDataBoundItems="true"
<asp:ListItem Text="" Value=""></asp:ListItem>
For my ObjectDataSource, even thoug my UpdateMethod takes a single parameter, the entity, I add Update params for each Nullable Field of the Entity with convert to NULL
<UpdateParameters>
<asp:Parameter Name="No_Empl_Ferme" Type="Int32" ConvertEmptyStringToNull="true" />
</UpdateParameters>
I do the same for the Insert.
Works fine.
I ended up doing this - kind of a shotgun approach, but in this case all of my empty string values should be nulls. I've also considered using a string array in the code to specify which values should be nulled - and then could just loop thru the string array instead of over all of the values.
protected void RequestItemFormView_ItemInserting(object sender, FormViewInsertEventArgs e)
{
for (int i = 0; i < e.Values.Count - 1; i++)
{
if (e.Values[i].ToString() == string.Empty)
{
e.Values[i] = null;
}
}
}
In your Object DataSource, you need to add InsertParameters for each of your nullable type with the Attribute ConvertEmtpyStringToNull="True" :
<InsertParameters>
<asp:Parameter Name="NullableFieldName" Type="Int32" ConvertEmptyStringToNull="true" />
</InsertParameters>
Quote:
Tonio - i'm not using individual params, but DataObjectTypeName instead. My insert method takes a single param, and that's the business object that I want to have saved back to the database. – Scott Ivey May 1 at 12:57
I've fixed it like this:
protected void FormViewSettings_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
OrderedDictionary values = e.NewValues as OrderedDictionary;
var personID = values["PersonID"];
if (string.IsNullOrEmpty(personID.ToString()))
{
values.Remove("PersonID");
values.Add("PersonID", null);
}
}
It's a little hack but it works fine.
This way you can set the object property to null instead of string.empty without using the ConvertEmptyStringToNull setting.

Resources