Update StoredProcedure executes but DB not updated - c#

I've searched around for a while and tried all the different solutions but I can't seem to get the database updated.
I've executed the stored procedure on its own through SSMS and it works fine.
Here's my asp settings:
<asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" UpdateCommand="spProofStamp" UpdateCommandType="StoredProcedure">
<UpdateParameters>
<asp:Parameter Name="sID" Type="String" />
<asp:Parameter Name="UserID" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
Button:
<dx:LayoutItem Caption="">
<LayoutItemNestedControlCollection>
<dx:LayoutItemNestedControlContainer ID="LayoutItemNestedControlContainer1" runat="server">
<dx:ASPxButton ID="ASPxFormLayout2_E2" OnClick="Button1_Click" runat="server" Text="Validate" AutoPostBack="false">
<ClientSideEvents Click="function(s,e){validate();}" />
</dx:ASPxButton>
</dx:LayoutItemNestedControlContainer>
</LayoutItemNestedControlCollection>
</dx:LayoutItem>
My code behind (I've tried databind and update separately as well).
I've also traced through the values and they're all there, how can I tell if the Update/DataBind works or not? Other Databinds within my code are working fine:
protected void Button1_Click(object sender, EventArgs e)
{
SqlDataSource5.UpdateCommandType = SqlDataSourceCommandType.StoredProcedure;
SqlDataSource5.UpdateCommand = "spProofStamp";
SqlDataSource5.UpdateParameters["sID"].DefaultValue = selectedValue;
SqlDataSource5.UpdateParameters["UserID"].DefaultValue = login.ToUpper();
SqlDataSource5.Update();
SqlDataSource5.DataBind();
}
StoredProcedure:
ALTER PROCEDURE [dbo].[spProofStamp]
#UserID nvarchar(15),
#sID nvarchar(15)
AS
SET NOCOUNT ON
UPDATE [dbo].[ORDER]
SET [USERID] = #UserID,
[DATE] = CURRENT_TIMESTAMP
WHERE ID = #sID

I would like to recommend you to change your method from sqldatasource to code behind, as it makes your code more clear and it is more effective.
You may use the next method:
protected void UpdateDB(string user_id, string sid){
SqlConnection con = new SqlConnection(your_connection_string);
SqlCommand cmd = new SqlCommand("spProofStamp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#USERID", SqlDbType.NVarChar).Value = user_id;
cmd.Parameters.Add("#SID", SqlDbType.NVarChar).Value = sid;
try{
con.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex){
//process your exception
}
finally{
con.Close();
Response.Redirect(Request.Url.AbsoluteUri); //refresh this page
}
}
And call your method:
UpdateDB(login.ToUpper(), selectedValue);

Related

Print Data of only first row of database instead of whole table

I need to output the data that's only on the first row, but it is printing all the data added to the database table. Here is the data:
For example, It should print only "Not Very Nice" and the message of ID 27, but not the second row that has ID 28.
Here is the code:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class feedback1 : System.Web.UI.Page
{
SqlConnection con;
string cons = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
con = new SqlConnection(cons);
con.Open();
cmd = new SqlCommand("insert into feedback(username,message) values('" + TextBox1.Text + "','" + TextBox2.Text +"')", con);
cmd.ExecuteNonQuery();
}
}
Here is the output..
This is the output page code..
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1" EnableModelValidation="True" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" GridLines="None">
<Columns>
<asp:BoundField DataField="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="username" HeaderText="username" SortExpression="username" />
<asp:BoundField DataField="message" HeaderText="message" SortExpression="message" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" OnSelecting="SqlDataSource1_Selecting" SelectCommand="SELECT * FROM [feedback]"></asp:SqlDataSource>
<div>
</div>
</form>
This is just a case of modifying your SQL-query:
Selecting the 1st row:
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
OnSelecting="SqlDataSource1_Selecting"
SelectCommand="SELECT * FROM [feedback] LIMIT 1">
</asp:SqlDataSource>
Selecting specific ID:
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
OnSelecting="SqlDataSource1_Selecting"
SelectCommand="SELECT * FROM [feedback] WHERE [id] = REPLACE_WITH_YOUR_NUMBER">
</asp:SqlDataSource>
"Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause to select a limited number of records."
Please see: https://www.w3schools.com/sql/sql_top.asp
NOTE
Your program is vulnerable to SQL-injections.
Please modify your input to sanitize your query before its executed.
protected void Button1_Click(object sender, EventArgs e)
{
con = new SqlConnection(cons);
con.Open();
string txtb1= TextBox1.Text,
txtb2= TextBox2.Text;
sqlCommand.CommandText = "select * from product where name = #name";
cmd = new SqlCommand("insert into feedback(username,message) values('" + #txtb1 + "','" + #txtb2 +"')", con);
cmd.Parameters.AddWithValue("txtb1", txtb1);
cmd.Parameters.AddWithValue("txtb2", txtb2);
cmd.ExecuteNonQuery();
}
😠Stop right there! 🚨✋! This is the police 👮 I hope you've read up on the laws around this block. You're in violation of penal code 404 - Database Not Found!
If you post another 📖 sql-vulnerable 📠 post again in this neighborhood 🏠🏠
I'm gonna have to 🔒 arrest you 🔒
No ticket today 👦
📟This is just a warning ⚠️ be careful next time 🚧
Depending on whether you always want that specific row with ID 27, or whether you just want the "first" row, whatever that happens be, you can write either
SELECT * FROM feedback WHERE id = 27
or
SELECT * FROM feedback LIMIT 1
respectively.
P.S. This is given using MySQL syntax, since that's what you tagged the question with. However, from your code I can see that you use a SqlConnection object to connect, which is only compatible with Microsoft SQL Server. If you're using SQL Server and not MySQL, then please change your question tags to mention the correct product. You would also need to alter the second query in my example above to SELECT TOP 1 FROM feedback, as TOP is used in SQL Server, whereas LIMIT achieves the same effect in MySQL.

ASP. NET - SqlDataSource update data base

I'm learning ASP and I get stuck to update the database using asp SqlDataSource and GridView.
I have the following controls:
<asp:SqlDataSource ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:BPersonalConnectionString %>"
OldValuesParameterFormatString="original_{0}"
ConflictDetection="CompareAllValues"
SelectCommand="SELECT [Marca], [Nume], [Prenume], [Salariu], [Profesia] FROM [Salariati]"
UpdateCommand="update [Salariati] set [Marca] = Marca, [Nume] = Nume, [Prenume] = Prenume, [Salariu] = Salariu, [Profesia] = Profesia
where [Marca] = #original_Marca">
<UpdateParameters>
<asp:Parameter Name="Marca" Type="Int16"/>
<asp:Parameter Name="Nume" Type="String" Size="20"/>
<asp:Parameter Name="Prenume" Type="String" Size="20" />
<asp:Parameter Name="Salariu" Type="Int32" />
<asp:Parameter Name="Profesia" Type="String" Size="10" />
<asp:Parameter Name="original_Marca" Type="Int16" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView"
runat="server"
DataSourceID="SqlDataSource1"
AutoGenerateColumns="true"
AutoGenerateEditButton="true"
DataKeyNames="Marca"
AllowPaging="true"
PageSize="3"></asp:GridView>
Whenever I try to edit and update a item I dont get any result. The grid shows me exact same values as before the update. I did not wrote any code in code behind file.
I looked to some other examples already done on this subject but I was unable to identify the cause of the update problem.
Any hints?
Thanks!!!
Use the code Behind to fill gridView, it's much easier and offer you more handling and customization to gridView binding
here you will find some guide for the simplest way to connect gridView with sql data source.
If you want to do this by creating a method that returns a DataSet as well as passing parameters to execute the query then do something like this I will post the same thing returning a DataTable as well but it's pretty straight forward it works with any query that you pass dynamically
public static DataSet ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
return ds;
}
}
if you want to return a DataTable
public static DataTable ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
return ds.Tables[0];
}
}
You added parameters, but where is the value?
And look to your query: to some parameters you didn't used #, but for last one used. Change your query to the following:
UpdateCommand="update [Salariati] set [Marca] = #Marca, [Nume] = #Nume, [Prenume] = #Prenume, [Salariu] = #Salariu, [Profesia] = #Profesia
where [Marca] = #original_Marca">
And then your parameters:
<asp:ControlParameter ControlID="YourControlID" Name="Marca" PropertyName="Text" />
<asp:ControlParameter ControlID="YourControlID" Name="Nume" PropertyName="Text" />
<asp:ControlParameter ControlID="YourControlID" Name="Prenume" PropertyName="Text" />
<asp:ControlParameter ControlID="YourControlID" Name="Salariu" PropertyName="Text" />
<asp:ControlParameter ControlID="YourControlID" Name="Profesia" PropertyName="Text" />
<asp:ControlParameter ControlID="YourControlID" Name="original_Marca" PropertyName="Text" />

