C# Why are my variables not carrying over properly between forms? - c#

I've got several forms, some of which rely on information between each form. In this case, the selected index of the chosen option in Form 2 (AKA testSelect) is key to determining what will happen in Form 3 (AKA testPresent). This is placed into an integer called index. Upon closing form 2 the value of index is definitely whatever the selectedindex of the listbox is.
However upon opening and applying it in form 3 it resets to 0 all the time, and I can't figure out why. below is the code where index is used/determined in form 2 as well as the code where it is called in form 3. Also, it is a public int defined at the start of form 2;
private void lstExams_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//Create a connection object to the DB via string location
con = new OleDbConnection(connectionString);
//Open the connection to the DB
con.Open();
String sql = "SELECT typeID, description FROM TestConfiguration WHERE examID = " +(lstExams.SelectedIndex +1);
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
//DataSet ds = new DataSet();
DataTable testConfig = new DataTable();
//Set the SQL command text
da.Fill(testConfig);
lstTestType.DisplayMember = "description";
lstTestType.ValueMember = "typeID";
lstTestType.DataSource = testConfig;
index = lstExams.SelectedIndex + 1;
MessageBox.Show("INDEX = " + index);
}
catch (Exception err)
{
//If cannot connect to DB, display the error;
MessageBox.Show("A Database error has occurred: " + Environment.NewLine + err.Message);
}
}
private void btnStart_Click(object sender, EventArgs e)
{
//var testPresent = new testPresent(this);
testPresent testForm = new testPresent();
testForm.Show();
//testForm.difficulty = lstTestType.ValueMember;
this.Close();
MessageBox.Show("INDEX IS " + index);
testForm.eID = (index);
}
And for form 3
public partial class testPresent : Form
{
public int eID = 0;
public String difficulty;
testSelect select = new testSelect();
//Get the connection path to the DB from the static class
String connectionString = staticConnectionString.connectionString;
//Declare connection object
OleDbConnection con;
public testPresent()
{
InitializeComponent();
}
public void testPresent_Load(object sender, EventArgs e)
{
try
{
int qID;
Random random = new Random();
int examID;
bool valid = false;
String theQuestion;
eID += select.index;
//Create a connection object to the DB via string location
con = new OleDbConnection(connectionString);
//Open the connection to the DB
con.Open();
MessageBox.Show("eID = " + select.index);
if (eID == 1)
{
...
}
if (eID == 2)
{
...
}
if (eID == 3)
{
...
}
}
catch (Exception err)
{
//If cannot connect to DB, display the error;
MessageBox.Show("A Database error has occurred: " + Environment.NewLine + err.Message);
}
}
Oh yeah, this also uses Microsoft Access Databases to populate the listbox.

You set the value:
testForm.eID = (index);
But you do so after the form has already been loaded, so testPresent_Load has already used its default value:
testPresent testForm = new testPresent();
testForm.Show(); // this is where it uses the value
// ...
testForm.eID = (index); // this is where you set it
If the value is required for the testPresent form entirely, and it needs the value right away, try including the value in the constructor:
public testPresent(int eid)
{
InitializeComponent();
eID = eid;
}
Then when you create an instance of the form you'd have to pass it that value:
testPresent testForm = new testPresent(index);
testForm.Show();
At that point there'd be no need to set the value externally, so it should be private. (Data members should be private on objects anyway.):
private int eID;

Related

Databinding not updating database until after move to previous or next record

Creating a project for school, I have a form with some user controls.
3 textboxes a checkbox and 2 buttons for navigating through the records.
When I change the text on one of the textboxes, the data will only reflect to the database when I click the "Next" or "Prev" button.
public partial class Navigeren : UserControl
{
private readonly SqLiteDataAccess _sqLiteDataAccess;
private Timer _saveTimer;
private DataViewManager _dsView;
public Navigeren()
{
InitializeComponent();
_sqLiteDataAccess = new SqLiteDataAccess();
DataBinding();
_saveTimer = new Timer {Interval = 1000};
_saveTimer.Tick += _saveTimer_Tick;
_saveTimer.Start();
}
private void _saveTimer_Tick(object sender, EventArgs e)
{
_sqLiteDataAccess.UpdatePersonen(_dsView.DataSet);
// Tried using SqLiteDataAccess.PersonenDataSet gives me the same result.
}
private void DataBinding()
{
_dsView = SqLiteDataAccess.PersonenDataSet.DefaultViewManager;
textId.DataBindings.Add("Text", _dsView, "Personen.id", false, DataSourceUpdateMode.OnPropertyChanged);
textNaam.DataBindings.Add("Text", _dsView, "Personen.name", false, DataSourceUpdateMode.OnPropertyChanged);
textAdres.DataBindings.Add("Text", _dsView, "Personen.adres", false, DataSourceUpdateMode.OnPropertyChanged);
checkGehuwd.DataBindings.Add("Checked", _dsView, "Personen.gehuwd", false, DataSourceUpdateMode.OnPropertyChanged);
}
private void buttonNext_Click(object sender, EventArgs e)
{
CurrencyManager cm = (CurrencyManager)this.BindingContext[_dsView, "Personen"];
if (cm.Position < cm.Count - 1)
{
cm.Position++;
}
}
private void buttonPrev_Click(object sender, EventArgs e)
{
if (this.BindingContext[_dsView, "Personen"].Position > 0)
{
this.BindingContext[_dsView, "Personen"].Position--;
}
}
}
Sorry for my english.
Greetings Andy
EDIT:
SQLiteDataAccess:
class SqLiteDataAccess
{
private SQLiteConnection _sqliteconnection;
private string _database = #"Database.sqlite";
private static DataSet _personenDataSet;
public static DataSet PersonenDataSet
{
get { return _personenDataSet; }
set { _personenDataSet = value; }
}
public SqLiteDataAccess()
{
OpenConnection();
CreateTable();
CreateTableGeslachten();
CreateTableLanden();
FillDataSet();
}
private void OpenConnection()
{
if (!File.Exists(_database))
SQLiteConnection.CreateFile(_database);
_sqliteconnection = new SQLiteConnection("Data Source=" + _database + ";Version=3;");
_sqliteconnection.Open();
}
private void CreateTable()
{
try
{
string sql = "CREATE TABLE Personen (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name VARCHAR, " +
"adres VARCHAR, " +
"gehuwd INT, " +
"land INT, " +
"geslacht INT, " +
"telnr VARCHAR, " +
"studies VARCHAR, " +
"geboorteDatum DATETIME, " +
"foto BLOB)";
SQLiteCommand command = new SQLiteCommand(sql, _sqliteconnection);
command.ExecuteNonQuery();
}
catch (SQLiteException sle)
{
}
}
private void CreateTableGeslachten()
{
try
{
string sql = "CREATE TABLE Geslachten (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"geslacht TEXT," +
"FOREIGN KEY(id) REFERENCES Personen(geslacht));";
SQLiteCommand command = new SQLiteCommand(sql, _sqliteconnection);
command.ExecuteNonQuery();
InsertTableGeslachten();
}
catch (SQLiteException sle)
{
}
}
private void InsertTableGeslachten()
{
string sql = "INSERT INTO Geslachten(geslacht) VALUES('Man'), ('Vrouw');";
SQLiteCommand command = new SQLiteCommand(sql, _sqliteconnection);
command.ExecuteNonQuery();
}
private void CreateTableLanden()
{
try
{
string sql = "CREATE TABLE Landen (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"land TEXT," +
"FOREIGN KEY(id) REFERENCES Personen(land));";
SQLiteCommand command = new SQLiteCommand(sql, _sqliteconnection);
command.ExecuteNonQuery();
InsertTableLanden();
}
catch (SQLiteException sle)
{
}
}
public void Insert(string name, string adres, bool gehuwd, int land, int geslacht, string telnr, string studies,
string geboorteDatum, byte[] foto)
{
var sql =
new StringBuilder(
"insert into Personen (name, adres, gehuwd, land, geslacht, telnr, studies, geboorteDatum) values ('");
sql.Append(name).Append("','")
.Append(adres).Append("','")
.Append(Convert.ToInt32(gehuwd)).Append("','")
.Append(land).Append("','")
.Append(geslacht).Append("','")
.Append(telnr).Append("','")
.Append(studies).Append("','")
.Append(geboorteDatum).Append("');");
// .Append(foto).Append(");");
SQLiteCommand command = new SQLiteCommand(sql.ToString(), _sqliteconnection);
command.ExecuteNonQuery();
}
public void FillDataSet()
{
SqLiteDataAccess.PersonenDataSet = new DataSet();
try
{
string query = "select * from Personen";
SQLiteDataAdapter da = new SQLiteDataAdapter(query, _sqliteconnection);
da.Fill(PersonenDataSet, "Personen");
string query2 = "select id, geslacht from geslachten";
SQLiteDataAdapter da2 = new SQLiteDataAdapter(query2, _sqliteconnection);
da2.Fill(PersonenDataSet, "Geslachten");
string query3 = "select id, land from Landen";
SQLiteDataAdapter da3 = new SQLiteDataAdapter(query3, _sqliteconnection);
da3.Fill(PersonenDataSet, "Landen");
}
catch (Exception ex)
{
}
}
public void UpdatePersonen(DataSet ds)
{
try
{
string query = "select * from Personen";
SQLiteDataAdapter da = new SQLiteDataAdapter(query, _sqliteconnection);
SQLiteCommandBuilder sqLiteCommandBuilder = new SQLiteCommandBuilder(da);
da.Update(ds, "Personen");
}
catch (Exception ex)
{
MessageBox.Show("Test");
}
}
You don't need to change the position, you just need to call EndCurrentEdit method of the BindingManagerBase before save:
this.BindingContext[datasource, "datamember"].EndCurrentEdit();
Some Notes
Use BindingSource.
I recommend using a BindingSource component as data source which you want to use for data-binding. Then set the DataSource and DataMember of the BindingSource to the values which you want:
It enables you to perform data-binding at design time.
It enables you to use its methods and properties to navigation, add, remove and so on.
You can use it's sorting and filtering properties.
Use BindingNavigator.
Also use BindingNavigator control as a navigation toolbar. It's enough to set its BindingSource property to the BindingSource component which you used for data-binding, then its navigation button will do the job of navigation for you.
Also take a look at:
Why do I need to change the Binding Source Position before I can SaveChanges
Describes why changing position also does the trick.
Equivalent of MoveNext in VB.NET
Shows you how to create a rapid data application using designer features, data-binding, BindingSource and BindingNavigator using drag and drop. Also it share some useful links about these features.

DataSet not updated with new row inserted in C#

i am trying to insert new row in Emp table in c# (disconnected mode), the new row successfully inserted but the dataset not updated, so when i search for the new row, i don't find it, but when i search for an old row, i find it.
the insertBTN button used to insert new row
the searchByID button used to search for row by its ID
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SqlConnection conn;
private SqlDataAdapter adapter;
private DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
conn = new SqlConnection(#"data source=(local);initial catalog =Test;integrated security = true");
conn.Open();
adapter = new SqlDataAdapter("select * from Emp",conn);
ds = new DataSet();
adapter.Fill(ds,"Emp");
}
private void insertBTN_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
string name = textBox2.Text;
string address = textBox3.Text;
int age = int.Parse(textBox4.Text);
int salary = int.Parse(textBox5.Text);
SqlCommand command = new SqlCommand("Insert into Emp values(" + id + ",'" + name + "','" + address + "'," + age + "," + salary + ")", conn);
command.ExecuteNonQuery();
adapter.Update(ds,"Emp");
MessageBox.Show("Employee added successfully");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void searchByID_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
foreach (DataRow row in ds.Tables["Emp"].Rows)
{
if (Convert.ToInt32(row["id"]) == id)
{
textBox2.Text = Convert.ToString(row["name"]);
textBox3.Text = Convert.ToString(row["address"]);
textBox4.Text = Convert.ToString(row["age"]);
textBox5.Text = Convert.ToString(row["salary"]);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The Update method of the DataAdapter doesn't read again but tries to execute the INSERT, DELETE and UPDATE commands derived from the original SELECT statement against the Rows in the DataTable that have their RowState changed
So, if you want to use the Update method of the adapter you could write
private void insertBTN_Click(object sender, EventArgs e)
{
try
{
DataRow row = ds.Tables["emp"].NewRow();
row.SetField<int>("id", int.Parse(textBox1.Text));
row.SetField<string>("name", textBox2.Text));
row.SetField<string>("address", textBox3.Text));
row.SetField<int>("age", int.Parse(textBox4.Text));
row.SetField<int>("salary", int.Parse(textBox5.Text));
ds.Tables["emp"].Rows.Add(row);
adapter.Update(ds,"Emp");
MessageBox.Show("Employee added successfully");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
At this point your DataSet contains the added row because you have added it manually and then passed everything to the Update method to write it to the database.
However, keep in mind that the Update method to work requires certain conditions to be present. You could read them in the DbDataAdapter.Update page on MSDN.
Mainly you need to have retrieved the primary key of the table, do not have more than one table joined together and you have used the DbCommandBuilder object to create the required commands (Again the example in the MSDN page explain it)
Not related to your question, but you could change your search method and avoid writing a loop to search for the ID
private void searchByID_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
DataRow[] foundList = ds.Tables["Emp"].Select("Id = " + id);
if(foundList.Length > 0)
{
textBox2.Text = foundList[0].Field<string>("name");
textBox3.Text = foundList[0].Field<string>("address");
textBox4.Text = foundList[0].Field<int>("age").ToString();
textBox5.Text = foundList[0].Field<int>("salary").ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

is it possible to change the position of the blank row at the end of the datagridview?

I want to allow user to add rows but the blank row must be in he first position to let the user enter data without scroll down each time to insert a new row ?!
This is how I add the rows in the datagridview :
using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Windows.Forms;
namespace Parc_Automobile
{
public class SqlHelper
{
private const string ConnectionString =
"Data Source=KIM;Initial Catalog=TestingBlank;Integrated Security=True";
private readonly DataGridView _dgv;
private BindingSource _bindingSource;
private DataTable _dataTable;
private string _selectQueryString;
private SqlConnection _sqlConnection;
private SqlDataAdapter _sqlDataAdapter;
protected SqlHelper(DataGridView dgv)
{
_dgv = dgv;
}
//display a table in datagridview
public void ShowTable(String tableName)
{
_sqlConnection = new SqlConnection(ConnectionString);
_sqlConnection.Open();
_selectQueryString = "SELECT * FROM " + tableName;
_sqlDataAdapter = new SqlDataAdapter(_selectQueryString, _sqlConnection);
var sqlCommandBuilder = new SqlCommandBuilder(_sqlDataAdapter);
_dataTable = new DataTable();
_sqlDataAdapter.Fill(_dataTable);
_bindingSource = new BindingSource {DataSource = _dataTable};
var tempRow = this._dataTable.NewRow();
this._dataTable.Rows.InsertAt(tempRow, 0);
_dgv.DataSource = _bindingSource;
_sqlConnection.Close();
}
//Search In datagridview using input of users
public void SearchTable(String SearchText, String columnNameToSearch, int type)
{
try
{
var filterBuilder = "";
switch (type)
{
case TEXT_COLUMN:
filterBuilder = columnNameToSearch + " LIKE '" + SearchText + "%'";
break;
case NUMERIC_COLUMN:
filterBuilder = columnNameToSearch + " = '" + SearchText + "'";
break;
}
var bs = new BindingSource
{
DataSource = _dgv.DataSource,
Filter = filterBuilder
};
_dgv.DataSource = bs;
}
catch (Exception e)
{
// ignored
}
}
public void DeleteRow()
{
if (_dgv.CurrentRow != null) _dgv.Rows.RemoveAt(_dgv.CurrentRow.Index);
_sqlDataAdapter.Update(_dataTable);
}
public void SaveChanges(Label label)
{
try
{
_sqlDataAdapter.Update(_dataTable);
label.Text = "Changement a été effectué avec succès.";
}
catch (Exception e)
{
MessageBox.Show("" + e);
}
}
}
}
When you add a new row use the Insert method instead of Add. Insert allows to specify the index for the new row. Set the index to 0:
this.dataGridView1.Rows.Insert(0,new DataGridViewRow());
EDIT I
Adjusting the answer to your comment: if you are using a binding to a data source you have to create a new row using the data source. Then you insert it at specified position. Let's say that you have myDataSet data source with a Log table in it. This code will create a new row and insert it as the first row:
var tempRow = this.myDataSet.Log.NewRow();
this.myDataSet.Log.Rows.InsertAt(tempRow, 0);
Your DataGridView will be updated appropriately.
EDIT II
You will get exception if you try, for instance, to assign data type different than a column type in your table. Say the ID column is int but you try to add string. To handle data errors you have to handle the DataError event. Below an example using your code.
protected SqlHelper(DataGridView dgv)
{
_dgv = dgv;
_dgv.DataError += _dgv_DataError;
}
void _dgv_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
if (e.Exception != null)
{
MessageBox.Show(string.Format("Incorrect data: {0}", e.Exception.Message) );
e.Cancel = false;
// handle the exception
}
}

'xx' is inaccessible due to its protection level

I have this error studentHelperClass.Form1.cmbBox is inaccessible due to its protection level
for this part of my code
class studentHC : Form1
{
public studentHC()
{
InsertMethod();
}
private void InsertMethod()
{
MySqlConnection conn; // connection object;
string connstring =
"server=localhost;user Id=root;" +
"database=collegesystem;Convert Zero Datetime=True ";
conn = new MySqlConnection(connstring);
conn.Open();
using (var command = new MySqlCommand("SELECT * FROM person", conn))
{
using (var myReader = command.ExecuteReader())
{
cmbBox.Items.Add(myReader["personID"]);
}
}
}
internal static void insertMethod()
{
throw new NotImplementedException();
}
the above code is for a SELECT query to display the contents of a table called person
and this I have in my Form
public partial class Form1 : Form
{
MySqlConnection conn; // connection object;
string connstring =
"server=localhost;user Id=root;" +
"database=collegesystem;Convert Zero Datetime=True ";
public Form1()
{
InitializeComponent();
connection();
selectStudent();
}
private void selectStudent()
{
try
{
studentHelperClass.studentHC.insertMethod();
}
catch (Exception err)
{
lblInfo.Text = " Error reading the database.";
lblInfo.Text += err.Message;
}
}
How can I solve this error?
I believe that this is the last error before the program will work
EDIT:
this is thee only part of the code I didn't show you..and it has nothing to do with cmbBox :/
private void connection()
{
try
{
conn = new MySqlConnection(connstring); //make the connection object
conn.Open(); // try and open the connection
lblInfo.Text = " server version: " + conn.ServerVersion;
lblInfo.Text += "\n Connection is :" + conn.State.ToString();
}
catch (Exception err)
{
lblInfo.Text = " Error reading the database.";
lblInfo.Text += err.Message; ;
}
EDIT NUMBER 2:
private void InitializeComponent()
{
this.cmbBox = new System.Windows.Forms.ComboBox();
this.lblInfo = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// cmbBox
//
this.cmbBox.FormattingEnabled = true;
this.cmbBox.Location = new System.Drawing.Point(65, 9);
this.cmbBox.Name = "cmbBox";
this.cmbBox.Size = new System.Drawing.Size(121, 21);
this.cmbBox.TabIndex = 0;
I have to change that to public?
Ok so I used the properties window to change cmbBox to protected and that removed the error, but now my label for statuses on the database has given me this error after I ran the program, any idea why?
Error reading the database, method or operation is not implemented
I think you need to open auto generated partial class of Form1 and change cmbBox to protected. This can be done from the designer view also if you are using Visual Studio. This should solve the problem.
I suspect that cmbBox was declared as private (or maybe you didnt declare any protection level, and it defaults to private). If you can, please change it to be protected instead.
If you can't change it for some reason, try:
public partial class Form1 : Form
{
protected void AddPerson(Person p)
{
cmbBox.Items.Add(p);
}
}
and
class studentHC : Form1
{
public studentHC()
{
InsertMethod();
}
private void InsertMethod()
{
MySqlConnection conn; // connection object;
string connstring = "server=localhost;user Id=root;database=collegesystem;Convert Zero Datetime=True ";
conn = new MySqlConnection(connstring);
conn.Open();
using (var command = new MySqlCommand("SELECT * FROM person", conn))
{
using (var myReader = command.ExecuteReader())
{
AddPerson(myReader["personID"]);
}
}
}
}
If the ComboBox is created by IDE,most probably the ComboBox will have been declared Private.Try setting it to Protected under category Modifiers in the Properties Window.
Right click on the "cmbBox" object in the Form view. You need to set it's "Modifier" level to Public or Protected.

Dataset showing unexpected Data

I have 2 ListBoxes and five textBox. In ListBox_prod i want to retrieve all product (from PRODUCT table) and in Listbox_item i want to retrieve all Items corresponding to the selected Product (from PRODITEM table) on form load event. All the products have more than 1 items associated with them. Problem is with the Listbox_item as it is showing only 1 item. But I want all items to be displayed in Listbox_item when a particulat product is selected. getData() in class DBCommands actually causes the problem. Here's my code:
public partial class form_prodItems : Form
{
private DBCommands dBCommand;
public form_prodItems()
{
InitializeComponent();
listBx_prod.SelectedIndexChanged += new EventHandler(listBx_prod_selValChange);
listBx_item.SelectedIndexChanged += new EventHandler(listBx_item_selValChange);
}
private void form_prodItems_Load(object sender, EventArgs e)
{
// ...
refresh_listBx_prod("PRODUCT", this.listBx_prod, null, null);
refresh_listBx_prod("PRODITEM", this.listBx_item, listBx_prod.ValueMember, listBx_prod.SelectedValue.ToString());
}
private void listBx_item_selValChange(object sender, EventArgs e) // causing problem
{
if (listBx_item.SelectedValue != null)
showPrice("PRODITEM", listBx_item.ValueMember, listBx_item.SelectedValue.ToString());
}
private void listBx_prod_selValChange(object sender, EventArgs e)
{
if(listBx_prod.SelectedValue != null)
refresh_listBx_prod("PRODITEM", this.listBx_item, listBx_prod.ValueMember, listBx_prod.SelectedValue.ToString());
}
private void showPrice(string tblName,string where_column ,string where_val)
{
DataSet ds;
ds = dBCommand.getData("select * from " + tblName + " WHERE " + where_column + " = '" + where_val + "'");
DataRow col_val = ds.Tables[0].Rows[0];
txtBox_12oz.Text = col_val.ItemArray[3].ToString();
txtBox_16oz.Text = col_val.ItemArray[4].ToString();
txtBox_20oz.Text = col_val.ItemArray[5].ToString();
txtBox_1lbs.Text = col_val.ItemArray[6].ToString();
txtBox_2lbs.Text = col_val.ItemArray[7].ToString();
//ds.Clear();
}
private void refresh_listBx_prod(string tblName, ListBox listBox, string where_column, string where_val)
{
DataSet ds = new DataSet();
dBCommand = new DBCommands();
if (where_column == null)
{
ds = dBCommand.getData("SELECT * FROM " + tblName);
}
else
{
ds = dBCommand.getData("SELECT * FROM " + tblName + " WHERE " + where_column + " = " + where_val);
}
listBox.DataSource = ds.Tables[0];
// ds.Clear();
}
}
public class DBCommands
{
private SqlConnection conn;
private SqlDataAdapter dataAdapter;
private DataSet container;
public DataSet getData(string selectCmd)
{
container.Clear(); // I guess something needs to be fixed here some where..
conn = getConnection();
dataAdapter.SelectCommand = new SqlCommand(selectCmd, conn);
dataAdapter.Fill(container);
conn.Close();
return container;
}
private SqlConnection getConnection()
{
SqlConnection retConn = new SqlConnection("Data Source=" + Environment.MachineName + "; Initial Catalog=RESTAURANT; Integrated Security = TRUE");
retConn.Open();
return retConn;
}
}
Actually dataset flushes all data it had got from (SELECT * FROM PRODITEM where PRODUCT_id = '1') and shows data from the last executed query i-e (select * from proditem where item_id = 1)
Any suggestions..
my suggestion is trying to run the command via SqlCommand.
that way you will have better knowledge on what you get back.
use this example:
SqlCommand command = new SqlCommand(selectCmd, conn);
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
and modify it so you'll return a table as you need.
the reason i offer you this is that it's easy to use and you get immediate debug information that help you understand sql mistakes

Categories