StackOverflowException was unhandled. I need help on this. I get the error on the line
adp.Fill(ds)
Also I'm not sure why, but I can't remove throw, it says not all codes returning a value.
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbCustConn"].ToString();
string cmdStr = "Select * from MainDB";
public DAL() // default parameter. Use?
{
}
public DataTable Load() // what is this for? (loads all the records from the database)
{
SqlConnection conn = new SqlConnection(connStr);
//SqlCommand cmd = new SqlCommand(cmdStr, connStr);
SqlDataAdapter adp = new SqlDataAdapter(cmdStr, connStr); // SqlDataAdapater? Load all?
DataSet ds = new DataSet();
try
{
adp.Fill(ds);
return ds.Tables[0];
}
catch
{
throw;
}
finally
{
ds.Dispose();
adp.Dispose();
conn.Close();
conn.Dispose();
}
}
public DataTable Load() // what is this for? (loads all the records from the database)
{
SqlDataAdapter adp = new SqlDataAdapter(cmdStr, connStr); // SqlDataAdapater? Load all?
DataSet ds = new DataSet();
using(SqlConnection conn = new SqlConnection(connStr))
{
adp.Fill(ds);
return ds.Tables[0];
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
MasterCust.DataSource = GridDataSource();
MasterCust.DataBind();
//DetailCust.DataSource = ds2;
//DetailCust.DataBind();
}
private DataTable GridDataSource()
{
BAL p = new BAL();
DataTable dTable = new DataTable();
try
{
dTable = p.Load();
}
catch (StackOverflowException ee)
{
string message = ee.Message.ToString();
}
finally
{
p = null;
}
return dTable;
}
First, I think the issue is probably in MasterCust. I think that however that is defined may be causing your issues. If you update your question on how this is defined, that may shed some additional light.
Second, you have a lot of extraneous code that could be confusing the issue. Here is what I think that you need to do to pare it down the bare minimum:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
BindGrid();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
// Note that this is for debug purposes only. Production code should log
// this exception somewhere so that it can be observed and dealt with
}
}
private void BindGrid()
{
MasterCust.DataSource = BAL.Load();
MasterCust.DataBind();
}
Then your business access class:
public class BAL
{
private static string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbCustConn"].ToString();
private static string cmdStr = "Select * from MainDB";
public static DataTable Load() // what is this for? (loads all the records from the database)
{
using (var adp = new SqlDataAdapter(cmdStr, connStr))
{
var ds = new DataSet();
adp.Fill(ds);
return ds.Tables[0];
}
}
}
Related
Thanks, i need some help, and theres error for DBOperation dbo = new DBOperation(); which they say type or namespace cannot be found.
public partial class Survey : System.Web.UI.Page
{
public DataTable fillmydropdownlist()
{
DataTable drpdt = new DataTable();
SqlConnection con= new SqlConnection();
try
{
con.ConnectionString = #"SurveyFdBk_DB";
con.Open();
string q = "SELECT * FROM [Survey]";
SqlCommand cmd = new SqlCommand(q,con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
return drpdt;
}
catch { }
finally{ con.Close(); }
}
protected void Page_Load(object sender, EventArgs e)
{
DBOperation dbo = new DBOperation();
DataTable dt = new DataTable();
dt = dbo.fillmydropdownlist();
DataTable drpdt= new DataTable();
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource = drpdt;
DropDownList1.DataTextField="SurveyName";
DropDownList1.DataValueField="SurveyID";
DropDownList1.DataBind();
}
}
}
All the paths of execution must return something. In your method above there are 2 paths:
public DataTable fillmydropdownlist()
{
try
{
//path 1
return drpdt;
}
catch
{
//path 2
return null; //need return value here
}
}
In the event of an exception being thrown you need to return some sort of value, perhaps null?
That being said catching all errors with no logging or handling is not an advisable practice. You should consider adding some error handling and you should dispose of your DataAdapter in your finally block as well.
I'm new in C#. I'm trying to query an *.accdb database, but having 0 row in response and datagrid stays clear. Query works from MS Access. What's wrong?
Main form class
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
OleDbConnection database;
public Form1()
{
InitializeComponent();
}
private void filterButton_Click(object sender, EventArgs e)
{
MessageBox.Show(nameFilter.Text);
InitializeComponent();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\qwe.accdb;";
try
{
database = new OleDbConnection(connectionString);
database.Open();
string queryString = "SELECT id FROM table1";
loadDataGrid(queryString);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
public void loadDataGrid(string sqlQueryString) {
OleDbCommand comm = new OleDbCommand();
comm.CommandText = sqlQueryString;
comm.CommandType = CommandType.Text;
comm.Connection = database;
Int32 returnValue = comm.ExecuteNonQuery();
MessageBox.Show(returnValue.ToString());
OleDbCommand SQLQuery = new OleDbCommand();
DataTable data = null;
dataGridView1.DataSource = null;
SQLQuery.Connection = null;
OleDbDataAdapter dataAdapter = null;
dataGridView1.Columns.Clear(); // <-- clear columns
SQLQuery.CommandText = sqlQueryString;
SQLQuery.Connection = database;
data = new DataTable();
dataAdapter = new OleDbDataAdapter(SQLQuery);
dataAdapter.Fill(data);
dataGridView1.DataSource = data;
MessageBox.Show(data.ToString());
dataGridView1.AllowUserToAddRows = false; // <-- remove the null line
dataGridView1.ReadOnly = true; // <-- so the user cannot type
}
}
}
Why not something along the lines of:
private void filterButton_Click(object sender, EventArgs e)
{
dataGridView1.Columns.Clear();
MessageBox.Show(nameFilter.Text);
InitializeComponent();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\qwe.accdb;";
try
{
using (DataTable dt = new DataTable())
{
using (OleDbDataAdapter da = new OleDbDataAdapter(new SqlCommand("SELECT id FROM table1",new OleDbConnection(connectionString))))
{
da.Fill(dt);
MessageBox.Show(dt.Rows.Count.ToString());
dataGridView1.DataSource = dt;
dataGridView1.Update();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
I have a form in ASP.NET that loads data if it exists for the user, and then allows them to update. So in Page_Load I have:
protected void Page_Load(object sender, EventArgs e)
{
if (!CheckAndAddRecord(_currentUser.UserID))
{
CreateEntryPoint(_currentUser.UserID);
}
else
{
DataView dv = LoadApplicationData(_currentUser.UserID);
foreach (DataRowView rowView in dv)
{
DataRow row = rowView.Row;
_applicationId = row["id"].ToString();
txtProjectNumber.Text = row["ProjectNumber"].ToString();
if (String.IsNullOrEmpty(chkSignedNDANo.ToString()) || String.IsNullOrEmpty(chkSignedNDAYes.ToString()))
{
chkSignedNDANo.Checked = Convert.ToBoolean(row["SignedNDAOnFile"]);
chkSignedNDAYes.Checked = Convert.ToBoolean(row["SignedNDAOnFile"]);
}
txtDateWritten.Text = row["DateWritten"].ToString();
}
}
}
It calls this method:
public bool CheckAndAddRecord(int UserId)
{
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("CheckUserInTemp", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#SubmittedBy", UserId));
SqlDataAdapter dap = new System.Data.SqlClient.SqlDataAdapter(cmd);
DataSet ds = new DataSet();
// open conn
if (conn.State == ConnectionState.Closed)
conn.Open();
// fill
dap.Fill(ds);
// close the conn
if (conn.State == ConnectionState.Open)
conn.Close();
bool boolRecordExist = false;
if (ds.Tables[0].DefaultView.Count == 0)
{
boolRecordExist = false;
}
else
{
boolRecordExist = true;
}
return boolRecordExist;
}
This seems to work and populate the fields correctly. But then to update I call a Button click, which calls this method:
public void UpdateRecordInTemp(int appId, string projectNumber)
{
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("CPC_ProposalUpdateTemp", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", appId);
cmd.Parameters.AddWithValue("#ProjectNumber", txtProjectNumber.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception("Exception adding coupon. " + ex.Message);
}
finally
{
conn.Close();
}
}
The problem is the fields passed always contain the old values. So if the value when entering the page is "123" and I change it to "abc" and click the button, "123" is passed instead of "abc".
Sorry for the long post, I wanted to get all the details in. I am baffled by this. Thanks!
At page Load check IsPostBack property in if. It seems that your code is executing on every page load.
if(!IsPostBack)
{
// Do your work
}
UPDATE
In your code method UpdateRecordInTemp(int appId, string projectNumber) you are not using projectNumber instead you are using txtProjectNumber.Text
I have a homework about database connection via ms access.
I prepared my database and saved it as dbMert and put it to debug / bin
This is my CustomerDatabase class for connecting to database:
static class CustomerDatabase
{
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dbMert.mdb";
static OleDbConnection connection = null;
static OleDbCommand command = null;
public static void ConnectToDatabase()
{
if (connection == null)
{
connection = new OleDbConnection(connectionstring);
command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from Customer";
}
}
public static DataTable executeSelect(string sql)
{
ConnectToDatabase();
DataTable dt = null;
dt = new DataTable();
command.CommandText = sql;
OpenConnection();
OleDbDataReader datareader = command.ExecuteReader();
dt.Load(datareader);
datareader.Close();
CloseConnection();
return dt;
}
public static void OpenConnection()
{
try
{
if (connection != null)
{
connection.Open();
}
}
catch (Exception ex)
{
}
}
public static void CloseConnection()
{
if (connection != null)
{
connection.Close();
}
}
}
}
Form: In constructor i try to connect to database
public Form1()
{
InitializeComponent();
CustomerDatabase.ConnectToDatabase();
}
and in form's load i try to take tuples to datagridview but nothing happens :S
private void Form1_Load(object sender, EventArgs e)
{
string sql1 = "select * from Customer";
DataTable dt = CustomerDatabase.executeSelect(sql1);
}
Regardless of other things (such as not keeping a single connection open, using using statements etc) you're not connecting your newly-loaded DataTable to your DataGridView at all. Your Form1_Load method just loads the data into a DataTable, then effectively throws it away.
I suspect you want something like:
dataGridView.DataSource = dt;
at the end of the method.
EDIT: Note that this is also a really bad idea in your OpenConnection code:
catch (Exception ex)
{
}
That basically says, "If something goes wrong, don't bother recording that fact or changing how the rest of the code works - just keep going as if nothing had happened."
Why are you catching the exception at all?
Try to write simple code. I suggest you to use OleDbDataAdaper, its Fill() method populate the DataTable easily.
You may use |DataDirectory| if you are using database (.mdb) located under Bin\Debug folder.
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=|DataDirectory|\dbMert.mdb";
Or
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=x:\full_path\dbMert.mdb";
Or
static string connectionstring = #"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=x:\full_path\dbMert.mdb";
static class Test
{
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dbMert.mdb";
public static DataTable executeSelect(string sql)
{
DataTable dt = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql,connectionString);
adapter.Fill(dt);
return dt;
}
}
Add following code in form_load handler,
string sql1 = "select * from Customer";
DataTable dt = Test.executeSelect(sql1);
DataGridView1.DataSource=dt;
When I move the DB-file to bin/debug, an error message states "4.0 is not installed".
However, when I move it to bin, the problem is solved.
My code:
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source= ..\\dbMert.mdb";
con.Open();
recordları
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
OleDbDataAdapter da = new OleDbDataAdapter();
da = new OleDbDataAdapter("Select * from Customer", con);
da.Fill(dt);
dataGridView1.DataSource = dt;
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
if(col.ToString() == "emailAdress")
comboBox1.Items.Add(row[col]);
}
con.Close();
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
Following is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Eventmanagement
{
public partial class Registration : Form
{
SqlConnection aConnection;
SqlDataAdapter da = new SqlDataAdapter();
DataTable dta;
public Registration()
{
InitializeComponent();
}
//--------------------------------------------//
private void Registration_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'insertEventDataSet.Events' table. You can move, or remove it, as needed.
populateEventSalesPersonList();
populateEventNameIdTypeList();
//+++++++++++++++++++++++++++++++++++++++++++//
txtSalesTaxRate_Registration.Text = Convert.ToString( SalesTaxRate() +"%");
//+++++++++++++++++++++++++++++++++++++++++++//
txtSalesTax_Registration.Text = Convert.ToString(saleTax());
txtTotalCharges_Registration.Text = Convert.ToString(totalCharges());
txtAmountDue_Registration.Text = Convert.ToString(amountDue());
//+++++++++++++++++++++++++++++++++++++++++++//
}
//--------------------------------------------//
public string getConnectionString()
{
try
{
string sConnection = "";
// Get the mapped configuration file.
System.Configuration.ConnectionStringSettingsCollection ConnSettings = ConfigurationManager.ConnectionStrings;
sConnection = ConnSettings["DBConnectionString"].ToString();
return sConnection;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return "";
}
}
//--------------------------------------------//
public void populateEventNameIdTypeList()
{
try
{
cmbEvent_Registration.DataSource = getDataTable4();
//----------------------------
cmbEvent_Registration.ValueMember = "EventID";
cmbEvent_Registration.DisplayMember = "EventName";
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//--------------------------------------------//
public void populateEventSalesPersonList()
{
try
{
cmbSalesPerson_Registration.DataSource = getDataTable5();
cmbSalesPerson_Registration.ValueMember = "EmployeeID";
cmbSalesPerson_Registration.DisplayMember = "SalesPerson";
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//-------------------------------------------//
public void populateFeeScheduleByEventList()
{
try
{
cmbFeeSchedule_Registration.DataSource = getDataTable6();
cmbFeeSchedule_Registration.ValueMember = "FeeScheduleID";
cmbFeeSchedule_Registration.DisplayMember = "Fee";
cmbFeeSchedule_Registration.Text = cmbFeeSchedule_Registration.SelectedText.ToString();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//------------------------------------------//
//------------------------------------------//
private void btnclose_Registration_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnInsert_Registration_Click(object sender, EventArgs e)
{
try
{
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
//Calling the Stored Procedure
da.InsertCommand = new SqlCommand("RegistrationInsert", aConnection);
da.InsertCommand.CommandType = CommandType.StoredProcedure;
da.InsertCommand.Parameters.Add(#"RegistrationDate", SqlDbType.SmallDateTime).Value = Convert.ToDateTime(txtRegistrationDate_Registration.Text.ToString());
da.InsertCommand.Parameters.Add(#"PurchaseOrderNumber", SqlDbType.VarChar).Value = txtPoNumber_Registration.Text;
da.InsertCommand.Parameters.Add(#"SalesPerson", SqlDbType.Int).Value = Convert.ToInt64(cmbSalesPerson_Registration.SelectedValue.ToString());
da.InsertCommand.Parameters.Add(#"EventID", SqlDbType.Int).Value = cmbEvent_Registration.SelectedValue.ToString();
da.InsertCommand.Parameters.Add(#"FeeScheduleID", SqlDbType.Int).Value = cmbFeeSchedule_Registration.SelectedValue.ToString();
da.InsertCommand.Parameters.Add(#"RegistrationFee", SqlDbType.Money).Value = txtRegistrationFee_Registration.Text;
da.InsertCommand.Parameters.Add(#"SalesTaxRate", SqlDbType.Float).Value = txtSalesTaxRate_Registration.Text;
//da.InsertCommand.Parameters.Add(#"EndTime", SqlDbType.SmallDateTime).Value = Convert.ToDateTime(txtEndTime.Text.ToString());
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Inserted successfully!!!");
aConnection.Close();
da.InsertCommand.Dispose();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//-------------------------------------------//
public DataTable getDataTable4()
{
try
{
dta = new DataTable();
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("EventsSelectAll", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
da.Fill(dta);
aConnection.Close();
return dta;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return null;
}
}
public DataTable getDataTable5()
{
try
{
dta = new DataTable();
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("sp_RegistrationSalesPerson", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
dta.Clear();
da.Fill(dta);
aConnection.Close();
return dta;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return null;
}
}
public DataTable getDataTable6()
{
try
{
dta = new DataTable();
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
da.SelectCommand = new SqlCommand("sp_FeeScheduleSelectAllByEventID", aConnection);
da.SelectCommand.Parameters.Add("EventID", SqlDbType.Int).Value = Convert.ToInt32(cmbEvent_Registration.SelectedValue.ToString());
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
da.Fill(dta);
aConnection.Close();
return dta;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return null;
}
}
private void cmbEvent_Registration_SelectedIndexChanged(object sender, EventArgs e)
{
populateFeeScheduleByEventList();
txtRemainingSeats_Registration.Text = Convert.ToString(spaces());
}
private void cmbFeeSchedule_Registration_SelectedIndexChanged(object sender, EventArgs e)
{
txtRegistrationFee_Registration.Text = cmbFeeSchedule_Registration.Text.ToString();
}
public int totalRegisteredAttendees()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("RegistrationSelectAllByEventID", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("EventID", SqlDbType.Int).Value = Convert.ToInt32(cmbEvent_Registration.SelectedValue.ToString());
aConnection.Open();
int val = (int)da.SelectCommand.ExecuteScalar();
aConnection.Close();
return val;
}
public int spaces()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("EventsSelect", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("EventID", SqlDbType.Int).Value = Convert.ToInt32(cmbEvent_Registration.SelectedValue.ToString());
// MessageBox.Show(cmbEvent_Registration.SelectedValue.ToString());
aConnection.Open();
int spaces = Convert.ToInt16(da.SelectCommand.ExecuteScalar());
aConnection.Close();
int value = totalRegisteredAttendees();
int totalspaces = spaces - value;
return totalspaces;
}
public double SalesTaxRate()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("CompanyInfo", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
aConnection.Open();
double sale = Convert.ToDouble(da.SelectCommand.ExecuteScalar());
aConnection.Close();
return sale;
}
public void updateSaleTax()
{
}
public double saleTax()
{
double regFee = Convert.ToDouble(txtRegistrationFee_Registration.Text.ToString());
double sTR = Convert.ToDouble(SalesTaxRate());
double sr = regFee * (sTR / 100);
return sr;
}
public double totalCharges()
{
double tc = Convert.ToDouble(txtRegistrationFee_Registration.Text.ToString()) + (saleTax());
return tc;
}
public double amountDue()
{
double aD;
if (txtTotalPaid_Registration.Text == string.Empty)
{
aD = Convert.ToDouble(txtTotalCharges_Registration.Text.ToString());
}
else
{
double a = Convert.ToDouble(txtTotalPaid_Registration.Text.ToString());
double b= (Convert.ToDouble(txtTotalCharges_Registration.Text.ToString()));
aD = b-a;
}
return aD;
}
private void txtSalesTaxRate_Registration_TextChanged(object sender, EventArgs e)
{
}
private void gpRegistraton_Enter(object sender, EventArgs e)
{
}
}
}
I want saleTax to update when
txtRegistrationFee_Registration.Text.ToString()
changes, so basically I want to reconnect the whole thing. Please Help.
You could hook up your txtRegistrationFee_Registration with a TextChanged event. The event handler can call saleTax().
Long time since I last worked in Winforms. But doesn't textbox provide TextChange event? Maybe that event has different name. But there must be event that fires whenever You change text.
And when You want to get data from textbox it's just textbox.Text. You don't need to call textbox.Text.ToString(). Text is already a string.