System.Data.SqlClient.SqlException: 'Invalid column name 'music'.' - c#

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.

Related

DataGridView does not show SOME data

I created an app for inserting specific data into database and it works fine.
However, when i try to view that data, DataGridView shows just some of those fields.
I stucked here. I tried to delete DataGridView and write code again, but it didn't helped.
private void displayData()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\me\Documents\DataB.mdf;Integrated Security=True;Connect Timeout=30";
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM dbo.Users ";
cmd.ExecuteNonQuery();
DataGrid.Update();
DataSet dt = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
DataGrid.DataSource = dt;
conn.Close();
}
I expected completely filled DataGridView, but some fields are empty.
I can see name, username, date of birth, than 5 empty cells, then again i can see salary, education and so on..

Insert and restore and search in combox?

Salam Alekom .
I have comboBox filling it from database as
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlCommand scm = new SqlCommand();
scm.Connection = con;
scm.CommandText = "select * from com";
SqlDataAdapter adpt = new SqlDataAdapter(scm);
DataTable dt = new DataTable();
adpt.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = dt.Columns["com_name"].ToString();
comboBox1.ValueMember = dt.Columns["com_id"].ToString();
Where filling with all data that store in the table from database.
This comboBox use also to insert to another table in database
This also poses no problem
The problem when making search in table to get some data. I need to get the text value that store in table and equal to text value of comboBox and sort it in position 0 of this comboBox
I made the search no problem but what property or method that allow me to put the value in position 0 with out affecting the other values that be in combobox
SqlConnection con = new SqlConnection(strcon);
con.Open();
using(SqlCommand scm2 = new SqlCommand())
{
scm2 .Connection = con;
scm2.CommandType = CommandType.StoredProcedure;
scm2 .CommandText = "SP_retrieve_data";
scm2.Parameters.AddWithValue ("#id", textBox1.Text);
SqlDataReader dr = scm2.ExecuteReader();
while (dr.Read())
{
comboBox1. = dr["com_name"].ToString();//what code accept the value
}
}

Populate listview with data received from SQL query

I am currently trying to populate a listview with some data I have pulled from my database table; but not sure where to start; I have tried the following:
lstData.DataSource = conn;
lstData.DataBind();
But that causes an error:
"Data source is an invalid type. It must be either an IListSource,
IEnumerable, or IDataSource. MVC"
Am I using the correct query strings in order to populate my listview?
Thanks,
Callum
C# Code:
string ssConnectionString = "Server connection";
SqlConnection conn = new SqlConnection(ssConnectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Category FROM [dbo].[Category] WHERE CategoryID = '16'";
command.ExecuteNonQuery();
string com = command.ExecuteScalar().ToString();
lblSQL.Text = com;
conn.Close();
Using your code as a base to start from you may want to try the following: I assume your connection in "Server connection" is a place holder for a real connection string and you know what should go there.
string ssConnectionString = "Server connection";
SqlConnection conn = new SqlConnection(ssConnectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Category FROM [dbo].[Category] WHERE CategoryID = '16'";
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dataTable;
da.Fill(dataTable);
lstData.DataSource = dataTable;
lstData.DataBind();
conn.Close();

Click Button - No Action

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)

error while deleting row in gridview via 3 tier

Object reference not set to an instance of an object.
This is the error which i m getting while i trying to delete .. row from my grid view
this is in .. page_ load
gvDetails.DataSource =myBl.DeleteAllCountry(int.Parse(gvDetails.SelectedRow.ToString()));
on data access layer
public DataTable DeleteCountry(int country_id)
{
DataTable dltcontry = new DataTable();
SqlConnection con = new SqlConnection(#"Data Source=a8-pc\sqlexpress;Integrated Security=True");
SqlDataAdapter da;
try
{
SqlCommand cmd = new SqlCommand();
cmd.connection= con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_DeleteCountry";
con.Open();
da = new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("country_id", #country_id);
cmd.ExecuteNonQuery();
da.Fill(dltcontry);
con.Close();
}
and in business layer the code is like
public DataTable DeleteAllCountry(int country_id)
{
return mydtLayer.DeleteCountry(country_id);
}
First thing to correct, you need to set connection to your command
cmd.Connection =con;
or in the constructor as below
SqlCommand command = new SqlCommand(
queryString, connection);
Another problem is you try to convert selected gvDetails.SelectedRow to int value
check gvDetails.selectedRows.Count before you get value of selected row
if you have selection you can then get cell valu of your country_id column as below
gvDetails.SelectedRow.cells("country_id").Text
now you can convert this to a int value by using int.TryParse and if it is success send to your BL function to delete the record

Categories