Adding a "Select All" in drop down list

I have added a "Select All" value in ddlCategory to select all categories when it is selected but I got this error message "Cannot perform '=' operation on System.Int32 and System.String." Any ideas? Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
if (ddlCategory.SelectedItem.Text == "Select All")
{
ProductDataSource.SelectCommand = "SELECT [ProductId], [ProductName], [ImageUrl], [Price], [CategoryId] FROM [Product] WHERE [SystemId] = 1";
}
}
Here is the code to ProductDataSource:
<asp:SqlDataSource
ID="ProductDataSource"
EnableCaching="true"
DataSourceMode="DataSet"
runat="server"
ConnectionString="<%$ ConnectionStrings:ProjectConnectionString1 %>"
SelectCommand="SELECT [ProductId], [ProductName], [ImageUrl], [Price], [CategoryId] FROM [Product] WHERE [SystemId] = 1"
FilterExpression="CategoryId = '{0}'">
<FilterParameters>
<asp:ControlParameter Name="categoryparm" ControlID="ddlCategory" PropertyName="SelectedValue" />
</FilterParameters>
</asp:SqlDataSource>
You added element Select All, but what is the value of your element? I think it is better to you to use SelectedValue. Add to your DropDownList element Select All with value 0, and then your method will looks like
if (ddlCategory.SelectedValue == 0){ /* your query here */}
Also I recommend you to perform this actions on first load of the page, not on postbacks. So your Page_Load method will looks like
if (!IsPostBack){
if (ddlCategory.SelectedValue == 0)
ProductDataSource.SelectCommand = "select * from product where systemid = 1";
}

