I wrote this code to get data from mysql database using odbc connection. Its giving no error but no output as well. Am not able to find what the matter is.
public partial class Members : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
string conString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
using (OdbcConnection con = new OdbcConnection(conString))
{
con.Open();
// We are now connected. Now we can use OdbcCommand objects
// to actually accomplish things.
using (OdbcCommand com = new OdbcCommand("SELECT * FROM abc", con))
{
using (OdbcDataAdapter ad = new OdbcDataAdapter(com))
{
ad.Fill(table);
}
}
con.Close();
}
}
catch (Exception ei)
{
Label1.Text = ei.Message;
}
GridView1.DataSource=table;
GridView1.DataBind();
}
}
In web.config do you have a connectionString? Please check that.
If not you can add datasource from visual studio designer and it will ask to add connection string in one of the steps .At the end you can remove datasource from designer but still have connectionstring in web.config file .And in your code behind can you try this
string SQL_CONNECTION_STRING = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectionTest"].ConnectionString;
where "SqlConnectionTest" is the name of connection string in web.config.
The problem was that I converted a vb project just by replacing the c# file with the vb ones to make it a c# project, and this created this whole mess.The code work perfectly fine when done on a new projects.
Related
I'm working on a small project that's unrelated to this, it needs a database to be integrated into it, so I looked into SQLite and tried to teach myself the basics.
My code works fine but I realised if I was to deploy this on another machine it wouldn't be able to connect to the database because it wouldn't have the file as I've hard coded it in (it's running of my C:\ drive currently which will be an issue for users who haven't got it there obviously).
I was wondering if it was possible to update to connection string for the user at runtime? Even say, when the user installs it, it installs a copy of the database and changes its path to that?
Here's my code:
using System;
using System.Windows.Forms;
using System.Data.SQLite;
namespace sqltest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string cs = #"Data Source=c:\student.db;Version=3;FailIfMissing=False";
string stm = "SELECT Name FROM Customer";
using var con = new SQLiteConnection(cs);
con.Open();
using var cmd = new SQLiteCommand(stm, con);
using SQLiteDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
MessageBox.Show($"{rdr.GetString(0)}");
}
}
}
}
Thanks for any help!
you can get datasource from config file, e.g. appsetting.json
The connection string that you pass to new SQLiteConnection(...); is actually being passed at runtime already.
Sounds like the simplest solution is to create the database if it doesn't already exists with a predetermined path. This will ensure that when your script runs on a machine that doesn't have a DB, the DB will be created at runtime.
Here's a relevant post: Programmatically create sqlite db if it doesn't exist?
I am trying to fill list boxes with elements and been doing everything by a clean guide but I am getting connection string error when I am trying to run it.
Clearly i have done something foolish and can't understand it so a deeper explanation would be appreciated
The error
The ConnectionString property has not been initialized.
The Code
public partial class FormMain : Form
{
SqlConnection connection;
string connectionString;
public FormMain()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["NaujasAutoSalonas.Properties.Settings.AutoSalonasConnectionString"].ConnectionString;
}
private void FormMain_Load(object sender, EventArgs e)
{
PopulateAutoKlases();
}
private void PopulateAutoKlases()
{
using (connection = new SqlConnection(connectionString));
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM AutoKlases", connection))
{
DataTable KlasesTable = new DataTable();
adapter.Fill(KlasesTable);
lstKlases.DisplayMember = "KlasesPavadinimas";
lstKlases.ValueMember = "KlasesID";
lstKlases.DataSource = KlasesTable;
}
}
}
As you have stated that the connection string property is not initialized,so I guess that your applications is not able to read the connection string from the config file.You can confirm this by putting a breakpoint in the constructor of FormMain class.
If the connection string is not being set in the constructor then you need to identify whether you have declared the connection string properly in your config file.As there could be few config files ,so it is important that you declare your connection string in the correct config file.
Or if you are defining properties for your connection string in the .settings file,you can validate if you are accessing it correctly.
I am using Microsoft Visual Web Developer 2010 Express. I have been trying to enter my textbox input into a database table I created. I ran into a problem using the DataBinding property (located under the BindTextBoxes method at the bottom). I searched the internet and found out that the DataBinding property does not exist in Web Developer. Is there an alternate way to transfer the textbox input into a database table?
Here is database part of my code (in C#):
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
//used to link textboxes with database
BindingSource bsUserDetails = new BindingSource();
//info stored in tables
DataSet dsUserDetails = new DataSet();
//manages connection between database and application
SqlDataAdapter daUserDetails = new SqlDataAdapter();
//create new SQL connection
SqlConnection connUserDetails = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Users\synthesis\Documents\Visual Studio 2010\Projects\Practical\Practical\App_Data\UserDetails.mdf;Integrated Security=True;User Instance=True");
protected void Page_Load(object sender, EventArgs e)
{
//link textboxes to relevant fields in the dataset
bsUserDetails.DataSource = dsUserDetails;
bsUserDetails.DataMember = dsUserDetails.Tables[0].ToString();
//call BindTextBoxes Method
BindTextBoxes();
private void BindTextBoxes()
{
txtBoxCell.DataBindings.Add(new Binding("Name entered into txtBox", bsUserDetails,
"Name column in database table", true));
}
}
}
You could always write your own SQL for inserting data from your text boxes. You'll need to setup a SqlConnection and SqlCommand object. Then you'll need to define the SQL on the command and set up the parameters to prevent SQL injection. Something like this:
StringBuilder sb = new StringBuilder();
sb.Append("INSERT INTO sometable VALUES(#text1,#text2)");
SqlConnection conn = new SqlConnection(connStr);
SqlCommand command = new SqlCommand(sb.ToString());
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("text1", text1.Text);
command.Parameters.AddWithValue("text2", text2.Text);
command.ExecuteNonQuery();
I want to display information of user stored in a MS Access database. The user enters his userid and on clicking a button following function is called. But no data is being displayed. What am I doing wrong ?
System.Data.OleDb.OleDbConnection con;
System.Data.OleDb.OleDbDataAdapter da;
protected void Button1_Click(object sender, EventArgs e)
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
string sql = "SELECT * From Leave where userid="+Textbox1.Text;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
DataTable t = new DataTable();
da.Fill(t);
GridView1.DataSource = t;
con.Close();
}
You need to call GridView1.DataBind()
GridView1.DataSource = t;
GridView1.DataBind();
Just a side-note, it is good practice to wrap your connection with using
using(con = new System.Data.OleDb.OleDbConnection())
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
...
...
}
This ensures your connection is properly disposed after use
You should use bind function:
protected void Button1_Click(object sender, EventArgs e)
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
string sql = "SELECT * From Leave where userid="+Textbox1.Text;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
DataTable t = new DataTable();
da.Fill(t);
GridView1.DataSource = t;
GridView1.DataBind();
con.Close();
}
First off, please, please please don't concatenate your WHERE parameters in your SQL. Use Parameters. Second, Add a "using System.Data.OleDb" statement at the top of your module, so that you are not having to type things like:
System.Data.OleDb.OleDbDataAdapter
Over and over again.
Try the following code. Personally, when I have to work with data tables and such, I prefer to avoid all the DataAdapter nonsense, and keep it as simple as possible.
Note in the code below:
the "using" blocks. These place the variables created within them inside their own scope, and take care of disposal and such for you.
I used an OleDb Parameter instead of concatenating criteria. This is a much safer way to do things, and creates much cleaner and more readable code as well, especially in cases where you have several criteria in your WHERE clause.
I assume your UserID input is a string, since you are grabbing the value from a Textbox. If it is in fact an int value (such as an auto-incrementing id in MS Access) you will need to use an int data type instead. You may have to mess with it a little. When you are still figuring this stuff out, it can be a bit painful. However, using parameters increases security and maintainability.
Once you have obtained a data table as the return from the MyUsers method, you should be able to simply set the data source of your Gridview. If you have difficulties still, do as Steve suggests and check the Autogenerate columns property in the designer, or set it in code.
Not that I have moved the connection string to the project Properties/Settings. You should find this in the solution designer. Place your connection string there, in one spot, and you can obtain it from anywhere in your code. If you later change the connection string (such as moving your Db to another computer, server share, etc) you need only change it in one place.
SAMPLE CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb; // put this here, and stop writing long namespaces inline
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Where possible, move code out of specific event handlers
// into methods which can be re-used from other client code.
// Here, I pulled the actual data access out into separate methods,
// and simply call it from the event handler:
this.LoadGridView(textBox1.Text);
}
private void LoadGridView(string UserID)
{
// Now we can load the gridview from other places in our
// code if needed:
this.dataGridView1.DataSource = this.MyUsers(UserID);
}
private DataTable MyUsers(string UserID)
{
var dt = new DataTable();
// Use a SQL Paramenter instead of concatenating criteria:
string SQL = "SELECT * FROM Leave WHERE userid = #UserID";
// The "using" statement limits the scope of the connection and command variables, and handles disposal
// of resources. Also note, the connection string is obtained from the project properties file:
using(OleDbConnection cn = new OleDbConnection(Properties.Settings.Default.MyConnectionString))
{
using (var cmd = new OleDbCommand(SQL, cn))
{
// For simpler things, you can use the "AddWithValue" method to initialize a new parameter,
// add it to the Parameters collection of the OleDBCommand object, and set the value:
cmd.Parameters.AddWithValue("#UserID", UserID);
// Get in, get out, get done:
cn.Open();
dt.Load(cmd.ExecuteReader());
cn.Close();
}
}
return dt;
}
}
}
Hope that helps. It's not how everyone might do it, but I have found it provides maximum flexibility, when you must work with MS Access.
I have a local project where I am trying to input data from an ASP:textbox to a database.
On building I get the following...
"Failed to generate a user instance of SQL Server. Only an integrated connection can generate a user instance. The connection will be closed."
I'm a little puzzled here, I have checked the database and it is active with the credentials i am trying to connect with.
Here is the code behind
C#
namespace OSQARv0._1
{
public partial class new_questionnaire : System.Web.UI.Page
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection sqlcon = new SqlConnection(#"user id=*myuserid*;"+"password=*mypassword*;"+"Data Source=mssql.dev-works.co.uk;User Instance=True;"+"Database=devworks_osqar"+"Trusted_Connection=true;");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Create_Click(object sender, EventArgs e)
{
DataBinder ds = new DataBinder();
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand("INSERT INTO QUESTIONNAIRES (QuestionnaireName) VALUES ('"+qnrName.Text+"')");
sqlcmd.Parameters.AddWithValue("#Name", qnrName.Text);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
}
}
}
Any help would be much appreciated.
Edited code behind (read commment below)
C#
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.Sql;
using System.Data.SqlClient;
namespace OSQARv0._1
{
public partial class new_questionnaire : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private string myConnectionString;
private SqlConnection myConn;
public new_questionnaire()
{
myConn = new SqlConnection();
myConnectionString += "Data Source=mssql.database.co.uk; Initial Catalog=devworks_osqar;User ID=myusername;Password=mypassword";
}
protected void Create_Click(object sender, EventArgs e)
{
//DataBinder ds = new DataBinder();
SqlCommand sqlcmd = new SqlCommand("INSERT INTO QUESTIONNAIRES (QuestionnaireName) VALUES ('"+qnrName.Text+"')");
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddWithValue("#Name", qnrName.Text);
insert(sqlcmd);
}
private void insert(SqlCommand myCommand)
{
myConn.Open();
myCommand.ExecuteNonQuery();
myConn.Close();
}
}
}
Fix error "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance."
Content from link pasted and altered below in case reference site is removed in the future:
Step 1.
Enabling User Instances on your SQL Server installation
First we are gonna make sure we have enabled User Instances for SQL Server installation.
Go to Query Window in SQL Server Management Studio and type this:
exec sp_configure 'user instances enabled', 1.
Go
Reconfigure
Run this query and then restart the SQL Server.
Step 2.
Deleting old files
Now we need to delete any old User Instances.
Go to your C drive and find and completely DELETE this path (and all files inside):
C:\Documents and Settings\ YOUR_USERNAME \Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS
(Dont forget to replace the bold text in the path with your current username (if you are not sure just go to C:\Documents and Settings\ path to figure it out).
After deleting this dir you can go to Visual Studio, create ASP.NET WebSite and click on your App_Data folder and choose Add New Item and then choose SQL Server Database and it should work!!!