Calculating a T-SQL Query Parameter at Load Time - c#

I'm trying to SELECT records out of an Events Database (with an EventDate field as Date) that have a EventDate that is in the current month.
I have functions for calculating the first day of the month:
public string GetFirstofMonth(DateTime dt)
{
int thisMonth = dt.Month;
int thisYear = dt.Year;
string firstOfMonth = thisMonth.ToString() + "/1/" + thisYear.ToString();
return firstOfMonth;
}
and the last day of the month:
public string GetLastofMonth(DateTime dt)
{
DateTime Date2Obj = new DateTime(dt.Year, dt.Month, 1);
int thisMonth = dt.Month;
int thisYear = dt.Year;
Date2Obj.AddMonths(1);
Date2Obj.AddDays(-1);
int lastDay = Date2Obj.Day;
string LastOfMonth = thisMonth + "/" + lastDay + "/" + thisYear;
return LastOfMonth;
}
So in the MasterPage (or the instance, doesn't matter) I have this SQLDataSource:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MeetingsConnectionString %>"
SelectCommand="SELECT * FROM [Events] WHERE (([EventDate] >= #EventDate) AND ([EventDate] <= #EventDate2))">
<SelectParameters>
<asp:Parameter DbType="Date" Name="EventDate" />
<asp:Parameter DbType="Date" Name="EventDate2" />
</SelectParameters>
</asp:SqlDataSource>
How do I modify the EventDate and EventDate2 parameters in the SQLDataSource to use GetFirstofMonth(DateTime.Today); and GetLastofMonth(DateTime.Today), respectively, as their values? Or is this not possible?

This can be done by handling the SqlDataSource's "Selecting" event as follows:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" OnSelecting="SqlDataSource1_Selecting"
ConnectionString="<%$ ConnectionStrings:MeetingsConnectionString %>"
SelectCommand="SELECT * FROM [Events] WHERE [EventDate] BETWEEN #EventDate AND #EventDate2">
<SelectParameters>
<asp:Parameter Name="EventDate" />
<asp:Parameter Name="EventDate2" />
</SelectParameters>
</asp:SqlDataSource>
In your codebehind or in your inline code (where ever you have your functions defined) add this method:
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceEventArgs e)
{
e.Command.Parameters["#EventDate"].Value
= GetFirstofMonth(DateTime.Now); //replace with your date param
e.Command.Parameters["#EventDate2"].Value
= GetLastofMonth(DateTime.Now); //replace with your date param
}

One way to do this is to put hidden fields on your page, set the value of those fields in code-behind with the dates using your methods, then tie the data source parameters to the hidden fields.
Codebehind
public void Page_Load( ... )
{
...
EventDate.Value = GetFirstOfMonth( DateTime.Today );
EventDate2.Value = GetLastOfMonth( DateTime.Today );
...
}
Mark up
<asp:HiddenField runat="server" id="EventDate" />
<asp:HiddenField runat="server" id="EventDate2" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MeetingsConnectionString %>"
SelectCommand="SELECT * FROM [Events] WHERE (([EventDate] >= #EventDate) AND ([EventDate] <= #EventDate2))">
<SelectParameters>
<asp:ControlParameter DbType="Date" Name="EventDate" ControlID="EventDate" PropertyName="Value" />
<asp:ControlParameter DbType="Date" Name="EventDate2" ControlID="EventDate2" PropertyName="Value" />
</SelectParameters>
</asp:SqlDataSource>

I usually find it simpler to do this:
select * from Events where Month(EventDate) = Month(getdate())
If the month can be selected by the user, then you just substitute a parameter for the month number (returned from a selection list).
P.S. - If you want to do more complex summary analysis of your event data (counts per hour, day etc.) and you are using SQL Server 2005+ then the function described in this post might be useful.

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)"
}

Bind dropdownlist to SqlDataSource

I have 20 textboxes and a dropdownlist on my form.
I am using EditItemTemplate and a SqlDataSource for editing and inserting data.
I replaced a dropdownlist with a textbox and things didn't work. With the textbox, the form was working fine.
Initially, I had:
<asp:TextBox ID="IDTextBox" runat="server" Text='<%# Bind("EPMProjectUID") %>'/>
<asp:SqlDataSource ID="dsManageProject" runat="server"
SelectCommand="SELECT [EPMProjectUID] from Table"
UpdateCommand="UPDATE [Table] SET [EPMProjectUID] = #EPMProjectUID "
InsertCommand="Insert into [Table] values(EPMProjectUID)"
<SelectParameters>
<asp:Parameter Name="EPMScheduleUID" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="EPMScheduleUID" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="EPMScheduleUID" />
<InsertParameters>
</asp:SqlDataSource>
And the things were working,I use to get the data and update it and even store it.
But now, I want a dropdownlist here, so I added
<asp:DropDownList ID="UIDDropDownList" runat="server"></asp:DropDownList>
In the cs file, I wrote
DB db1 = new DB(Global.ConnStringName);
db1.QueryText = #"SELECT UID, ProjectName FROM Table ";
DataTable dt = db1.GetDataTable();
DropDownList ddlUID = (DropDownList)FormView1.FindControl("UIDDropDownList");
if (ddlUID != null)
{
ddlUID.DataSource = dt;
ddlUID.DataTextField = "ProjectName";
ddlUID.DataValueField = "UID";
ddlUID.DataBind();
}
And this helps me to load the data, but if I try to insert/update anything, it stores as null.

insert variable into db in c# code behind using sqldatasource

I wanted to insert a variable into a table in db using the SqlDataSource. Below is my code in aspx:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ACM_DBConnectionString %>"
DeleteCommand="DELETE FROM [ContestRelation] WHERE [relationid] = #relationid"
InsertCommand="INSERT INTO [ContestRelation] ([contestid]) VALUES (#contestid)"
SelectCommand="SELECT [relationid], [contestid] FROM [ContestRelation]"
UpdateCommand="UPDATE [ContestRelation] SET [contestid] = #contestid WHERE [relationid] = #relationid">
<DeleteParameters>
<asp:Parameter Name="relationid" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="contestid" Type="Int32" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="contestid" Type="Int32" />
<asp:Parameter Name="relationid" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
and the code behind:
protected void ConfirmContest_Click(object sender, EventArgs e)
{
try
{
foreach (GridItem item in RadGrid1.MasterTableView.Items)
{
GridDataItem dataitem = (GridDataItem)item;
TableCell cell = dataitem["selectContest"];
CheckBox checkBox = (CheckBox)cell.Controls[0];
if (checkBox.Checked)
{
string value = dataitem.GetDataKeyValue("contestid").ToString();
SqlDataSource1.InsertParameters.Add("contestid", value);
SqlDataSource1.Insert();
}
}
}
catch (Exception ex)
{
Response.Write("<script language='javascript'>alert('No data selected .');</script>");
}
}
The "value" variable is not inserted into the database table. Can anyone point me my mistakes? Thanks in advance.
Problem Solved!
I actually cannot add an existing insert parameter, instead, I change to following code
string value = dataitem.GetDataKeyValue("contestid").ToString();
SqlDataSource1.InsertParameters.Add("contestid", value);
SqlDataSource1.Insert();
to following code. And the problem is solved.
string value = dataitem.GetDataKeyValue("contestid").ToString();
SqlDataSource1.InsertParameters["contestid"].DefaultValue = value;
SqlDataSource1.Insert();

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 %>'"

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.

Categories

Resources