Return all values from table if one field in query string is empty and its in String format

I have a page that list products from table based on values passed in querystring.
ex:- abc/product.aspx/subcat=Mobile&bnd=Samsung
Here it will display all mobile with brand Samsung
How can i display all mobile irrespective of the brand if bnd is empty or not passed i.e only subcat value is passed.
I need SqlDataSource command to do the same. My current query is as shown below:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:shoppingConnectionString2 %>"
SelectCommand="SELECT * FROM [ProductDetails] WHERE (([Sub_category] = #Sub_category) AND ([Brand] = #Brand OR #Brand IS NULL))"
onselecting="SqlDataSource1_Selecting">
<SelectParameters>
<asp:QueryStringParameter Name="Sub_category" QueryStringField="subcat"
Type="String" DefaultValue="" "" />
<asp:QueryStringParameter Name="Brand" QueryStringField="bnd" Type="String"
DefaultValue="IS NULL" ConvertEmptyStringToNull="True" />
</SelectParameters>
</asp:SqlDataSource>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string subcat = Request.QueryString["subcat"];
string bnd = Request.QueryString["bnd"];
string query = "SELECT * FROM [ProductDetails] WHERE ([Sub_category] = " + subcat + ")";
if (!String.IsNullOrEmpty(bnd))
{
query += " AND ([Brand] = " + bnd + ")";
}
SqlDataSource1.SelectCommand = query;
}
}
HTML markup:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:shoppingConnectionString2 %>"
SelectCommand="SELECT * FROM [ProductDetails]"
onselecting="SqlDataSource1_Selecting">
</asp:SqlDataSource>
(Note the removed SelectParameters)
I've never used a SqlDataSource before, but this is similar to what I'd do for an ObjectDataSource. Would the above code work for your scenario?
EDIT : Please note that this method is open to SQL injection attacks, so you ought to validate/sanitize the querystring parameters first.

