I am having problems getting data to be displayed in a gridview in VS 2010.
I have a SQLdataSource which is connecting to my database but the gridview is not showing at all, my error message is all that is displayed. Would anyone know why this is?
This is the code that I have:
`using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Web.Services.Description;
namespace DBprototype2
{
public partial class _Default : System.Web.UI.Page
{
void Page_Load(Object sender, EventArgs e)
{
// This example uses Microsoft SQL Server and connects
// to the Northwind sample database. The data source needs
// to be bound to the GridView control only when the
// page is first loaded. Thereafter, the values are
// stored in view state.
if(!IsPostBack)
{
// Declare the query string.
String queryString =
"SELECT * FROM ";
// Run the query and bind the resulting DataSet
// to the GridView control.
DataSet ds = GetData(queryString);
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
Label1.Text = "Connected.";
}
else
{
Label1.Text = "Unable to connect to the database.";
}
}
}
DataSet GetData(String queryString)
{
// Retrieve the connection string stored in the Web.config file.
String connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
DataSet ds = new DataSet();
try
{
// Connect to the database and run the query.
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
// Fill the DataSet.
adapter.Fill(ds);
Label1.Text = "Connected.";
}
catch(Exception ex)
{
// The connection failed. Display an error message.
Label1.Text = "Unable to connect.";
}
return ds;
}
}
}
`
If anyone could tell me the problem with my code that would be extremely helpful.
The problem is your query:
String queryString =
"SELECT * FROM ";
You are missing the table to select from, later in your method GetData you are not adding any table name in the query, that is why it is failing.
Also consider enclosing your connection in using statement
Use the Exception object ex.Message instead of hard coded error in label, this will help you debug and see what exactly is going wrong.
Not for this particular scenario but always consider using parametrized queries.
Related
I have an int variable in my C# code and I'm trying to use it in a MySql query.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace projeV1
{
public partial class ProjeDetay : Form
{
public ProjeDetay()
{
InitializeComponent();
}
private void ProjeDetay_Load(object sender, EventArgs e)
{
int satir_projem = Projeler.satir_proje;
string connectionString = "Server = localhost; Port = ...; Database = ...; Uid = root; Pwd = ...; Allow User Variables=True";
MySqlConnection databaseConnection = new MySqlConnection(connectionString);
MySqlCommand command;
databaseConnection.Open();
command = databaseConnection.CreateCommand();
string myQuery = "select projeAdi from projeler where projeID = #satir_projem";
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(myQuery, databaseConnection);
command.Parameters.Add("#satir_projem", MySqlDbType.Int32).Value = satir_projem;
DataSet DS = new DataSet();
dataAdapter.Fill(DS);
dataGridView_ProjeDetay.DataSource = DS.Tables[0];
MessageBox.Show(Projeler.satir_proje.ToString());
MessageBox.Show(satir_projem.ToString());
}
}
}
(Sorry if it looks like a mess in regard to coding but I'm new at this ^^)
MessageBox windows show the variables' values correctly, so there's no problem with the variable. And when I replace#satir_projem from the query string with a number like "2" (see the example below), for example, the result is correct, but when I use #satir_projem in the query, it doesn't work. I can't see what I'm doing wrong.
Example query string:
"select projeAdi from projeler where projeID = 2"
P.S 1: Originally I'm trying to get the index of the selected row (which is the variable called Projeler.satir_proje) in a DataGridView used in a form called "Projeler" and in another form (which is called ProjeDetay), assigning that index value into another variable called "satir_projem" and use this value to get the related data from my database and put that data in another DataGridView located in my second form (which is called dataGridView_ProjeDetay).
P.S 2: I've made a lot of research about this problem and tried many of the solutions I encountered along the way; however, none of them worked for me. So, here I am :)
Thanks in advance.
You are setting parameter for command that is not used.
Instead you should use DataAdapter.SelectCommand
dataAdapter.SelectCommand.Parameters.Add(...)
MySqlConnection databaseConnection = new MySqlConnection(connectionString);
MySqlCommand command;
string myQuery = "select projeAdi from projeler where projeID = #satir_projem";
databaseConnection.Open();
command = new MySqlCommand(myQuery, databaseConnection);
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(command);
Just want to elaborate, why #Onur_Saatcioglu's code is throwing error.
you are adding #satir_projem to command but the parameter thus added to command is not being passed to dataadapter which serves as a bridge between a DataSet and SQL Server for retrieving and saving data.
Hence you can
1) As Lester told, create command like
command = new MySqlCommand(myQuery, databaseConnection);
and pass the command to DataAdapter
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(command);
2) As #Pablo_notPicasso said, if you are using
dataAdapter.SelectCommand.Parameters.AddWithValue("#satir_projem", satir_projem);
then "command" does not make sense, you can just delete it.
I'm new to C# and javacript. I'm doing my first program on Visual Studio and I have one problem to retrieve data from a SQL Server database.
I want to retrieve data from SQL Server and convert it to Json by using an ajax method. But when I start my web page I can see only the table empty, so I think I have not a good method to connect to my data base.
Here is the code for my WebMethod used to retrieve data and convert to Json:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using Newtonsoft.Json;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string LoadData()
{
string strcon = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("select * from kit", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return JsonConvert.SerializeObject(ds.Tables[0]);
}
Please I need your Help I have done several days on this program. Thanks for all your help.
Your CommandType should be Text and not StoredProcedure since you are using a string SQL command and not a Stored Procedure.
I am still new to ASP.net and I'm learning how to call classes. I've looked around for tutorials, but not all are specific to ASP.net 4.0 so I'm not sure if I should apply them.
Right now, I am trying to connect to my SQL database. My webconfig file has been set up with the connectionstring "dbConnectionString" and is working properly when I've tested it with GridViews. What I'd like to do now is access the database from code behind.
I've seen some ways to accomplish this, but I'd like the most efficient, resuable way. I've tried to adopt the answer listed here: How to create sql connection with c# code behind, access the sql server then conditionally redirect? however, I'm getting an error.
I am doing this with C# as a website, not a web application. Here is my code behind for Login.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SqlComm; // Is this how I connect to my class from this page????
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//no code written yet
}
}
}
My class in the App_Code folder, file name SQLComm.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web;
/// <summary>
/// SQL Query class
/// </summary>
public class SqlComm
{
// Connection string
static string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;
// Execute sql command with no value to return
public static void SqlExecute(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
// Execute SQL query and return a value
public static object SqlReturn(string sql)
{
using (SqlConnection conn = new SqlConnection(PjSql.dbcs()))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
object result = (object)cmd.ExecuteScalar();
return result;
}
}
// Retrieve an entire table or part of it
public static DataTable SqlDataTable(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
DataTable TempTable = new DataTable();
TempTable.Load(cmd.ExecuteReader());
return TempTable;
}
}
// Execute a stored procedure with 1 parameter
// Returning a value or just executing with no returns
public static object SqlStoredProcedure1Param(string StoredProcedure, string PrmName1, object Param1)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(StoredProcedure, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(PrmName1, Param1.ToString()));
cmd.Connection.Open();
object obj = new object();
obj = cmd.ExecuteScalar();
return obj;
}
}
}
As you can see, I haven't written any code to actually use the class yet, but the "using SQLComm;" line itself is giving me this error:
Compiler Error Message: CS0246: The type or namespace name 'SqlComm' could not be found (are you missing a using directive or an assembly reference?)
As I'm still new, I'm unsure where to go from here. I seem to have included everything contained in the answer on the page I linked above. What else and I missing?
Edit: I read this post regarding a similar issue: asp.NET 2.0 Web Site Can't Access Classes in App_Code
Could this be because I am doing a website and not a web application, so the App_Code folder is being handled differently when I FTP the files over?
using SQLComm means you want to use the namespace SqlComm, which doesn't exist. I think what you want is (somewhere in your codebehind):
DataTable dt = SqlComm.SqlDataTable(...) // call one of the static methods.
You can call it directly.
Given your class has static methods only you'll call it like this:
SqlComm.SqlReturn("select * from table");
So I believe I figured it out. I had my App_Code folder within the subdirectory of my Aspx website, instead of in the root of the server. I moved the folder to the root and now it's working.
I'd be interested in hearing any answers to my edit to my original post though. Since I'm doing this as a website instead of a web application, are there any other issues I will need to keep in mind regarding using classes like this or other issues? I've looked around but haven't seen many differences.
Thanks to everyone for you help!
I'm using Visual Web Developer 2010 Express and SQL Server 2008 R2 Management Studio Express
Hey guys,
Pretty new at C# here. I'm trying to follow this C# ADO.NET tutorial (currently on step 2), and I'm stumped. I'm following all the steps, and everything makes sense to me in it, but whenever I try to debug, it does not show anything (in the sense of the c# methods not printing out a table from Northwind database onto my webpage) in WebApplication1's Default.aspx page.
For a while, I thought it was my connection string, conn, and I wasn't naming the "Data Source" attribute, which from my understanding is the name of the server I'm trying to connect to. It is all on a local machine, and I'm putting the correct server name.. I think. Server name is AZUES-221\JDOESQLSERVER
I'm properly escaping the backward slash, but I still don't know. Is there something in my coding that's flawed? Please help!
C# code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Main(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn); //passed the connection
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{ Console.WriteLine(rdr[0]); }//selected in the table
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
Thanks in advance
As your example seems to be a WebProject try to put your code within Page_Load eventHandler. Afterwards you should try to print your data to the Debug window or to a control within your webPage.
using System;
using System.Data;
// and all the others ...
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn);
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{
System.Diagnostics.Debug.WriteLine(rdr[0]); // or on the other hand
lblOutput.Text += rdr[0]; // as a "quick and dirty" solution!
}
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
You may it find very useful to have a look at databound controls or just use another type of project (eg winForm, console, ...)
Create a Console application instead of the Web Application you have created.
Otherwise you will run into similar issues considering you are new to C# (or Visual Studio in general) AND considering the rest of the tutorial uses Console.WriteLine heavily.
Then you can use the same code as shown in the tutorial.
Additonally if you are concerned about the slash in the database server (it is a database server instance), you may wanna try this:
SqlConnection conn = new SqlConnection(#"Server=AZUES-221\JDOESQLSERVER;Database=Northwind;Trusted_Connection=True;");
Source: Connection Strings Reference
why would console.writeline show anything. you are not working on console.
in case just to see your output. use Response.writeline(rdr[0]);
I am trying to write t-sql in C# (visual studio). I have this code to connect to the database:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Xtreme\\Desktop\\CardsDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
Where/how do I write the T-SQL code and how do I get the result?
Can someone give me an simple select example in my code?
You can use DataAdapter.Fill Method:
try
{
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM Employee", cnn))
{
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// Render data onto the screen
dataGridView1.DataSource = t; //if you want.
}
}
catch (Exception ex)
{
MessageBox.Show("Problem!");
}
Create a SqlCommand and set the CommandType to CommandType.Text. Then add your SQL to the CommandText property of the SqlCommand.
SqlCommand command = new SqlCommand(commandName, (SqlConnection)Connection);
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM MyTable";
IDataReader result = command.ExecuteReader();
Ardman already showed you how to execute any arbitary sql command. But what i didn't answer very well, is where to put your sql statement.
I think it is a very bad behaviour and also not very good to read if you put your statement directly into the code.
A better method (in my eyes) is the following:
Within your project create a new folder (maybe called Queries)
Right click this folder and select Add - New Item
In the dialog just select Textfile and give it the name about what this query will do
Make sure you replace the file extension from .txt to .sql
Just put your statement right into this file
In the Resource Editor add this file as a resource
Now you can access this sql statement within your project just by using Properties.Resources.MySqlStatement