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.
Related
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string SaveLayout(string layout, object state)
{
SqlConnection conn = new SqlConnection(#"Persist Security Info=False;User ID=admin;Password=admin123;Initial Catalog=Test_Layout;Data Source=Myserver");
conn.Open();
SqlCommand cmd = new SqlCommand("insertlayout", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#layout", layout);
cmd.Parameters.AddWithValue("#states", state);
cmd.ExecuteNonQuery();
conn.Close();
return "successfully state saved";
}
}
i am using webmethod(using Json,jquery) to store object in sql server 2008
but i am getting following error on sql server 2008 i am using varchar(max) datatype for storing object(state variable) in database how to convert state variable(object) to string to store in database
The problem is that you have to pass a string instead of dictionary. I may suggest you to serialise your dictionary and pass that value to AddWithValue function. Let JSON be the format of serialisation. I would recommend Json.net as serialization library. It provides convenient way of dictionary serialization/deserialization.
So your code may look like this:
cmd.Parameters.AddWithValue("#states", JsonConvert.SerializeObject(state));
P.S. better use using statement both for SqlConnection and SqlCommand objects.
If you want to store any object use VARBINARY(MAX) in sqlserver like
sqlCmd.Parameters.Add("#states", SqlDbType.VarBinary, Int32.MaxValue);
sqlCmd.Parameters["#states"].Value = state;
here state will be your object
All I want to do is to retrieve data from tables in .accdb file.
Here is my full application:
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 System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection myConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Microland.accdb;Persist Security Info=False;");
myConn.Open();
OleDbCommand myQuery = new OleDbCommand("select CustID from Customers WHERE CustID = 1;", myConn);
OleDbDataReader myReader = myQuery.ExecuteReader();
if(myReader.HasRows)
{
myReader.Read();
label1.Text = myReader.ToString();
}
myConn.Close();
}
}
}
I think I am missing some using at the very top or my code is somewhat broken becasue then I click the button1 the label1 text changes to System.Data.OleDb.OleDbDataReader.
Also is this the correct way to connect to access data base (.accdb) Do I need to do this walkthrough in order for it to work or this is irrelevant to what I need to do?
Thanks for any information! Very appreciated
When you call myReader.ToString() it returns a string that represents the current object. So "System.Data.OleDb.OleDbDataReader" is exactly that.
It seems like you want the label to be equal to the data that's read. I'm not familiar with this reader in particular, but refer here for documentation.
You'll need to call one of the Get*() functions.
label1.Text = myReader["CustID"] as string; // if nullable field
Or
label1.Text = (string)myReader["CustID"] // if not null
I'm facing this issue and I don't know the reason behind it. Here's the error Visual Studio is reporting:
The best overloaded method match for 'PostForum.INSERTforum(int, string, string, System.DateTime)' has some invalid arguments
I'm using Oracle to store my data and also created a procedure called INSERTFORUM. I am not sure if I have a problem with the stored procedure or something else. Please help me sort out this issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Forum : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string course_Id = DropDownList1.Text;
int ccourse_Id = Convert.ToInt32(course_Id);
string question = TextBox1.Text;
string posterName = TextBox2.Text;
DateTime blog_date = DateTime.Now;
PostForum.INSERTforum(course_Id, question, posterName, blog_date);
}
}
Code for :Postforum.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public class PostForum
{
public static int INSERTforum(int course_Id, string question, string posterName, DateTime blog_date)
{
int rowsAffected = 0;
using (SqlConnection connection = ConnectionManager.GetDatabaseConnection())
{
SqlCommand command = new SqlCommand("INSERTforum", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#course_Id", SqlDbType.Int).Value = course_Id;
command.Parameters.Add("#question", SqlDbType.VarChar).Value = question;
command.Parameters.Add("#posterName", SqlDbType.VarChar).Value = posterName;
command.Parameters.Add("#blog_date", SqlDbType.DateTime).Value = blog_date;
rowsAffected = command.ExecuteNonQuery();
}
return rowsAffected;
}
}
INSERTforum expects an int as the first parameter. You're passing it a string. Correct your invocation of INSERTforum to read:
PostForum.INSERTforum(ccourse_Id, question, posterName, blog_date);
Note that this will fail if DropDownList1.Text can't be parsed as an integer.
Don't forget to look at the Error List tab in Visual Studio. The error you saw was only the first - the next error would have given you the information I did.
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.
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!