Check if user input into a ASP.net webform Textbox exists in a SQL column - sql

How can I validate the user input to a data in a SQL table?
I want to ensure the users can only input Part Numbers that are in a SQL table.
It is a Web form in ASP.net.
private static List<string> AutoFillProducts(string prefixText)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "select PART from PARTSTABLE where " + "LOWER (PART) like #Search + '%'";
com.Parameters.AddWithValue("#Search", prefixText);
com.Connection = con;
con.Open();
List<string> parts = new List<string>();
using (SqlDataReader sdr = com.ExecuteReader())
{
while (sdr.Read())
{
parts.Add(sdr["PART"].ToString());
}
}
con.Close();
return parts;
}
}
}
<asp:TextBox ID="txtpart" runat="server" Height="30px" input type="text" placeholder="Enter Part" style="text-transform:uppercase;" onblur="onLeave(this)" OnTextChanged="txtpart_TextChanged"></asp:TextBox>
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="4"
CompletionInterval="5" EnableCaching="false" CompletionSetCount="1" TargetControlID="txtpart"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">
</asp:AutoCompleteExtender>

Related

Passing DropDownList value into SQL command in ASP.net

I have a DropDownList which gets it values from SQL table
I want to get the Average of the selected item (course in this case) from the dropDownList and to show it in a label :
This section works -
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand("SELECT Course FROM GradesTable1", sqlConnection1);
Command.Connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(Command);
DataTable dataTble1 = new DataTable();
dataAdapter.Fill(dataTble1);
if (dataTble1.Rows.Count > 0)
{
foreach (DataRow row in dataTble1.Rows)
{
ListItem course1 = new ListItem(row["Course"].ToString());
if (!DropDownList1.Items.Contains(course1))
{
DropDownList1.Items.Add(course1); // showing the 2 courses
}
}
}
Command.Connection.Close();
}
}
Here is the problem - (I get nothing, no data )
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand($"SELECT AVG(Grade) FROM GradesTable1 WHERE Course = #course", sqlConnection1);
Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem);
Command.Connection.Open();
SqlDataReader sqlDataReader1 = Command.ExecuteReader();
if (sqlDataReader1.Read())
{
LabelAverage.Text = sqlDataReader1[0].ToString();
}
else
{
LabelAverage.Text = "No Data"; // doesn't get into here anyhow
}
}
EDIT
I tried several variations as $"SELECT AVG(Grade) AS "ClassAVG" FROM GradesTable1 WHERE Course = #course" and Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem.Text), or DropDownList1.SelectedValue
I believe the problem is with the DropDownlist values which being received from the SQL and are not hard coded.
Is there a correct way to this? is it possible without knowing what are the "Courses" in advanced?
Thanks for the answers, feel free to give your opinion.
I found out what was missing in the DropDownList in aspx page (not the aspx.cs page) -the AutoPostBack="true"
Adding that to DropDownList solved the problem.
// query = Sql query
query.Select(s => new MusteriNoktaComboItemDTO
{
Label = s.Adi,
Value = s.ID.ToString()
}).ToList();

Asp.net sql deleting a row generated by datatable

I want to create a delete button that gets the id next to it
My method to get data is like this a button generates creates the picture
protected void btnSelect_Click(object sender, EventArgs e)
{
try /* Select After Validations*/
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = ConfigurationManager.ConnectionStrings["SHOT"].ToString();
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "Select * from shot_assessment";
cmd.CommandType = CommandType.Text;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cmd.Dispose();
connection.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
catch (Exception ex) { }
}
html code as: `
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="delete">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField></Columns></asp:GridView> `

How to get average rating using Ajax Rating Tool

My code
<form id="form1" runat="server">
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</cc1:ToolkitScriptManager>
<cc1:Rating ID="Rating1" AutoPostBack="true" OnChanged="OnRatingChanged" runat="server"
StarCssClass="Star" WaitingStarCssClass="WaitingStar" EmptyStarCssClass="Star"
FilledStarCssClass="FilledStar">
</cc1:Rating>
<br />
<asp:Label ID="lblRatingStatus" runat="server" Text=""></asp:Label>
</form>
Rating.aspx
public partial class CS : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = this.GetData("SELECT ISNULL(AVG(Rating), 0) AverageRating, COUNT(Rating) RatingCount FROM UserRatings");
Rating1.CurrentRating = Convert.ToInt32(dt.Rows[0]["AverageRating"]);
lblRatingStatus.Text = string.Format("{0} Users have rated. Average Rating {1}", dt.Rows[0]["RatingCount"], dt.Rows[0]["AverageRating"]);
}
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void OnRatingChanged(object sender, RatingEventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO UserRatings VALUES(#Rating)"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Rating", e.Value);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
}
I found this code online.It is not working. I can not find any errors but it is not inserting records.In this output screen is shows 0 users have rated, Average Rating 0 even after you rate it.
I am new to Ajax and asp.net.If you can give any suggestions it would be helpful
THANK YOU.

Login form in ASP.net does not work

I'm new to ASP.net and currently failing to create a simple functioning login form. After establishing the connection to my database, I wanted the function to check whether a given combination of username and password exists in the database. Due to the fact that I have not created the "member zone" page yet, It's supposed to do nothing if the data is valid and return "Login failed" in the opposite case. For some reason, it doesn't work. I would be glad if someone could help me trace the problem.
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT * FROM users WHERE username='" + UserName.Text +
"' AND password='" + Password.Text + "' ";
SqlCommand cmd = new SqlCommand(query, con);
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
Response.Write("Login failed.");
}
You have SELECT * FROM in the query and you are using ExecuteScalar method to check if anything is returned.
You should use SELECT COUNT(*) FROM to get the number of rows exist in the table for given username and password.
Another thing which is not right in your code is the generation of query. Using parameterized query is the most recommended approach.
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT COUNT(*) FROM users WHERE username=#userName AND password=#password";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#userName", UserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", Password.Text));
con.Open();
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
{
Response.Write("Login failed.");
}
This should resolve your issue.
You forgot to open connection before executing ExecuteScalar()
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT COUNT(*) FROM users WHERE username=#userName AND password=#password";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#userName", UserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", Password.Text));
//Add Below line and test your code.
con.Open();
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
{
Response.Write("Login failed.");
}

silverlight C# code

This is coded in Service.svc.cs file
[OperationContract]
public List<Branch> GetAllBranch()
{
List<Branch> Br = new List<Branch>();
using (SqlConnection con = new SqlConnection(myConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "GetBranch";
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Branch BrName = new Branch();
BrName.Name = Convert.ToString(dr["BranchName"]);
Br.Add(BrName);
}
dr.Close();
}
}
return Br;
}
public class Branch
{
public string Name { get; set; }
}
End of Service file Code----
This is coded in the Form
ServiceClient client= new ServiceClient();
test.GetAllBranchCompleted += (s, ea) =>
{
cboBranch.ItemsSource = ea.Result;
};
client.GetAllBranchAsync();
My requirement is I want to populate all the Names of the Branches that are present in my database.With this code the combobox for BranchName is getting populated but not with the Database records but something like this CRUD.ServiceReference1.ServiceBranch.
CRUD is my solution Name.
Please correct me with this..
Thanks
To get just the name to appear in your ComboBox you need to result a List<string>. Here you are returning a List<Branch>.
So you either need to rework your service code or just extract a list of strings from your ea.Result.
cboBranch.ItemsSource = ea.Result.Select(b => b.Name).ToList();
(from memory)