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();
Related
I'm trying to INSERT data into my SQL database but its not showing anything at all.
This is a for an online role-playing game . There is no error but when I refresh my browser for phpmyadmin using XAMP, no data is being shown.
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
string checkDatabase = "select * from players where username = #playerName";
MySqlCommand command = new MySqlCommand(checkDatabase, connection);
command.Parameters.AddWithValue("#playerName", player.SocialClubName);
MySqlDataReader reader = command.ExecuteReader();
if(reader.Read())
{
player.SendChatMessage("There is an account with the assiociated Social Club Profile!");
}
else
{
MySqlConnection connection1 = new MySqlConnection(connectionString);
connection1.Open();
string playerInsert = "insert into players(username,password) VALUES (#user,#password)";
MySqlCommand command1 = new MySqlCommand(playerInsert, connection1);
command1.Parameters.AddWithValue("#user", player.SocialClubName);
command1.Parameters.AddWithValue("#password", password);
connection1.Close();
}
connection.Close();
You need to execute the query. Try:
...
command1.ExecuteNonQuery();
That's cause you are not executing the query at all as can be seen in below posted code
string playerInsert = "insert into players(username,password) VALUES (#user,#password)";
MySqlCommand command1 = new MySqlCommand(playerInsert, connection1);
command1.Parameters.AddWithValue("#user", player.SocialClubName);
command1.Parameters.AddWithValue("#password", password);
command1.ExecuteNonQuery(); //execute the query
connection1.Close();
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.
For reference, this page (add.ashx.cs), is an add page to a database.
What I'm trying to do is :
figure out how to execute string queryID, and then
store the results of queryID
I'm a bit new at this, but this is what I'm working with so far. Am I on the right path, and what should I change? I don't believe the code below includes storing the results, but just executing queryID.
// new query to get last ID value
// store the command.executeNonQuery results into a variable
string queryID = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
// first: look up how to execute queryID
// then: store results of query ^
// execute queryID? (section below)
SqlConnection sqlConnection1 = new SqlConnection(queryID);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "Select * FROM queryID";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// data is accessible through the datareader object here
sqlConnection1.Close();
There are some things missmatched in your code sample. First queryID is your actual query. Second in SqlConnection you need to provide a connection string, that connects to your database (SQL Server, ACCESS, ...). A valid example could look like this:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
SqlDataReader reader;
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
List<string> results = new List<string>();
if(reader.HasRows)
{
while(reader.Read())
{
results.Add(reader[0].ToString());
}
}
sqlConnection1.Close();
Another thing is, that you execute a reader but only select one single value. You can perfectly use ExecuteScalar for that:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
sqlConnection1.Close();
One last thing. You should use objects that implement IDisposable in a using block. This way the will be removed from memory when they are no longer needed:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
using(SqlConnection sqlConnection1 = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
}
Below is a snapshot of my code. I am trying to access the only column in the customer table and place the values into a textbox on the form. I keep getting the error with my code "InvalidOperationException was unhandled" at the line declaring dr as a OleDbDataReader object.
What do I have wrong with the below code that would be giving me this error?
Should I do a list to pick out the text I want from the database?
How can I return the column values from access into a list in C# so that I can search the list for a particular value?
string strsql = "Select * from Customer";
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
textBox1.Text += dr["Customer"].ToString();
}
conn.Close();
A command carries the info to be executed, a connection carries the info to reach the database server. The two objects should be linked together to produce any result. You miss that line
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
cmd.Connection = conn; // <= here
conn.Open();
Remember also that disposable objects like a command, a reader and a connection should be disposed immediately after usage. For this pattern exists the using statement
So you should write
string cmdText = "Select * from Customer";
using(OleDbConnection conn = new OleDbConnection(.....constring...))
using(OleDbCommand cmd = new OleDbCommand(cmdText, conn))
{
conn.Open();
using(OleDbDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
.....
}
}
Here is some sample code.
try
{
using (OleDbConnection myConnection = new OleDbConnection())//make use of the using statement
{
myConnection.ConnectionString = myConnectionString;
myConnection.Open();//Open your connection
OleDbCommand cmdNotReturned = myConnection.CreateCommand();//Create a command
cmdNotReturned.CommandText = "someQuery";
OleDbDataReader readerNotReturned = cmdNotReturned.ExecuteReader(CommandBehavior.CloseConnection);
// close conn after complete
// Load the result into a DataTable
if (readerNotReturned != null) someDataTable.Load(readerNotReturned);
}
}
After that you have a Datatable containing your data. Ofcourse you can afterwards search for records in the Datatable any way you like.
I got this OfficeWriter error when debugging the console application. I used methods to retrieve config details for the database used in the coding from the master database, and ended up having this error.
Error binding in GetColumnNumber at row 1
Attached here is partial coding for my work. Anyone can explain me what the error is?
SqlDataReader rdSource = getSource();
SqlDataReader rdDestination = getDestination();
SqlDataReader rdCode = getCode();
while (rdSource.Read() && rdDestination.Read())
{
string src = rdSource["Value"].ToString();
string dest = rdDest["Value"].ToString();
ExcelTemplate XLT = new ExcelTemplate();
XLT.Open(src);
DataBindingProperties dataProps = XLT.CreateBindingProperties();
XLT.BindData(rdCode, "Code", dataProps);
XLT.Process();
XLT.Save(dest);
}
//rdCode method
SqlDataReader rdConnection = getConnection(); //method for getting connection from master
while (rdConnection.Read())
{
string con = rdConnection["Value"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
string SQL = "SELECT * FROM Sales.Currency";
sqlCon.Open();
SqlCommand cmd = new SqlCommand(SQL, sqlCon);
cmd.ExecuteReader();
sqlCon.Close();
}
return rdConnection;
//getConnection method
string strCon = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(strCon);
string cSQL = "SELECT Value FROM dbo.COMMON_CONFIG WHERE Value = 'Data Source=localhost;Initial Catalog=Test;Integrated Security=True'";
SqlCommand cmd = new SqlCommand(cSQL, sqlCon);
sqlCon.Open();
return new SqlCommand(cSQL, sqlCon).ExecuteReader(CommandBehavior.ConnectionString);
//getSource & getDestination methods
string strCon = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(strCon);
string srcPath = #"FILE PATH NAME"; //change to destPath for getDestination
string sSQL = "SELECT Value FROM dbo.COMMON_CONFIG WHERE Value = '" + srcPath + "'";
SqlCommand cmd = new SqlCommand(cSQL, sqlCon);
sqlCon.Open();
return new SqlCommand(cSQL, sqlCon).ExecuteReader(CommandBehavior.ConnectionString);
The error is a generic message that is thrown by ExcelWriter when it is unable to bind data to the template.
I think this might be caused by your getCode() method. In getCode(), you use a SQLDataReader to retrieve the connection string for the database:
SqlDataReader rdConnection = getConnection(); //method for getting connection from master
Then you execute a SQL query against that database, but you don't actually get a handle on the SqlDataReader that is executing the SQL query to return the data.
SqlCommand cmd = new SqlCommand(SQL, sqlCon);
cmd.ExecuteReader(); //Note: This returns the SqlDataReader that contains the data
Then you return rdConnection, which is the SQLDataReader for the connection string - not the data you are trying to import. rdConnection contained 1 row and you already called Read(), so there are no records left to read.
SqlDataReader rdCode = getCode();
...
XLT.BindData(rdCode, "Code", dataProps);
The SQL reader you are binding is the used 'connection string', rather than your sales data. I would recommend the following:
Return the new SqlDataReader that is generated by cmd.ExecuteReader() in getCode(), rather than rdConnection.
Do not close the connection to this new SqlDataReader. ExcelWriter needs to be able to read the data reader in order to bind the data. If you close the connection, ExcelWriter will not be able to bind data correctly.