Click Button - No Action - c#

I am trying to retrieve information from database. User enters id of the person he is looking for to ID textbox, than press display button. The grid view should show the result. But when button is pressed, nothing happens. Could anyone help or tell me what I should check?
Code for button:
protected void btnDisplay_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source="Name";Initial Catalog="Name";Integrated Security=True");
SqlCommand cmd = new SqlCommand("displayData", conn);
conn.Open();
cmd.Parameters.Add("#ID", System.Data.SqlDbType.Int).Value = Convert.ToInt32(txtID.Text);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader rd = cmd.ExecuteReader();
grvResults.DataSource = rd;
grvResults.DataBind();
}
Here is stored procedure:
USE ["Name"]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[displayData] (#ID int)
as
begin
SELECT * FROM Customers WHERE ID = #ID
end
Here is display data method:
public List<Customer> displayData()
{
List<Customer> lst = new List<Customer>();
SqlConnection conn = new SqlConnection("Data Source="Name";Initial Catalog="Name";Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * From Customers", conn);
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
lst.Add(new Customer()
{
ID = rd.GetInt32(0),
FName = rd.GetString(1),
LName = rd.GetString(2)
});
}
return lst;
}
aspx for button:
<asp:Button ID="btnDisplay" runat="server" Text="Display" OnClick="btnDisplay_Click" />

have you tried to put a breakpoint in button click. Is it hitting breakpoint. If not then I will say remove
OnClick="btnDisplay_Click"
from your aspx page. And then add default click event from .cs page by selecting control and it events. Them try to debug line by line.

Give the following code a try in your codebehind. It should bind properly and fill a gridview. If it works, add more code from there. If it doesn't work, look at things like your connection string. Let me know.
SqlConnection conn = new SqlConnection("Data Source="?";Initial Catalog="?";Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers WHERE ID = #ID", conn);
cmd.Parameters.Add("#ID", System.Data.SqlDbType.Int).Value = Convert.ToInt32(txtID.Text);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
conn.Close();
grvResults.DataSource = dt;
grvResults.DataBind();

I think you are complicating yourself too much
First do this:
That should make it work. You already have a stored procedure which makes it easier. (Sorry for the pictures, I wanted to make sure you understood this)

Related

System.Data.SqlClient.SqlException: 'Invalid column name 'music'.'

I want to display a category (service) based on menu item value, so when the user clicks on music item for example it should fill the repeater from database table (ServiceP) where the name of the service = to the menu item value.
I tried this code, but I get an error
System.Data.SqlClient.SqlException: 'Invalid column name 'music'
This is the code when users clicks a menu item
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\TOSHIBA\Documents\PartyZone.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from ServiceP where
ServiceName = "+e.Item.Value.ToString() ;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
d1.DataSource = dt;
d1.DataBind();
conn.Close();
}
Assuming you actually have:
cmd.CommandText = "select*from ServiceP where ServiceName="+e.Item.Value.ToString() ;
and e.Item.Value is "music", then what you need here is a parameter to hold the value to search for, i.e.
cmd.CommandText = "select*from ServiceP where ServiceName=#value";
cmd.Parameters.AddWithValue("#value", e.Item.Value.ToString());
Note that you can also throw away the cmd.ExecuteNonQuery(); - that does nothing useful here, and means you do the work twice.

how to get max id from master table and based on that insert one record in master table and one or more entry in child table

