How to get average rating using Ajax Rating Tool - sql

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.

Related

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

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>

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 do I print SQL query using MessageBox in C#

I am stuck with this problem since yesterday. I have created a button, which when clicked display the results from a SQL Server table. I thought of using MessageBox to print these results or if there is any other way to print results?
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * FROM Products", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
command.ExecuteNonQuery();
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
I have tried different methods but it never worked.. I am really stuck. If you want more details, let me know. Thanks for the help in advance
Add a datagridview control to show multiple rows and try this code and rename it what you want and replace this YourDataGridVeiwName from the name you set for datagridview control and try below code
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
DataTable dt = new DataTable();
sda.Fill(dt);
YourDataGridVeiwName.DataSource= dt;
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
You need to use the SqlDataReader and iterate over the rows returned, extract what you need from each row, and then display that to the enduser.
I modified your code a bit, to make it safer (using blocks!), and I modified the query to return only the product name (assuming you have that) since you cannot really display a whole row in a message box....
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string productName = reader.GetFieldValue<string>(0);
MessageBox("Product is: " + productName);
}
reader.Close();
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}

C# SQL Server Update, If not exists, insert new records

I am using the following code in the button click event to update the values. If the row does not exist yet, I want to insert a new row into the table. But the code does not execute when I click on the button. Both the stored procedures are just regular insert and update SQL statements.
Any thoughts? Thank you so much!
SqlConnection con = new SqlConnection(conn.GetConnectionString());
SqlCommand cmdnew = new SqlCommand();
cmdnew.CommandType = CommandType.StoredProcedure;
cmdnew.Connection = con;
cmdnew.CommandText = "dbo.UpdateMagtoSpec";
cmdnew.Parameters.AddWithValue("#SpecNo", DropDownList1.SelectedText);
cmdnew.Parameters.AddWithValue("#TestID", ddl_testclass.SelectedValue);
cmdnew.Parameters.AddWithValue("#Max", TextBox6.Text);
cmdnew.Parameters.AddWithValue("#Typical", TextBox8.Text);
cmdnew.Parameters.AddWithValue("#Min", TextBox7.Text);
cmdnew.Parameters.AddWithValue("#Comments", TextArea2.Text);
cmdnew.Parameters.AddWithValue("#Unit", ddl_units.SelectedText);
con.Open();
SqlDataReader rdr = null;
rdr = cmdnew.ExecuteReader();
if (rdr.HasRows)
{
try
{
cmdnew.ExecuteNonQuery();
Alert.Show("Changes Saved!", MessageBoxIcon.Information);
btn_edit.Hidden = false;
Button1.Hidden = true;
Button2.Hidden = true;
TextBox6.Readonly = true;
TextBox7.Readonly = true;
TextBox8.Readonly = true;
ddl_units.Readonly = true;
TextArea2.Readonly = true;
}
catch (Exception ex)
{
if (ex.Message.ToString().Contains("Error"))
{
Alert.Show("Modification Failed!", MessageBoxIcon.Information);
}
}
con.Close();
}
else
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.CommandText = "dbo.InsertMagtoSpec";
cmd.Parameters.AddWithValue("#SpecNo", DropDownList1.SelectedText);
cmd.Parameters.AddWithValue("#TestID", ddl_testclass.SelectedValue);
cmd.Parameters.AddWithValue("#Max", TextBox6.Text);
cmd.Parameters.AddWithValue("#Typical", TextBox8.Text);
cmd.Parameters.AddWithValue("#Min", TextBox7.Text);
cmd.Parameters.AddWithValue("#Comments", TextArea2.Text);
cmd.Parameters.AddWithValue("#Unit", ddl_units.SelectedText);
try
{
cmd.ExecuteNonQuery();
Alert.Show("Records Saved!", MessageBoxIcon.Information);
}
catch (Exception ex)
{
if (ex.Message.ToString().Contains("Error"))
{
Alert.Show("Modification Failed!", MessageBoxIcon.Information);
}
}
con.Close();
}
Show us your aspx code with the button click declaration. Most probably you have to wire the code to the event.
You need both parts:
<asp:Button id="Button1"
Text="Click here for greeting..."
OnClick="GreetingBtn_Click"
runat="server"/>
And
void GreetingBtn_Click(Object sender,
EventArgs e)
{
// When the button is clicked,
}

suppose i have max(pid)=1001 if i want to display values of 1002 which is through +1 into max value so how can i do

suppose i have max(pid)=1001 if i want to display values of 1002 which is through +1 into max value so how can i do
This is my entire code i want to select max(pid) and want to display that into textbox
public PatientRegistration()
{
InitializeComponent();
string connectionstring = "DATABASE=hmanagmentsystem;UID=root;PASSWORD=;SERVER=localhost";
con = new MySqlConnection(connectionstring);
con.Open();
}
private void PatientRegistration_Load(object sender, EventArgs e)
{
MySqlCommand command = new MySqlCommand("select max(pid) from patientreg",con);
int cmd=Int32.Parse(command.ExecuteScalar().ToString());
con.Close();
}
How about:
MySqlCommand command = new MySqlCommand("select max(pid) + 1 from patientreg",
con);
More fully:
string connectionString;
public PatientRegistration()
{
InitializeComponent();
connectionString = "DATABASE=hmanagmentsystem;UID=root;PASSWORD=;SERVER=localhost";
}
private void PatientRegistration_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open;
using (SqlCommand = new SqlCommand("select max(pid) + 1 from patientreg",conn))
{
// this assumes an asp:TextBox called IDTextBox
IDTextBox.Text = command.ExecuteScalar().ToString();
}
}
}