Asp.net sql deleting a row generated by datatable - sql

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> `

Related

Database is not being updated with Textbox values on button click event

I have an SQL update command for some Textboxes and Comboboxes. However, when the event is fired the database is not getting updated with the Textboxes and I am not getting any exception errors.
The line in particular that I am having an issue with is cmd.Parameters.AddWithValue("#FR_CMMNT", txt_ResolutionNotes.Text);
Here is my code:
private void Button_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=WINDOWS-B1AT5HC\\SQLEXPRESS;Initial Catalog=CustomerRelations;Integrated Security=True;");
try
{
SqlCommand cmd = new SqlCommand("UPDATE [hb_Disputes] SET FR_DSP_CLSF=#FR_DSP_CLSF, FR_CUST_CNTCT=#FR_CUST_CNTCT, FR_WRK_REQ=#FR_WRK_REQ, FR_OPN_ERR=#FR_OPN_ERR, FR_SO_TP=#FR_SO_TP, FR_SO_DTLS=#FR_SO_DTLS, FR_CMMNT=#FR_CMMNT, FR_SO_DT_WNTD=#FR_SO_DT_WNTD, FINADJ=#FINADJ, SERTYPE=#SERTYPE, CALLRSN=#CALLRSN, SECCAUSE=#SECCAUSE, MTR=#MTR, RPTTYPE=#RPTTYPE, PRMCAUSE=#PRMCAUSE WHERE DSP_ID=#DSP_ID", con);
cmd.Parameters.AddWithValue("#DSP_ID", txt_RowRecrd.Text);
// Second Row
cmd.Parameters.AddWithValue("#FR_DSP_CLSF", cmb_DisputeClassification.SelectedValue);
cmd.Parameters.AddWithValue("#FR_CUST_CNTCT", cmb_CustomerContact.SelectedValue);
cmd.Parameters.AddWithValue("#FR_WRK_REQ", cmb_requestedwork.SelectedValue);
cmd.Parameters.AddWithValue("#FR_OPN_ERR", cmb_OpenInError.SelectedValue);
cmd.Parameters.AddWithValue("#FR_SO_TP", cmb_ServiceOrderType.SelectedValue);
cmd.Parameters.AddWithValue("#FR_SO_DTLS", cmb_ServiceOrderDetails.SelectedValue);
cmd.Parameters.AddWithValue("#FR_CMMNT", txt_ResolutionNotes.Text);
cmd.Parameters.AddWithValue("#FR_SO_DT_WNTD", DatePicker_ScheduledFor.Text);
// Third Row
cmd.Parameters.AddWithValue("#RPTTYPE", cmb_UtilityRptTyp.SelectedValue);
cmd.Parameters.AddWithValue("#FINADJ", cmb_FinancialAdjustment.SelectedValue);
cmd.Parameters.AddWithValue("#SERTYPE", cmb_ServiceTypeAdjustment.SelectedValue);
cmd.Parameters.AddWithValue("#CALLRSN", cmb_InitialCallReason.SelectedValue);
cmd.Parameters.AddWithValue("#PRMCAUSE", cmb_PrimCause.SelectedValue);
cmd.Parameters.AddWithValue("#SECCAUSE", cmb_UnderlyingCause.SelectedValue);
cmd.Parameters.AddWithValue("#MTR", cmb_MeterIssue.SelectedValue);
con.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
cmd.Dispose();
cmd.Dispose();
MessageBox.Show("Data updated!");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

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.

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,
}

Dropdownlist not fetching values for Second and third list Item

I have two dropdowns for Showing Categories and Second for showing sub-categories related to the selected categories.
Scenario is. The category values are coming from the tables.And it is fetching properly. The problem is that, when I select the first category the second dropdown shows me the exact subcategory. But when I select the second category, it does not show me the subcategories related to it.
Please see the Code where I have binded the categories and sub categories to fetch the data.:-
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultSQLConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select CategoryName from dbo.CategoriesForMerchant where ParentId is null", conn);
SqlDataReader dr = cmd.ExecuteReader();
ddlCategories.DataSource = dr;
ddlCategories.Items.Clear();
ddlCategories.DataTextField = "CategoryName";
ddlCategories.DataValueField = "CategoryName";
ddlCategories.DataBind();
ddlCategories.Items.Insert(0, new ListItem("--Select Category--", "0"));
conn.Close();
}
}
protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultSQLConnectionString"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from CategoriesForMerchant where ParentId=0" + ddlCategories.SelectedIndex + "", conn);
SqlDataReader dr = cmd.ExecuteReader();
ddlSubCategories.DataSource = dr;
ddlSubCategories.Items.Clear();
ddlSubCategories.DataTextField = "CategoryName";
ddlSubCategories.DataValueField = "CategoryName";
ddlSubCategories.DataBind();
ddlSubCategories.Items.Insert(0, new ListItem("--Select Sub Category--", "NA"));
conn.Close();
}
Also see the SQL Table structure for the same:-
CREATE TABLE [dbo].[categoriesformerchant]
(
categoryid INT IDENTITY(1,1) NOT NULL,
categoryname NVARCHAR(50) NOT NULL,
parentid INT NULL,
CONSTRAINT [pk_CategoriesForMerchant] PRIMARY KEY CLUSTERED (categoryid ASC)
)goALTER TABLE [dbo].[categoriesformerchant] WITH CHECK ADD CONSTRAINT [fk_subcategories] FOREIGN KEY(parentid) REFERENCES [dbo].[categoriesformerchant] ([categoryid])goALTER TABLE [dbo].[categoriesformerchant] CHECK CONSTRAINT [fk_subcategories]go
Also see the HTML of the code:-
<asp:DropDownList ID="ddlCategories" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlCategories_SelectedIndexChanged">
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqCategory" runat="server" ControlToValidate="ddlCategories" ErrorMessage="Please select the category" InitialValue="0"></asp:RequiredFieldValidator>
<br />
<asp:DropDownList ID="ddlSubCategories" runat="server" AutoPostBack="True">
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqSubCategory" runat="server" ControlToValidate="ddlSubCategories" ErrorMessage="Please select the sub-category" InitialValue="0"></asp:RequiredFieldValidator>
Replace this Part
string xyz = "";
if (!String.IsNullOrEmpty(ddlCategories.SelectedValue.ToString()))
{
xyz = ddlCategories.SelectedValue.ToString();
}
SqlCommand cmd = new SqlCommand("Select * from CategoriesForMerchant where ParentId ='" + xyz + "'", conn);
SqlDataReader dr = cmd.ExecuteReader();
ddlSubCategories.DataSource = dr;
ddlSubCategories.Items.Clear();
ddlSubCategories.DataTextField = "CategoryName";
ddlSubCategories.DataValueField = "CategoryName";
ddlSubCategories.DataBind();
ddlSubCategories.Items.Insert(0, new ListItem("--Select Sub Category--", "0"));
cm.con.Close();
n this also
SqlCommand cmd = new SqlCommand("Select * from dbo.CategoriesForMerchant where ParentId is null", conn);
SqlDataReader dr = cmd.ExecuteReader();
ddlCategories.DataSource = dr;
ddlCategories.Items.Clear();
ddlCategories.DataTextField = "CategoryName";
ddlCategories.DataValueField = "CategoryId";
ddlCategories.DataBind();
ddlCategories.Items.Insert(0, new ListItem("--Select Category--", "0"));
cm.con.Close();