When I click on add that data will go to child table and above data go to master table.
Here's a screenshot of the design:
save button click event:
protected void btnsave_Click(object sender, EventArgs e)
{
SqlConnection con2 = new SqlConnection(#"Data Source=GLSPL06-PC\GLSPL06;Initial Catalog=example;User ID=sa;Password=sa#123");
con2.Open();
SqlCommand cd = new SqlCommand("insertmaster", con2);
cd.CommandType = CommandType.StoredProcedure;
cd.Parameters.AddWithValue("#name", txtname.Text.Trim());
cd.Parameters.AddWithValue("#age", txtage.Text.Trim());
cd.Parameters.AddWithValue("#gender", Radiogender.SelectedItem.ToString());
cd.ExecuteNonQuery();
con2.Close();
foreach (GridViewRow item in gv.Rows)
{
SqlConnection con = new SqlConnection(#"Data Source=GLSPL06-PC\GLSPL06;Initial Catalog=example;User ID=sa;Password=sa#123");
con.Open();
string statment = string.Format("insert into child_table ( [relative_name], [relation]) values ('{0}','{1}')", item.Cells[0].Text, item.Cells[1].Text);
SqlCommand cmd = new SqlCommand(statment, con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
}
successmsg.Text = "Data Inserted Successfully";
}
You have to write Sql query as below in your procedure and call your procedure from application:
DECLARE #id INT
INSERT INTO MainPerson VALUES(Name,Age,Male)
SET #id= SCOPE_IDENTITY()
INSERT INTO RelativePerson Values(#id,Name,Relation)
As you have to use the Scope_Identity in order to get the last id inserted to your master table.
Change Your code to this:
SqlConnection con2 = new SqlConnection(#"Data Source=GLSPL06-PC\GLSPL06;Initial Catalog=example;User ID=sa;Password=sa#123");
con2.Open();
SqlCommand cd = new SqlCommand("insertmaster", con2);
cd.CommandType = CommandType.StoredProcedure;
cd.Parameters.AddWithValue("#name", txtname.Text.Trim());
cd.Parameters.AddWithValue("#age", txtage.Text.Trim());
cd.Parameters.AddWithValue("#gender", Radiogender.SelectedItem.ToString());
string id = cd.GetScalar();
con2.Close();
And Change Your insertmaster Procedure to:
Insert into MainTable values(name,age,gender)
Select SCOPE_IDENTITY()
Then you will get the id use that to insert in child table from code.

Asp.Net SQL Update Statement

I have an Asp.net application on my page the user requests for a user to be removed. This then populates my 'Admin_TaskList' db.
An administrator then goes in the secure area of the site and enters the users name and clicks a button. Upon the confirmation, the user is then deleted from my 'Users' db (already got this working) but I want my 'Admin_TaskList' db 'Status' column to change from 'To Do' to 'Completed'.
As I sad I have the delete bit working but I am struggling updating my other table.
Snippet of code I have tried
conn.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = #Name", conn);
cmd2.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd2 = cmd2.ExecuteReader();
conn.Close();
Full code
public void btnRemoveConfirmYes_Click(object sender, EventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = #Name", conn);
cmd1.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd1 = cmd1.ExecuteReader();
conn.Close();
conn.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = #Name", conn);
cmd2.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd2 = cmd2.ExecuteReader();
conn.Close();
txtRemoveUser.Text = "";
Response.Redirect("/AdminSide/TaskList.aspx");
}
Instead of using a SqlDataReader to update a value use SqlCommand.ExecuteNonQuery:
int updated = cmd2.ExecuteNonQuery();
Remember that you need to use ExecuteNonQuery on commands that modify your data like Delete, Insert or Update.
MSDN:
You can use the ExecuteNonQuery to perform catalog operations (for
example, querying the structure of a database or creating database
objects such as tables), or to change the data in a database without
using a DataSet by executing UPDATE, INSERT, or DELETE statements.
The complete method:
int deleted, updated;
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
using (var conn = new SqlConnection(connection))
{
conn.Open();
string delSql = "DELETE FROM Users WHERE Name = #Name";
using (var cmd = new SqlCommand(delSql, conn))
{
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
deleted = cmd.ExecuteNonQuery();
}
string updSql = #"UPDATE Admin_TaskList
SET Status = 'Complete'
WHERE Description = 'Remove User'
AND Name = #Name";
using (var cmd = new SqlCommand(updSql, conn))
{
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
updated = cmd.ExecuteNonQuery();
}
}

SQL update command not working

I have created a web page in Asp.net website. The following page load will run as it gets arguments from previous page. The page also has an option for editing the contents and updating in database. But when the button(save) is clicked it doesn't update the database.Kindly help in this. But when there is no connection in page load the update command works.
protected void Page_Load(object sender, EventArgs e)
{
String cust=Request.QueryString["custName"];
String env = Request.QueryString["env"];
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
view();
if (env == "Production")
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value= myRow["Customer_Maintenance"].ToString();
serviceAffect.Value=myRow["Systems/Services_Affected"].ToString();
email_Content.Value= myRow["Email_Content"].ToString();
email_Signature.Value= myRow["Email_Signature"].ToString();
email_From.Value=myRow["Email_From"].ToString();
email_To.Value=myRow["Email_To"].ToString();
email_Cc.Value=myRow["Email_Cc"].ToString();
email_Bcc.Value=myRow["Email_Bcc"].ToString();
}
}
else
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Non_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value = myRow["Customer_Maintenance"].ToString();
serviceAffect.Value = myRow["Systems/Services_Affected"].ToString();
email_Content.Value = myRow["Email_Content"].ToString();
email_Signature.Value = myRow["Email_Signature"].ToString();
email_From.Value = myRow["Email_From"].ToString();
email_To.Value = myRow["Email_To"].ToString();
email_Cc.Value = myRow["Email_Cc"].ToString();
email_Bcc.Value = myRow["Email_Bcc"].ToString();
}
}
The following is the button click for Save Button(for update command)
protected void save_click(object sender, EventArgs e)
{
//Button Click Save
/* String id = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",TextBox1.Text,id);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
*/
String cust = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
if (env.Value == "Production")
{
//String sql = String.Format("Update Customer_Production set Customer_Maintenance='{0}',Environment='{1}',[Systems/Services_Affected]='{2}',Email_Content='{3}',Email_Signature='{4}',Email_To='{5}',Email_Cc='{6}',Email_Bcc='{7}',Email_From='{8}' where Customer_Name like '{9}' ", "custMaintain.Value","env.Value","serviceAffect.Value","email_Content.Value","email_To.Value","email_Cc.Value","email_Bcc.Value","email_From.Value", "cust");
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'", email_Signature.Value,cust);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
}
else
{
}
}
I'm not sure why having a connection (or not) in the Page_Load would make a difference, but here's one thing that looks off to me:
String.Format(
"Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",
email_Signature.Value,
cust);
(I broke it into several lines because the part I'm interested in is the last part of the format string.)
You've set cust to "A" earlier in that method. So the SQL that will result will look (at the end) like this:
... where Customer_Name like 'A'
Unless you have a customer name that is exactly equal to A, that's not going to return anything, and therefore no records will be updated. You're forgetting the '%' wildcard.
I agree with all those who have pointed out that your code is vulnerable to SQL injection (and you'll also have a problem with single quotes), but just to show you what it needs to look like, here it is with the wildcard:
Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}%'

Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'PRC0000001'

i keep getting this error, i dont know why, im still new to c#. kindly help me figure this out please. i have two dropdownlist that would populate data based on first dropdownlist selected value.
when i select a value on the first dropdownlist, i get that error..
here is my code..
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//read sql server connection string from web.config file
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT CITY_NAME FROM emed_city WHERE PROVINCE_CODE ="+ddlProvince.SelectedValue, conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlProvince.DataBind();
}
}
It happens because you passed the raw value without quotes, so the database thought you mean field name.
Avoid this all mess by using Parameters:
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT CITY_NAME FROM emed_city WHERE PROVINCE_CODE=#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
This answer is an alternative approach, when using Parameters isn't viable.
The SQL interpreter is confusing values with database objects.
You can save the interpreter from confusion by making your SQL statement more explicit. Surround columns and table names with [ square brackets and wrap any values in single quotes.
using (conn)
{
var whereValue = "'"+ddlProvince.SelectedValue+"'";//wrap in single quotes
conn.Open();
SqlCommand comm = new SqlCommand("SELECT [CITY_NAME] FROM [emed_city] WHERE [PROVINCE_CODE] = "+whereValue;
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
The square brackets explicitly state to the SQL Intepreter that it is dealing with a database object. The single quotes inform the interpreter it is dealing with a value.
Now the interpreter won't mistake your value for a column name.

Categories