using session variable within sql query

i have an application where a user logs in and can edit his/other's data. however, if the user is an admin, he gets a gridview with all user's records which he can edit. if the user is not an admin, he will just get a listview where he can edit his own data.
when a user logs into the page, his userid, which is in itself also stored in the db, is stored as a session variable in Session["ID"]. now i need to populate the listview with the user's data. i thought it would be good to just query the data based on the Session["ID"] parameter. but i am not sure how to do this.
EDIT:
ok i have little code regarding this as i have no idea how to do it but i will post what i have. first is the method where i set the session variable of the userid:
objda = new SqlDataAdapter("[GetIDOfUser]", objcon);
objda.SelectCommand.CommandType = CommandType.StoredProcedure;
objda.SelectCommand.Parameters.Add("#Username", SqlDbType.VarChar).Value = tbUsername.Text;
objda.SelectCommand.Parameters.Add("#UserPassword", SqlDbType.VarChar).Value = tbPassword.Text;
String id = (string)objda.SelectCommand.ExecuteScalar();
Session["ID"] = id;
this is my markup:
<asp:ListView ID="ListView1" Visible="False" runat="server" DataSourceID="SqlDataSource2"></asp:ListView>
this is the code where i enable the listview:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserAuthentication"] == null)
{
Response.Redirect("Login.aspx");
}
if (Session["Benutzerart"].ToString() == Enums.Enumerations.Benutzer.Administrator.ToString())
{
GridView1.Visible = true;
//Set controls for admin
}
if (Session["Benutzerart"].ToString() != Enums.Enumerations.Benutzer.Administrator.ToString())
{
ListView1.Visible = true;
//Set controls for other users
}
}
ok guys i have figured it out:
i just make normal listview as in the code above. only the data source has no selectcommand attribute in the markup. this attribute is set in-code:
if (Session["Benutzerart"].ToString() != Enums.Enumerations.Benutzer.Administrator.ToString())
{
ListView1.Visible = true;
SqlDataSource2.SelectCommand = "SELECT [Titel], [Bezeichnung], [Vorname], [Nachname], [Geburtsdatum], [Geburtsort], [Straße], [Nationalität], [Hausnummer], [PLZ], [Ort], [Land], [Mobil], [UrlaubstageGenommen], [UrlaubstageInsgesamt], [Status], [Benutzerart], [Homepage], [Email], [Festnetz], [Fax], [UrlaubstageRest], [Username], [UserPassword] FROM [Benutzer] WHERE [BenutzerID] = '" + Session["ID"] + "'";
}
markup of datasource:
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ></asp:SqlDataSource>
you are binding listview with SqlDataSource, use sqldatasource SelectParameter
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:yourConnection %>"
SelectCommand="SELECT * FROM yourTable WHERE userid = #userid">
<SelectParameters>
<asp:SessionParameter Name="userid" SessionField="ID" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
To select data from DB you can create sql data source and bind it to ListView:
SqlDataSource ds = new SqlDataSource();
ds.ConnectionString = yourDBconnectionString;
ds.SelectCommand = "SELECT * FROM records_table WHERE user_id=#user_id";
ds.SelectParameters.Add("user_id", Convert.ToInt32(Session["id"]));
ListView1.DataSource = ds;
ListView1.DataBind();
Then to bind records fields to ListView on aspx page use (just an example):
<%# Eval("recort_title") %>

Categories