Select statement not working properly in SqlCommand - c#

I'm using the below code to create an sql data grid on a web page in an ASP.Net web application.
private void BindGrid()
{
string strConnString = "server= N-1077; Trusted_Connection=yes; database=Slaughter; connection timeout=30";
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("SELECT WeekEndingDate = CONVERT(date, Week_Ending_Date, 103), Week_Number, North_Island, South_Island FROM Slaughter ORDER BY WeekEndingDate DESC"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
I'm not sure why but when I call the select statement - "SELECT WeekEndingDate = CONVERT(date, Week_Ending_Date, 103), Week_Number, North_Island, South_Island FROM Slaughter ORDER BY WeekEndingDate DESC" - the WeekEndingDate still shows up on the web page with the datetime.
If I run the same command in Sql Server it does it correctly.
So what am I doing wrong here? Here is the html side of things just in case that is the problem.
<div style="width: 1250px; height: 300px; overflow: auto">
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#6699ff" HeaderStyle-ForeColor="Black" RowStyle-BackColor="#ccffff" AlternatingRowStyle-BackColor="White"
AlternatingRowStyle-ForeColor="#000" runat="server" AutoGenerateColumns ="false" AllowPaging="false" OnPageIndexChanging="OnPageIndexChanging" AllowSorting="True">
<Columns>
<asp:BoundField DataField ="WeekEndingDate" HeaderText="Week Ending Date" ItemStyle-Width="150px" />
<asp:BoundField DataField ="Week_Number" HeaderText="Week Number" ItemStyle-Width="150px" />
<asp:BoundField DataField ="North_Island" HeaderText="North Island" ItemStyle-Width="150px" />
<asp:BoundField DataField ="South_Island" HeaderText="South Island" ItemStyle-Width="150px" />
</Columns>
</asp:GridView>
</div>

This will format date:
<asp:BoundField DataField ="WeekEndingDate" HeaderText="Week Ending Date" ItemStyle-Width="150px" dataformatstring="{0:MM-dd-yyyy}"/>

CONVERT(date, Week_Ending_Date, 103) converts the value of Week_Ending_Date to a date datatype in the returned dataset. .NET receives that as a DateTime and the default string format of a DateTime includes the time value. That's why your web page has the time displayed. If you do not want the time displayed, convert the value to a string either in your SQL: CONVERT(nvarchar(10), Week_Ending_Date, 103) or in your ASP tag: dateformatstring="{0:d}" or dateformatstring="{0:dd-MM-yyyy}" if your current culture settings don't give you the format you want with the first one.

Related

Select two dates simultaneously in a Textbox that uses TextMode"Date"

I have a textbox that is used to filter data shown on a gridview. The Textbox is using TextMode="Date" so that when clicked, a mini calander is shown for the user to select a date and load the gridview accordingly.
<asp:TextBox ID="txtTime" runat="server" Width="100px" TextMode="Date" OnTextChanged="txtTime_TextChanged" AutoPostBack="True"></asp:TextBox>
The selected date is put in lblTIME and that label is used in an SQL statement to filter the gridview.
SqlCommand cmdSQL = new SqlCommand("SELECT * FROM Schedule.dbo WHERE Date = '" + lblTIME.Text + "'
ORDERY BY ASC");
GvSchedule.DataSource = MyRstP(cmdSQL);
GvSchedule.DataBind();
Is it possible for the user to select two dates from the calandar simulaneously? To be more specific: I want the user to select a day and then the following day is automatically selected as well and sent to a seperate label (ex. lblTomorrow). I believe the SQL Statement would look like this:
SqlCommand cmdSQL = new SqlCommand("SELECT * FROM Schedule.dbo WHERE Date = '" + lblTIME.Text + "'
AND '" + lblTomorrow.Text + "' ORDERY BY ASC");
GvSchedule.DataSource = MyRstP(cmdSQL);
GvSchedule.DataBind();
Ok, so I would for "easy" just set the 2nd date box to "always" the same date as the first box.
So, a user might select any old date, but then the 2nd box will default as same. That way they can easy select a single date, but if they need to change the 2nd date box, at least it will be "starting" from the same date.
So, we only need a "wee bit" of js code to make that 2nd date box follow the first (but, one is free to THEN change the 2nd date to whatever they want).
So, say this markup above the grid view (our results).
<div style="float: left">
<h3>Hotel Bookings</h3>
</div>
<div style="float: left; margin-left: 25px">
<h4>Start Date</h4>
<asp:TextBox ID="dtStart" runat="server" TextMode="Date" ClientIDMode="Static"
onchange="mychange()"></asp:TextBox>
</div>
<script>
function mychange() {
dtStart = $('#dtStart').val()
$('#dtEnd').val(dtStart)
}
</script>
<div style="float: left; margin-left: 20px">
<h4>End Date</h4>
<asp:TextBox ID="dtEnd" runat="server" TextMode="Date" ClientIDMode="Static" >
</asp:TextBox>
</div>
<div style="float: left; margin-left: 25px">
<br />
<asp:Button ID="cmdSearch" runat="server"
Text="Search" OnClick="cmdSearch_Click" CssClass="btn" />
</div>
<div style="clear:both"></div>
<br />
<br />
Ok, and right below above follows say our grid view results:
<asp:GridView ID="GridView1" runat="server" CssClass="table table-hover"
DataKeyNames="ID" AutoGenerateColumns="false" Width="60%">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Province" HeaderText="Province" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="BookingDate" HeaderText="Booking Date"
ItemStyle-Width="110px" DataFormatString="{0:MM/dd/yyyy}" />
</Columns>
</asp:GridView>
And now all we need is the code for the "search" button, say this:
protected void cmdSearch_Click(object sender, EventArgs e)
{
String strSQL
= #"SELECT * FROM tblHotelsA
WHERE BookingDate BETWEEN #dtStart AND #dtEnd
ORDER BY HotelName";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#dtStart", SqlDbType.Date).Value = dtStart.Text;
cmdSQL.Parameters.Add("#dtEnd", SqlDbType.Date).Value = dtEnd.Text;
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And now we get/see this:
Edit: user wants only/just next day
Ok, well, this might be a leap year (feb 28 or 29), or this might be the last day of the year, so to jump/add to next date, we need (should) use a date type.
So, this code will work:
<script>
function mychange() {
dtStart = new Date($('#dtStart').val())
dtEnd = dtStart
dtEnd.setDate(dtEnd.getDate() + 1)
$('#dtEnd').val(dtEnd.toISOString().split('T')[0])
}
</script>
And if you don't want the user to see (or change) the 2nd value, then just hide it with style
eg this:
<asp:TextBox ID="dtEnd" runat="server" TextMode="Date" ClientIDMode="Static"
style="display:none"
>
</asp:TextBox>
that way, user don't see it, but the post code can thus continue to work "as is"

How to display 2 numbers after decimal in Web Page grid view in ASPX Web Forms?

This is the table I have created:
CREATE TABLE Product
(ID INTEGER IDENTITY(1,1) NOT NULL ,
Product_No AS RIGHT ('PDT0000' + CAST(ID AS VARCHAR(10)),10) PERSISTED PRIMARY KEY CLUSTERED,
Product_Image VARBINARY (MAX) NOT NULL,
Product_Name VARCHAR(50) NOT NULL,
Product_Category_No INTEGER NOT NULL FOREIGN KEY REFERENCES Product_Category(Product_Category_No),
Product_Price MONEY NOT NULL,
Product_Quantity INTEGER NOT NULL,
Grocery_Branch_No INTEGER NOT NULL FOREIGN KEY REFERENCES Grocery_Branch(Grocery_Branch_No)
)
When I insert a value like 10.50 or 100.45 or 11.05 in Product_Price column and then run SELECT * FROM Product in both SQL Server and Visual Studio, the Product_Price column value gets displayed as 10.50 or 100.45 or 11.05.
However, when I see the result of SELECT * FROM Product in a gridview from aspx page, then it shows 10.5000 or 100.4500 or 11.0500.
In other words, the results for Product_Price column value in SQL Server and Visual Studio is showing 2 numbers after the decimal (because in INSERT Statement I have added 2 numbers after decimal).
But, while running the aspx page, in the Product_Price column value in Grid View, it is showing 4 numbers after the decimal.
I made sure to add the Regular Expression Validator for Product_Price column in AddProducts.aspx
p>
Price:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="TextBox2" ErrorMessage="This field is required"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator7" runat="server" ControlToValidate="TextBox2" ErrorMessage="After decimal only 2 numbers" ValidationExpression="^\d{1,9}\.\d{1,2}$"></asp:RegularExpressionValidator>
</p>
Then this is what I have done in my AddProducts.cs
Stream stream = postedfile.InputStream;
BinaryReader binaryreader = new BinaryReader(stream);
byte[] bytes = binaryreader.ReadBytes((int)stream.Length);
string branch = Session["BranchAdmin"].ToString();
string CS;
CS = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand("AddProducts", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
cmd.Parameters.AddWithValue("#ProductImage", FileUpload1.FileBytes);
cmd.Parameters.AddWithValue("#ProductName", TextBox1.Text);
cmd.Parameters.AddWithValue("#ProductCategoryName", DropDownList1.SelectedValue);
cmd.Parameters.AddWithValue("#ProductPrice", TextBox2.Text);
cmd.Parameters.AddWithValue("#ProductQuantity", TextBox3.Text);
cmd.Parameters.AddWithValue("#GroceryBranchName", branch);
cmd.ExecuteNonQuery();
con.Close();
MessageBox("New Product has been added");
Then this is what I have done in ViewProducts.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" HorizontalAlign="Center">
<Columns>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="100px" Width="150px"
ImageUrl='<%#"data:Image/png/jpg/jpeg/gif/bmp;base64," + Convert.ToBase64String((byte[])Eval("Product_Image")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Product_Name" HeaderText="Product" />
<asp:BoundField DataField="Product_Category_Name" HeaderText="Category" />
<asp:BoundField DataField="Product_Price" HeaderText="Price" DataFormatString="{0} AUD" />
<asp:BoundField DataField="Product_Quantity" HeaderText="Quantity" />
<asp:BoundField DataField="Grocery_Branch_Name" HeaderText="Branch" />
</Columns>
</asp:GridView>
And this is what I have done in ViewProducts.cs
private void DisplayProducts()
{
string CS;
CS = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand("ViewProducts", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
I still could not figure out why the ViewProducts.aspx page is showing 4 numbers after the decimal for Product_Price column value in Grid View.
It would be helpful if the recommended syntax solution is provided to display 2 numbers after the decimal for Product_Price column value in Grid View.
This code should work:
<asp:BoundField DataField="Product_Price" HeaderText="Price" DataFormatString="{0:0.00} AUD" />

Populate ASP DataGrid With Fields With Spaces

I have a SQL Server table that has fields with spaces in it. I am attempting to populate an asp datagrid with this information, but on the Bind() event I keep getting an error of
Additional information: A field or property with the name '[Field With Space]' was not found on the selected data source.
I know the field is properly named as if I run it in SSMS it executes properly. Below is my HTML and my C# - what is set-up incorrectly?
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["LSTMain"].ConnectionString))
{
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT [Field With Space] FROM [Inventory Log] order by ID ASC", cn);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
cn.Close();
}
<div id="dgv">
<asp:GridView ID="GridView1" runat="server" CssClass="Grid" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="[Field With Space]" HeaderText="SQL Field With Spaces" />
</Columns>
</asp:GridView>
you can use the datareader dr.GetString(0)

Updating Database with sessions not working C# SQL

So my code brings across the searched for userID of a lecturer and the ModuleID previously selected by the user. However it breaks on this line;
myCommand.ExecuteNonQuery();
The error is;
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near '('.
I don't know why it does it but I can see that my stuff is being pulled across when I use a break point.
Front end code:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
SelectCommand="SELECT Lecturer_Records.UserID, Lecturer_Records.FirstName, Lecturer_Records.Surname, Lecturer_Records.PhoneNumber, Users.Email
FROM Lecturer_Records
INNER JOIN Users ON Lecturer_Records.UserID = Users.UserID
WHERE (Users.Email = #email)">
<SelectParameters>
<asp:QueryStringParameter Name="email" QueryStringField="searchlects" />
<asp:SessionParameter Name="ModuleID" SessionField="ModuleID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="SearchResult" runat="server" AutoGenerateColumns="False" AutoGenerateSelectButton="True" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="SearchResult_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="Surname" HeaderText="Surname" SortExpression="Surname" />
<asp:BoundField DataField="PhoneNumber" HeaderText="PhoneNumber" SortExpression="PhoneNumber" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
</Columns>
</asp:GridView>
And my C# code
protected void SearchResult_SelectedIndexChanged(object sender, EventArgs e)
{
// open new connection
SqlConnection connection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
connection1.Open();
string SearchUser = SearchResult.SelectedRow.Cells[1].Text;
string Module = (string)Session["ModuleID"];
SqlCommand myCommand = new SqlCommand("UPDATE [Modules] SET (UserID = '" + SearchUser + "') WHERE (ModuleID = '" + Module + "')", connection1);
myCommand.ExecuteNonQuery();
// move on to home page
Response.Redirect("APMDefault.aspx");
}
You don't need any ( or ) in your command. They breaks your sql syntax. Just delete them.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Based on your column names, they seems as a numerical types. That means, you might need to delete single quotes as well. If you use prepared statements, you will not need this of course.
And use using statement to dispose your connection and command.
using(var connection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
using(var myCommand = connection1.CreateCommand())
{
myCommand.CommandText = #"UPDATE Modules SET UserID = #userid
WHERE ModuleID = #moduleid";
myCommand.Parameters.Add("#userid", SqlDbType.NVarChar).Value = SearchUser;
myCommand.Parameters.Add("#moduleid", SqlDbType.NVarChar).Value = Module;
// I assumed your column types are nvarchar
connection1.Open();
myCommand.ExecutenonQuery();
// move on to home page
Response.Redirect("APMDefault.aspx");
}
But really, those columns are seem as numerical types. Either you can their type or change their name that points their types as character.

Appending LINQ to exist datasource/gridview in C#

I have the following in my .aspx page:
<asp:GridView ID="Table1" runat="server" AutoGenerateColumns="False" BorderColor="Black" OnRowCreated="Table1_RowCreated" OnRowDataBound="Table1_RowDataBound" CellPadding="3" CellSpacing="0" DataSourceID="Table1DataSrc" DataKeyNames="Field1">
<Columns>
<asp:BoundField DataField="Field1" HeaderText="Field1" SortExpression="Field1">
<ItemStyle HorizontalAlign="Left" Font-Size="8" Wrap="false" />
<HeaderStyle CssClass="header" Font-Size="8" />
</asp:BoundField>
</Columns>
</asp:GridView>
Where the gridview has a DataSource that loads a few fields. In my C# code behind, I have the following function which runs a LINQ query to process a stored procedure (on a different server than my other datasource)
private void RenderTables()
{
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("sp_special", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#AmIY", "Y");
adapter.SelectCommand = cmd;
adapter.Fill(dt);
adapter.Dispose();
conn.Close();
}
var enumvar = dt.AsEnumerable();
var query = from x in enumvar
orderby x.Field<string>(3)
select new
{
Field3 = x.Field<string>(3),
Field4 = x.Field<int>(4),
};
//I do some data manipulation using LINQ, but omitted here
//do something with query.....
}
How would I add new columns Field3 and Field4 to my Gridview and bind these new records? I do not want to store anything in temp tables on either servers
it will work like this...
<asp:BoundField DataField="Field3" HeaderText="Field3" SortExpression="Field3">
<asp:BoundField DataField="Field4" HeaderText="Field4" SortExpression="Field4">

Categories

Resources