I am trying to populate a grid view from a query I have in an SQL table through a connection string yet somehow I receive the following error.
Realistically as I am a beginner I think this is going to be an extremely simple error with the code so don't assume anything!
"The system cannot find the file specified
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.ComponentModel.Win32Exception: The system
cannot find the file specified"
The following is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
namespace GridviewTOExcel
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("data source=.; database=Richard2016DB; integrated security=SSPI");
SqlCommand cmd = new SqlCommand("Select * from dbo.tblEmployee", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
}
I believe you should send it to a DataTable first before being able to bind it.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("data source=.; database=Richard2016DB; integrated security=SSPI");
SqlCommand cmd = new SqlCommand("Select * from dbo.tblEmployee", con);
con.Open();
DataTable table = New DataTable();
using(SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
con.Close();
}
You will need the following reference to use DataTable's
using System.Data;
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace GridviewTOExcel
{
public partial class WebForm1 : System.Web.UI.Page
{
private SqlConnection con;
private SqlCommand cmd;
private string constr, query;
private void connection()
{
string dbConnectiomName = "conStr"; // Set your keyname from web.config file
constr = WebConfigurationManager.ConnectionStrings[dbConnectiomName].ToString();
con = new SqlConnection(constr);
con.Open();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
gvBind(); // Bind Gridview on pageload
}
}
// Function which bind gridview control
Public void gvBind(){
connection();
cmd = new SqlCommand();
cmd.CommandText = "Select Query"; // best practise is to use storedprocedure
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.CommandTimeout = 0;
SqlDataAdapter dap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dap.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
}
}
Related
When I try to run the above code the first part which is load all the existing records works fine. But when I try to find a specific record by using the search box the following error box pops up:
Any help would be appreciated. The code is given below:
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.SqlClient;
using System.Configuration;
namespace DataBase
{
public partial class Form1 : Form
{
string Connection = ConfigurationManager.ConnectionStrings["DataBase"].ConnectionString;
public Form1()
{
InitializeComponent();
}
private void Load1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(Connection);
SqlCommand command = new SqlCommand("select * from tblClasses", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
DataTable table = new DataTable();
table.Load(reader);
dataGridView2.DataSource = table;
con.Close();
}
private void Search1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(Connection))
{
SqlCommand command = new SqlCommand("select * from tblClasses where Teacher_ID = '" + textBox1.Text + "'", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
BindingSource Source = new BindingSource();
Source.DataSource = reader;
dataGridView2.DataSource = Source;
}
}
}
}
This is not totally correct but it might put a different slant on it.
con = new SqlConnection(Connection);
SqlCommand command;
string sql = ("select * from tblClasses");
command = new SqlCommand(sql, con);
con.Open();
command.ExecuteReader();
DataTable table = new DataTable();
table.Load(table);
dataGridView2.DataSource = table;
con.Close();
I've been practicing with ADO.NET and SQL Server in a Windows Forms application, but I can't get table data into a DataGridView on the press of a button.
There are no errors and I make server connection checking. I have corresponding database and table name with some data in it.
Any ideas what I am doing wrong?
Here is code from the button:
private void button1_Click(object sender, EventArgs e)
{
string ConnectionString = "Server=DESKTOP-FV268LU;Database=ado_database;Integrated Security=true";
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = ConnectionString;
myConnection.Open();
if (myConnection.State == ConnectionState.Open)
label1.Text = "YES!";
else if (myConnection.State != ConnectionState.Open)
label1.Text = "Nope!!";
string sql = "SELECT * FROM Main";
SqlDataAdapter myAdapter = new SqlDataAdapter(sql, myConnection);
DataSet myDataSet = new DataSet("Main");
myAdapter.Fill(myDataSet, "Main");
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = myDataSet.DefaultViewManager;
dataGridView1.Refresh();
}
You need to call after setting the DataSource
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = myDataSet.DefaultViewManager;
dataGridView1.DataBind();
EDIT
dataGridView1.DataSource = myDataSet.Tables[0];
dataGridView1.AutoGenerateColumns = true;
How about this?
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.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Configuration;
using System.Data.SqlClient;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
private DataTable table;
private DAL dal;
protected void Form_Load(object sender, EventArgs e)
{
dal = new DAL();
table = dal.GetData();
dataGridView1.DataSource = table;
}
public Form1()
{
InitializeComponent();
}
private void button5_Click(object sender, EventArgs e)
{
dal.UpdateData(table);
}
class DAL //data access layer
{
string connString = #"Server=EXCEL-PC\EXCELDEVELOPER;Database=AdventureWorksLT2012;Trusted_Connection=True;";
SqlDataAdapter da;
SqlCommandBuilder builder;
DataTable table;
SqlConnection conn;
public DataTable GetData()
{
table = new DataTable("dataGridView1");
conn = new SqlConnection(connString);
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(#"SELECT * FROM [SalesLT].[Product]", conn);
builder = new SqlCommandBuilder(da);
da.Fill(table);
return table;
}
public void UpdateData(DataTable table)
{
if (da != null && builder != null)
{
da.Update(table);
}
}
}
}
}
Here is another option for you to consider.
private void button6_Click(object sender, EventArgs e)
{
SqlConnection con = new System.Data.SqlClient.SqlConnection();
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Server=EXCEL-PC\\EXCELDEVELOPER;Database=AdventureWorksLT2012;Trusted_Connection=True;";
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
for (int i = 0; i <= dataGridView1.Rows.Count - 2; i++)
{
String insertData = "INSERT INTO Import_List(Fname, Lname, Age) VALUES (#Fname, #Lname, #Age)";
SqlCommand cmd = new SqlCommand(insertData, con);
cmd.Parameters.AddWithValue("#Fname", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Lname", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#Age", dataGridView1.Rows[i].Cells[2].Value);
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}
con.Close();
}
I'm trying to search my database to retrieve some results and populate those to a gridview.
However, I get the above error in the title, and some research hasn't really helped me on why this kind of error flags, and was wondering whether someone with a sharper mind could explain the reason for this error. My code for the code behind file of the specific page is shown below:
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;
namespace StarksComics
{
public partial class search : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
string b = "";
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["DBVS"].ConnectionString; // the error occurs at this line. ---- nullreference exception was unhandled by code.
if (con.State == ConnectionState.Closed)
{
con.Open();
}
}
private void user_chk()
{
string a;
a = TextBox1.Text;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from tbCharacters where CharName like'" + a + "%'";
cmd.Connection = con;
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
rep_bind();
GridView1.Visible = true;
TextBox1.Text = "";
}
else
{
GridView1.Visible = false;
b = TextBox1.Text + "is not available in list";
TextBox1.Text="";
}
}
private void rep_bind()
{
string a;
a = TextBox1.Text;
SqlDataAdapter adp = new SqlDataAdapter("select * from tbCharacters where CharName like'" + a + "%'",
ConfigurationManager.ConnectionStrings["DBVS"].ConnectionString);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
user_chk();
}
}
}
once again, thank you all kindly for reviewing my code. (I've commented out the line, it's just not visible unless you drag the bar, in the page load method.)
Obviously it can't find the connection string DBVS.
Check your web.config whether it exists.
Try this code to check for null on the connection:
ConnectionString connStr = ConfigurationManager.ConnectionStrings["DBVS"];
if (connStr == null)
{
throw new Exception("Cannot find connection string DBVS in web.config");
}
I have text and a button and when on submit, I am checking whether the database has any rows-if not then insert rows or else update them, but on submit its throwing an error saying incorrect syntax at "cmd.ExecuteNonQuery" in the else condition
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;
public partial class CM : System.Web.UI.Page
{
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlCommand cmd;
DataTable dt;
SqlConnection con = new SqlConnection("server =consulting76\\SQLEXPRESS; database = msdb; Integrated Security=True; MultipleActiveResultSets=True");
protected void Page_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("Select * from NOTESMAKER", con);
da.Fill(ds);
//dt = ds.Tables["NOTESMAKER"];
}
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
if (ds.Tables[0].Rows.Count == 0)
{
cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values(#text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}
else
{
cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = #text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
da.UpdateCommand = cmd;
cmd.ExecuteNonQuery();
}
con.Close();
}
}
You are closing a bracket on this line, which is never opened:
cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = #text1)",con);
Also, setting the InsertCommand and UpdateCommand properties of the data adapter isn't neccessary.
I want to bind a dropdownlist to a database. I did the following coding but it isn't working.
using System;
using System.Configuration;
using System.Data;
using System.Linq;
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.Odbc;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rebind();
}
}
public void rebind()
{
try
{
OdbcConnection myConn = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);
string sql = "select casename,casecode from casetype";
myConn.Open();
OdbcCommand cmd = new OdbcCommand(sql, myConn);
OdbcDataReader MyReader = cmd.ExecuteReader();
{
DropDownList3.DataSource= sql;
DropDownList3.DataTextField = "casename";
DropDownList3.DataValueField = "casetype";
DropDownList3.DataBind();
}
}
catch (Exception ex)
{
Response.Write(ex.StackTrace);
}
}
}
I am getting the error as
at _Default.rebind() in c:\Documents and Settings\a\My Documents\Visual Studio 2008\WebSites\toolbar1\Default.aspx.cs:line 32
Please help me to solve my problem and bind the dropdownlist to a datasource.I want my dropdownlist to display text from a database column and use the value field for some other purpose later on in code. I am getting the page displayed when i run the project but not able to get the data in dropdownlist
Did you try using DataAdapter like this?
public void rebind()
{
try
{
OdbcConnection myConn = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);
string sql = "select casename,casecode from casetype";
myConn.Open();
OdbcCommand cmd = new OdbcCommand(sql, myConn);
OdbcDataAdapter adapter = new OdbcDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
DropDownList3.DataSource = dt;
DropDownList3.DataTextField = "casename";
DropDownList3.DataValueField = "casecode";
DropDownList3.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.StackTrace);
}
}
try following code....it will surely work....
first define ConnectionString in web.config inside
protected void Page_Load(object sender, EventArgs e)
{
string strconnection = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(strconnection);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select ename,ecompany from example";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "example");
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "ename";
DropDownList1.DataValueField = "ecompany";
DropDownList1.DataBind();
}
You are setting the string of sql to the datasource, not a data structure.
read out your objects into a list or Ilist sub type.
Then bind that to the drop down.
List<CaseType> ct = new List<CaseType>();
try
{
OdbcConnection myConn = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);
string sql = "select casename,casecode from casetype";
myConn.Open();
OdbcCommand cmd = new OdbcCommand(sql, myConn);
OdbcDataReader MyReader = cmd.ExecuteReader();
while(MyReader.ReadNext()){
ct.Add(new CaseType(){Name = MyReader.Read("casename").ToString(), Type = Convert.ToInt32(MyReader.Read("casetype"))});
}
}
catch (Exception ex)
{
Response.Write(ex.StackTrace);
}
Its been a long time since I've done anything this metal with ado. However it should be more like that in the reader part.
Then the binding afterwards.
DropDownList3.DataSource= ct;
DropDownList3.DataTextField = "Name";
DropDownList3.DataValueField = "Type";
DropDownList3.DataBind();
Your query is querying columns casename,casecode
string sql = "select casename,casecode from casetype";
Edit -
But, while binding you are binding different columns to your datatextfield and datavaluefields.
You are using the sql string variable as the datasource. You should be using your datareader instead.
Try using -
DropDownList3.DataSource= MyReader;
DropDownList3.DataTextField = "casename";
DropDownList3.DataValueField = "casecode";