Inherit Datatable object - c#

I'm working at a C# solution, and I've got this form which I'm populating my txtboxes, using a DataTable object and then retrieving the information trought the row number, the problem is, I've got navigation buttons, next and previous, and I just noticed that when I call my function to PopulateView(); after I press this buttons, I redo the DB connection, the SQLite query and the datatable fill.
I feel ashamed but, I really don't know where is the proper place to put this function in order that my other functions in this form receive these objects.
My Code:
namespace X_Project{
public partial class Cad_Prod : Form
{
System.Data.SQLite.SQLiteConnection conn1 = new System.Data.SQLite.SQLiteConnection("data source=X.s3db");
int prodstart = 0;
public Cad_Prod()
{
InitializeComponent();
}
public void Cad_Prod_Load(object sender, EventArgs e)
{
}
private void PopulateView()
{
string query = "SELECT * FROM Cad_Prod";
string query2 = "SELECT * FROM Cat";
try
{
using (SQLiteCommand comm = new SQLiteCommand(query, conn1))
using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(comm))
using (SQLiteCommand comm2 = new SQLiteCommand(query2, conn1))
using (SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(comm2))
{
conn1.Open();
DataTable produtos = new DataTable();
adapter.Fill(produtos);
DataTable categoria = new DataTable();
adapter2.Fill(categoria);
int auxCat = int.Parse(produtos.Rows[prodstart].ItemArray[4].ToString()) - 1;
txtProdutoNome.Text = produtos.Rows[prodstart].ItemArray[1].ToString();
txtProdutoPreco.Text = produtos.Rows[prodstart].ItemArray[2].ToString();
txtProdutoQtd.Text = produtos.Rows[prodstart].ItemArray[3].ToString();
cbbCategoria.Text = categoria.Rows[auxCat].ItemArray[1].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnAvancar_Click(object sender, EventArgs e)
{
prodstart = prodstart + 1;
PopulateView();
}
private void btnVoltar_Click(object sender, EventArgs e)
{
prodstart = prodstart - 1;
PopulateView();
}
}
the code above works, but no the way I want it, what i really would like to do is:
namespace X_Project\
{
public partial class Cad_Prod : Form
{
System.Data.SQLite.SQLiteConnection conn1 = new System.Data.SQLite.SQLiteConnection("data source=X.s3db");
int prodstart = 0;
public Cad_Prod()
{
InitializeComponent();
}
public void Cad_Prod_Load(object sender, EventArgs e)
{
string query = "SELECT * FROM Cad_Prod";
string query2 = "SELECT * FROM Cat";
try
{
using (SQLiteCommand comm = new SQLiteCommand(query, conn1))
using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(comm))
using (SQLiteCommand comm2 = new SQLiteCommand(query2, conn1))
using (SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(comm2))
{
conn1.Open();
DataTable produtos = new DataTable();
adapter.Fill(produtos); // I would like this to be inherited
DataTable categoria = new DataTable();
adapter2.Fill(categoria); // I would like this to be inherited
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void PopulateView()
{
int auxCat = int.Parse(produtos.Rows[prodstart].ItemArray[4].ToString()) - 1;
txtProdutoNome.Text = produtos.Rows[prodstart].ItemArray[1].ToString();
txtProdutoPreco.Text = produtos.Rows[prodstart].ItemArray[2].ToString();
txtProdutoQtd.Text = produtos.Rows[prodstart].ItemArray[3].ToString();
cbbCategoria.Text = categoria.Rows[auxCat].ItemArray[1].ToString();
}
private void btnAvancar_Click(object sender, EventArgs e)
{
prodstart = prodstart + 1;
PopulateView();
}
private void btnVoltar_Click(object sender, EventArgs e)
{
prodstart = prodstart - 1;
PopulateView();
}
}

Place the dataTables in form level property variables that use the "Lazy initializer" pattern, i.e., where they are coded so they will only call the database once, and populate a static private variable with the datatable that first time; every successive call will just read the private variable and skip the database call.
public partial class Cad_Prod : Form
{
private static readonly SQLiteConnection conn1 =
new SQLiteConnection(("data source=X.s3db");
private static DataTable produtos;
private static DataTable produtos;
private static DataTable AutoDataTable =>
produtos?? (produtos = GetAutos());
private static DataTable CategoryDataTable =>
categoria ?? (categoria = GetCategories());
int prodstart = 0;
public Cad_Prod() { InitializeComponent(); }
public void Cad_Prod_Load(object sender, EventArgs e) { }
private static DataTable GetAutos()
{
string query = "SELECT * FROM Cad_Prod";
try
{
using (SQLiteCommand comm = new SQLiteCommand(query, conn1))
using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(comm))
{
conn1.Open();
DataTable produtos = new DataTable();
adapter.Fill(produtos);
return produtos;
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Erro",
MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
}
}
private static DataTable GetCategories()
{
string query2 = "SELECT * FROM Cat";
try
{
using (SQLiteCommand comm2 = new SQLiteCommand(query2, conn1))
using (SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(comm2))
{
conn1.Open();
DataTable categoria = new DataTable();
adapter2.Fill(categoria);
return categoria;
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Erro",
MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
}
}
private void PopulateView()
{
int auxCat = int.Parse(produtos.Rows[prodstart]
.ItemArray[4].ToString()) - 1;
txtProdutoNome.Text = produtos.Rows[prodstart]
.ItemArray[1].ToString();
txtProdutoPreco.Text = produtos.Rows[prodstart]
.ItemArray[2].ToString();
txtProdutoQtd.Text = produtos.Rows[prodstart]
.ItemArray[3].ToString();
cbbCategoria.Text = categoria.Rows[auxCat]
.ItemArray[1].ToString();
}
private void btnAvancar_Click(object sender, EventArgs e)
{
prodstart = prodstart + 1;
PopulateView();
}
private void btnVoltar_Click(object sender, EventArgs e)
{
prodstart = prodstart - 1;
PopulateView();
}
}

Related

What should I do if I want the value of the dgv1(datagridview) to be shown on a different form?

Form1
namespace erpmam
{
public partial class Form1 : Form
{
MySqlDB mySqlDB;
SqlDataAdapter adpt;
DataTable dt;
SqlConnection con;
public void showdata()
{
adpt = new SqlDataAdapter("select deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms from sys_department;",con);
dt = new DataTable();
adpt.Fill(dt);
dgv1.DataSource = dt;
}
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
mySqlDB = new MySqlDB("server=······");
}
private SqlDataAdapter MySqlDataAdapter(string v, MySqlConnection con)
{
throw new NotImplementedException();
}
public void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void BTN_INSERT_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.ShowDialog();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string sql = "";
sql += " select";
sql += " deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms";
sql += " from sys_department";
sql += " where deptmt_id like '%" + textBox1.Text.Trim() + "%'";
DataTable dt = mySqlDB.ExecuteReader(sql, mySqlDB.DBConnection());
dgv1.SuspendLayout();
dgv1.Rows.Clear();
for (int idx = 0; idx < dt.Rows.Count; idx++)
{
DataRow r = dt.Rows[idx];
dgv1.Rows.Add(1);
dgv1[0, idx].Value = r["deptmt_id"].ToString().Trim();
dgv1[1, idx].Value = r["deptmt_name"].ToString().Trim();
dgv1[2, idx].Value = r["deptmt_seq"].ToString().Trim();
dgv1[3, idx].Value = r["reg_ymdtms"].ToString().Trim();
dgv1[4, idx].Value = r["mod_ymdtms"].ToString().Trim();
}
dgv1.ResumeLayout();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
string sql = "";
sql += " select";
sql += " deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms";
sql += " from sys_department";
sql += " where deptmt_name like '%" + textBox2.Text.Trim() + "%'";
DataTable dt = mySqlDB.ExecuteReader(sql, mySqlDB.DBConnection());
dgv1.SuspendLayout();
dgv1.Rows.Clear();
for (int idx = 0; idx < dt.Rows.Count; idx++)
{
DataRow r = dt.Rows[idx];
dgv1.Rows.Add(1);
dgv1[0, idx].Value = r["deptmt_id"].ToString().Trim();
dgv1[1, idx].Value = r["deptmt_name"].ToString().Trim();
dgv1[2, idx].Value = r["deptmt_seq"].ToString().Trim();
dgv1[3, idx].Value = r["reg_ymdtms"].ToString().Trim();
dgv1[4, idx].Value = r["mod_ymdtms"].ToString().Trim();
}
dgv1.ResumeLayout();
}
private void dgv1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Form3 Form3 = new Form3();
Form3.ShowDialog();
}
}
}
Form2
namespace erpmam
{
public partial class Form2 : Form
{
MySqlConnection connection = new MySqlConnection("datasource =······");
MySqlCommand command;
public Form2()
{
InitializeComponent();
}
public void executeMyQuery(string query)
{
try
{
openConnection();
command = new MySqlCommand(query, connection);
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Query Executed");
}
else
{
MessageBox.Show("Query Not Executed");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
}
public void openConnection()
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
}
public void closeConnection()
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
string insertQuery = "INSERT INTO sys_department(DEPTMT_ID, DEPTMT_NAME, DEPTMT_SEQ, REG_YMDTMS) VALUES(" + textBox1.Text + ',' + textBox2.Text + ','+ textBox3.Text + ','+ "NOW()" +")";
connection.Open();
MySqlCommand command = new MySqlCommand(insertQuery, connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("adding normally");
}
else
{
MessageBox.Show("error");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Form3
namespace erpmam
{
public partial class Form3 : Form
{
MySqlConnection connection = new MySqlConnection("datasource = localhost; port = 3306; Initial Catalog = 'erp'; username = root; password=610822");
MySqlCommand command;
public Form3()
{
InitializeComponent();
}
public void executeMyQuery(string query)
{
try
{
openConnection();
command = new MySqlCommand(query, connection);
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Query Executed");
}
else
{
MessageBox.Show("Query Not Executed");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
} public void openConnection()
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
}
public void closeConnection()
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
private void btn_update_Click(object sender, EventArgs e)
{
string updateQuery = " UPDATE sys_department";
updateQuery += " SET DEPTMT_NAME = '" + textBox2.Text + "', DEPTMT_SEQ = '" + textBox3.Text + "', mod_ymdtms = NOW()";
updateQuery += " where DEPTMT_ID = '" + textBox1.Text + "'";
connection.Open();
MySqlCommand command = new MySqlCommand(updateQuery, connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("changed normally");
}
else
{
MessageBox.Show("error");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
this.Close();
}
private void btn_delete_Click(object sender, EventArgs e)
{
string deleteQuery = " DELETE from sys_department";
deleteQuery += " where DEPTMT_ID = '" + textBox1.Text + "' or DEPTMT_NAME = '" + textBox2.Text + "' or DEPTMT_SEQ = '" + textBox3.Text + "'" ;
connection.Open();
MySqlCommand command = new MySqlCommand(deleteQuery, connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("adding normally");
}
else
{
MessageBox.Show("error");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
this.Close();
}
private void btn_cancel_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Simply you can create a Global variable of Datatable to use it as source of Data and you can use it anywhere in your Forms
This is the GLobal Class
//make sure to import this System.Data
using System.Data;
class Global
{
private static DataTable source;
public static DataTable Source
{
get
{
// Reads are usually simple
return source;
}
set
{
// You can add logic here for race conditions,
// or other measurements
source = value;
}
}
}
In your first form
string connectString = "datasource=xxxx;port=3306;username=xxxx;password=;database=xxxxx;";
MySqlConnection conn;
MySqlCommand comm;
MySqlDataReader read;
MySqlDataAdapter adapter;
Global mySource;
void getData() {
string query = "Select * from tableName";
conn = new MySqlConnection(connectString);
conn.Open();
comm = new MySqlCommand(query, conn);
adapter = new MySqlDataAdapter(query, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
//setting up
Global.Source = ds.Tables[0];
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
In you second Form
public Form2()
{
InitializeComponent();
dataGridView1.DataSource = Global.Source;
}
Simply you can create static method in the class of form3 and accept one argument from DataGridView type and call this method from form1 and pass dg1 after filling it with rows then you can access it now from this static method...
private void dgv1_CellClick(object sender, DataGridViewCellEventArgs e) {
Form3 Form3 = new Form3();
Form3.staticMethodToPassDGVBetweenTwoForms(dgv1);
Form3.ShowDialog();
}
namespace erpmam {
public partial class Form3 : Form {
public Form3() {
initializeComponent();
}
public static void staticMethodToPassDGVBetweenTwoForms(DataGridView dgv1){
//do anything with dg1 now
}
}

pass checked datagridview rows from child form to main form datagridview

I have 2 forms
ApodeikseisTimologion
EggrafesTimologionEsodon
ApodeikseisTimologion is the main form and EggrafesTimologionEsodon is the childform and 1 datagridview (dataGridViewProionApodeixeisTimologiouEsodon and dataGridViewEggrafesProionParastikouEsodon) in each form.
DataGridViewProionApodeixeisTimologiouEsodon belongs to main form and dataGridViewEggrafesProionParastikouEsodon belongs to child form.
Now, I want to pass the checked values from the child form to parent form without losing the values that i have already put in other textboxes in parent form.
Here is my code:
Form ApodeikseisTimologion.
I use this to open the child form
private void LinkLblEisagogiEggrafon_Click(object sender, EventArgs e) {
EggrafesTimologionEsodon eggrTimolEsodon = new EggrafesTimologionEsodon(cmbBoxEponimiaPelatiApodeixeisTimologiouEsodon.Text);
eggrTimolEsodon.ShowDialog();
this.Refresh();
}
Form EggrafesTimologionEsodon
private void EggrafesTimologionEsodon_Load(object sender, EventArgs e) {
try {
con = new SqlConnection();
con = DBAccess.Conn;
con.Open();
adap = new SqlDataAdapter("select ProionParastatikou.* from ProionParastatikou inner join Parastatiko on ProionParastatikou.ParastatikoID = Parastatiko.ParastatikoID" +
" where ProionParastatikou.Ypoloipo > 0.00 and Parastatiko.Eponimia = '" + txtPelatisId.Text + "'", con);
ds = new System.Data.DataSet();
adap.Fill(ds, "BsProionParastatikouEsodon");
dataGridViewEggrafesProionParastikouEsodon.DataSource = ds.Tables[0];
con.Close();
}
catch (Exception ex) {
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally {
if (MyConn.State != ConnectionState.Closed)
MyConn.Close();
}
}
I have this image :
in the child form i also have this to check the rows from the checkbox column of the datagridview and stored them to a list to transfer them to the parent form without losing the other data that i have already.
private void BtnProsthikiEggrafon_Click(object sender, EventArgs e) {
ApodeixeisTimologion apo = new ApodeixeisTimologion(null);
List<Int64> lst2send = new List<Int64>();
Int64 toSend;
foreach (DataGridViewRow eggrafes in dataGridViewEggrafesProionParastikouEsodon.Rows) {
if (Convert.ToBoolean(eggrafes.Cells["CheckBoxColumn"].Value)) {
int RowIndexCheck = eggrafes.HeaderCell.RowIndex;
Int64.TryParse(dataGridViewEggrafesProionParastikouEsodon.Rows[RowIndexCheck].Cells["proionParastatikouIDDataGridViewTextBoxColumn"].Value.ToString(),out toSend);
lst2send.Add(toSend);
}
}
apo.AfterProsthikiProionParastatikou(null, null, lst2send);
//apo.Refresh();
this.Close();
}
When the child form close, I have that in parent Form:
public void AfterProsthikiProionParastatikou(object sender,EventArgs e,IList<Int64> lst) {
String csvLst = string.Empty;
int count = 0;
foreach ( Int64 lstItems in lst) {
if (count == 0) {
csvLst = lstItems.ToString();
count += 1;
}
else {
csvLst = csvLst + "," + lstItems.ToString();
}
}
_con = new SqlConnection();
_con = DBAccess.Conn;
_con.Open();
adap = new SqlDataAdapter("select ProionParastatikou.* from ProionParastatikou where" +
" ProionParastatikou.Ypoloipo > 0.00 and ProionParastatikou.ProionParastatikouID"+
" in( " + csvLst + ")", _con);
ds = new System.Data.DataSet();
adap.Fill(ds, "bsProionApodeixeisTimologiouEsodon");//
dataGridViewProionApodeixeisTimologiouEsodon.DataSource = ds.Tables["bsProionApodeixeisTimologiouEsodon"];
//dataGridViewProionApodeixeisTimologiouEsodon.Refresh();
_con.Close();
}
i make a breakpoint in
ds = new System.Data.DataSet();
adap.Fill(ds, "bsProionApodeixeisTimologiouEsodon");//
dataGridViewProionApodeixeisTimologiouEsodon.DataSource = ds.Tables["bsProionApodeixeisTimologiouEsodon"];
And i see that the ds fills with the correct values but rows are not coming in the dataGridViewProionApodeixeisTimologiouEsodon which is the grid in parent form.
In all the forms i am using datasets and bindingSources in datagrids, and the datagrids are bounded except of the checkbox column.
Can somebody helps.
If someone needs more help i will give it.
Here's a minimal, but working sample.
Have a public property on your Form2, and access it from Form1. My snippet is passing a string, but yours will be dealing with a different data type. Same concept, different data type.
Form1.cs
using System;
using System.Windows.Forms;
namespace PassParamsFromForm2ToForm1_45997869
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += Button1_Click;
}
private void Button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2("blah blah blah");
f2.ShowDialog();
label1.Text = f2.returnValue;
}
}
}
Form2.cs
using System;
using System.Windows.Forms;
namespace PassParamsFromForm2ToForm1_45997869
{
public partial class Form2 : Form
{
public string returnValue;
private string submittedString { get; set; }
public Form2(string incomingString)
{
InitializeComponent();
submittedString = incomingString;
button1.Click += Button1_Click;
}
private void Button1_Click(object sender, EventArgs e)
{
returnValue = "I'd rather show you my value instead of yours(" + submittedString + ")...";
this.Close();
}
}
}
Working with Grid types
Form1.cs
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace PassParamsFromForm2ToForm1_45997869
{
public partial class Form1 : Form
{
BindingList<gridentry> gridList = new BindingList<gridentry>();
DataGridView dgv = new DataGridView();
DataGridView gridViewForTheReturnedRows;
public Form1()
{
InitializeComponent();
initializeGrid();
addDataToGridSource("name1");
addDataToGridSource("name2");
addDataToGridSource("name3");
addDataToGridSource("name4");
button1.Click += Button1_Click;
}
private void addDataToGridSource(string incomingString)
{
gridList.Add(new gridentry { col1 = incomingString, col2 = incomingString + "in col2", col3 = incomingString + "in col3" });
}
private void initializeGrid()
{
dgv.Location = new System.Drawing.Point(this.Location.X + 5, this.Location.Y + 5);
this.Controls.Add(dgv);
dgv.AutoGenerateColumns = true;
dgv.DataSource = gridList;
}
private void Button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(dgv);
f2.ShowDialog();
if (f2.returnRows != null && f2.returnRows.Count > 0)
{
gridViewForTheReturnedRows = new DataGridView();
gridViewForTheReturnedRows.ColumnCount = f2.returnRows[0].Cells.Count;
gridViewForTheReturnedRows.Rows.InsertRange(0, f2.returnRows.ToArray());
gridViewForTheReturnedRows.Location = new System.Drawing.Point(10, dgv.Location.Y + dgv.Height + 5);
this.Controls.Add(gridViewForTheReturnedRows);
}
}
}
public class gridentry
{
public string col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
}
}
Form2.cs
using System;
using System.Windows.Forms;
using System.Collections.Generic;
namespace PassParamsFromForm2ToForm1_45997869
{
public partial class Form2 : Form
{
public DataGridView returnGrid = new DataGridView();
public List<DataGridViewRow> returnRows { get; set; }
private DataGridView submittedGrid { get; set; }
public Form2(DataGridView incomingGrid)
{
InitializeComponent();
submittedGrid = incomingGrid;
submittedGrid.Location = new System.Drawing.Point(this.Location.X + 5, this.Location.Y + 5);
Controls.Add(submittedGrid);
button1.Click += Button1_Click;
}
private void Button1_Click(object sender, EventArgs e)
{
returnGrid = submittedGrid;//if you want to return the grid
//returning rows
/*
* You'll need your own mechanism to differentiate between
*/
bool rowIsModified = false;
returnRows = new List<DataGridViewRow>();
foreach (DataGridViewRow item in submittedGrid.Rows)
{
if (item.Index % 2 != 0)
{
rowIsModified = true;
}
if (rowIsModified)
{
DataGridViewRow r = (DataGridViewRow)item.Clone();
for (int i = 0; i < item.Cells.Count; i++)
{
r.Cells[i].Value = item.Cells[i].Value;
}
returnRows.Add(r);
}
}
this.Close();
}
}
}
Form ApodeikseisTimologion. I use this to open the child form
private void LinkLblEisagogiEggrafon_Click(object sender, EventArgs e)
{
if (cmbBoxEponimiaPelatiApodeixeisTimologiouEsodon.Text == "")
{
MessageBox.Show("Πρέπει να επιλέξετε Πελάτη", "Προειδοποίηση");
}
else
{
EggrafesTimologionEsodon eggrTimolEsodon = new EggrafesTimologionEsodon(cmbBoxEponimiaPelatiApodeixeisTimologiouEsodon.Text);//p
eggrTimolEsodon.ShowDialog();
listToFill = eggrTimolEsodon.lst2send;
AfterProsthikiProionParastatikou(null,null,listToFill);
//AfterProsthikiProionParastatikou(null);
//this.Refresh();
}
}
Form EggrafesTimologionEsodon
private void EggrafesTimologionEsodon_Load(object sender, EventArgs e)
{
//CmbBoxPelatis.SelectedIndex = -1;
//EggrafesTimologionEsodon values = new EggrafesTimologionEsodon();
try
{
con = new SqlConnection();
con = DBAccess.Conn;
con.Open();
adap = new SqlDataAdapter("select ProionParastatikou.* from ProionParastatikou inner join Parastatiko on ProionParastatikou.ParastatikoID = Parastatiko.ParastatikoID" +
" where ProionParastatikou.Ypoloipo > 0.00 and Parastatiko.Eponimia = '" + txtPelatisId.Text + "'", con);
ds = new System.Data.DataSet();
adap.Fill(ds, "BsProionParastatikouEsodon");
dataGridViewEggrafesProionParastikouEsodon.DataSource = ds.Tables[0];
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (MyConn.State != ConnectionState.Closed)
MyConn.Close();
}
}
From that I am having the image which is on top.
public List<Int64> lst2send;
private void BtnProsthikiEggrafon_Click(object sender, EventArgs e)
{
lst2send = new List<Int64>();
Int64 toSend;
foreach (DataGridViewRow eggrafes in dataGridViewEggrafesProionParastikouEsodon.Rows)
{
if (Convert.ToBoolean(eggrafes.Cells["CheckBoxColumn"].Value))
{
int RowIndexCheck = eggrafes.HeaderCell.RowIndex;
Int64.TryParse(dataGridViewEggrafesProionParastikouEsodon.Rows[RowIndexCheck].Cells["proionParastatikouIDDataGridViewTextBoxColumn"].Value.ToString(),out toSend);
lst2send.Add(toSend);
}
}
this.Close();
}
When the child form close, I have that in parent Form:
public List<Int64> listToFill;
public void AfterProsthikiProionParastatikou(object sender, EventArgs e, IList<Int64> lst)//object sender,EventArgs e,
{
String csvLst = string.Empty;
int count = 0;
foreach ( Int64 lstItems in lst)
{
if (count == 0)
{
csvLst = lstItems.ToString();
count += 1;
}
else
{
csvLst = csvLst + "," + lstItems.ToString();
}
}
_con = new SqlConnection();
_con = DBAccess.Conn;
_con.Open();
adap = new SqlDataAdapter("select ProionParastatikou.* from ProionParastatikou where" +
" ProionParastatikou.Ypoloipo > 0.00 and ProionParastatikou.ProionParastatikouID"+
" in( " + csvLst + ")", _con);
DataSetApodeixeisTimologiouEsodon ds = new DataSetApodeixeisTimologiouEsodon();
adap.Fill(ds.ApodeixeisProionParastatiko);//
bsProionApodeixeisTimologiouEsodon.DataSource = ds.ApodeixeisProionParastatiko;// Tables[0];
dataGridViewProionApodeixeisTimologiouEsodon.DataSource = bsProionApodeixeisTimologiouEsodon;
_con.Close();
}
private void LinkLblEisagogiEggrafon_Click(object sender, EventArgs e)
{
if (cmbBoxEponimiaPelatiApodeixeisTimologiouEsodon.Text == "")
{
MessageBox.Show("Πρέπει να επιλέξετε Πελάτη", "Προειδοποίηση");
}
else
{
EggrafesTimologionEsodon eggrTimolEsodon = new EggrafesTimologionEsodon(cmbBoxEponimiaPelatiApodeixeisTimologiouEsodon.Text);//p
eggrTimolEsodon.ShowDialog();
listToFill = eggrTimolEsodon.lst2send;
AfterProsthikiProionParastatikou(null,null,listToFill);
//AfterProsthikiProionParastatikou(null);
//this.Refresh();
}
}
And I am having the results that I want
enter image description here

survey page in asp c#

I have requirement to create a survey web form which should be loaded from database.
Each questions will have 10 rating items from 1-10 and the result should be saved to the database with question number.
I tried to achieve it with a web form with label control at the top and RadioButtonList for options, but only one question and answer is possible to load for display at a time. I'm new to web programming. If there is any working code sample or any idea how to achieve this, it would be helpful.
I've done the coding to put each question on page and on button click I am loading the next question, but I need all the questions on a single page.
public partial class _Default : System.Web.UI.Page
{
public static SqlConnection sqlconn;
protected string PostBackStr;
protected void Page_Load(object sender, EventArgs e)
{
sqlconn = new SqlConnection(ConfigurationManager.AppSettings["sqlconnstr"].ToString());
PostBackStr = Page.ClientScript.GetPostBackEventReference(this, "time");
if (IsPostBack)
{
string eventArg = Request["__EVENTARGUMENT"];
if (eventArg == "time")
{
string str = "select * from tbl_Question";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "Question");
int count = ds2.Tables[0].Rows.Count;
getNextQuestion(count);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Visible = false;
txtName.Visible =false;
Button1.Visible = false;
Panel1.Visible = true;
lblName.Text = "Name : " + txtName.Text;
int score = Convert.ToInt32(txtScore.Text);
lblScore.Text = "Score : " + Convert.ToString(score);
Session["counter"]="1";
Random rnd = new Random();
int i = rnd.Next(1, 10);//Here specify your starting slno of question table and ending no.
//lblQuestion.Text = i.ToString();
getQuestion(i);
}
protected void Button2_Click(object sender, EventArgs e)
{
string str = "select * from tbl_Question ";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "Question");
int count = ds2.Tables[0].Rows.Count;
getNextQuestion(count);
}
public void getQuestion(int no)
{
string str = "select * from tbl_Question where slNo=" + no + "";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "Question");
// int count = ds2.Tables[0].Rows.Count;
if (ds2.Tables[0].Rows.Count > 0)
{
DataRow dtr;
int i = 0;
while (i < ds2.Tables[0].Rows.Count)
{
dtr = ds2.Tables[0].Rows[i];
Session["Answer"] = Convert.ToString(Convert.ToInt32 (dtr["Correct"].ToString())-1);
lblQuestion.Text = "Q." + Session["counter"].ToString() + " " + dtr["Question"].ToString();
lblQuestion2.Text = "Q." + Session["counter"].ToString() + " " + dtr["arQuestion"].ToString();
LblQNNo.Text = Session["counter"].ToString();
RblOption.ClearSelection();
RblOption.Items.Clear();
RblOption.Items.Add(dtr["Option1"].ToString());
RblOption.Items.Add(dtr["Option2"].ToString());
RblOption.Items.Add(dtr["Option3"].ToString());
RblOption.Items.Add(dtr["Option4"].ToString());
RblOption.Items.Add(dtr["Option5"].ToString());
RblOption.Items.Add(dtr["Option6"].ToString());
RblOption.Items.Add(dtr["Option7"].ToString());
RblOption.Items.Add(dtr["Option8"].ToString());
RblOption.Items.Add(dtr["Option9"].ToString());
RblOption.Items.Add(dtr["Option10"].ToString());
i++;
}
}
}
public void getNextQuestion(int cnt)
{
if (Convert.ToInt32(Session["counter"].ToString()) < cnt)
{
Random rnd = new Random();
int i = rnd.Next(1, 10);
lblQuestion.Text = i.ToString();
getQuestion(i);
//qst_no = i;
Session["counter"] = Convert.ToString(Convert.ToInt32(Session["counter"].ToString()) + 1);
}
else
{
Panel2.Visible = false;
//code for displaying after completting the exam, if you want to show the result then you can code here.
}
}
protected void Button3_Click(object sender, EventArgs e)
{
insertAns();
}
private void insertAns()
{
SqlCommand cmd;
sqlconn = new SqlConnection(ConfigurationManager.AppSettings["sqlconnstr"].ToString());
cmd = new SqlCommand("insert into Tbl_Ans(UserID, Question_ID, Answer) values(#ans, #ans1, #ans2)", sqlconn);
cmd.Parameters.AddWithValue("#ans", txtName.Text);
cmd.Parameters.AddWithValue("#ans1", Session["counter"].ToString());
cmd.Parameters.AddWithValue("#ans2", RblOption.SelectedItem.Text);
sqlconn.Open();
int i = cmd.ExecuteNonQuery();
sqlconn.Close();
if (i != 0)
{
lbmsg.Text = "Your Answer Submitted Succesfully";
lbmsg.ForeColor = System.Drawing.Color.ForestGreen;
}
else
{
lbmsg.Text = "Some Problem Occured";
lbmsg.ForeColor = System.Drawing.Color.Red;
}
}
#region Connection Open
public void ConnectionOpen()
{
try
{
if (sqlconn.State == ConnectionState.Closed) { sqlconn.Open(); }
}
catch (SqlException ex)
{
lbmsg.Text = ex.Message;
}
catch (SystemException sex)
{
lbmsg.Text = sex.Message;
}
}
#endregion
#region Connection Close
public void ConnectionClose()
{
try
{
if (sqlconn.State != ConnectionState.Closed) { sqlconn.Close(); }
}
catch (SqlException ex)
{
lbmsg.Text = ex.Message;
}
catch (SystemException exs)
{
lbmsg.Text = exs.Message;
}
}
#endregion
}
first i want to say that you should use question table id instead of question number to save with the answer for future use.
I dont know more about dotnet so i have not attached any code here. But i can suggest you that
First fetch all the questions with their respective id into an object or array or fetch from them adaptor etc.
Then you can use a form to show them using foreach loop. for eg.
suppose "questions" is an array containing your all fetched questions from database. then apply
<form action="abc" method="post">
foreach(questions as question){
<tr>
<td>(print your question here)</td>
<td><input type="anything you want" name="(print here question.id)" />
</tr>
}
<input type="submit" value="submit" />
</form>
Now where you will fetch data on the form submission then you can easily access the answers with their name that is already question id. So now both have associated with each other.
welcome for any query if not clear.

Control based Security, cant delete from treeview the database entries,took code from controls-based-security-in-a-windows-forms-application

I want to delete from the treeview the nodes,and of course the roleid and userid.and on the other hand i also want to delete from listboxes rows,but i can delete them,but after restart application they are here again.it doesnt save
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using FirebirdSql.Data.FirebirdClient;
using System.Collections;
using System.Reflection;
namespace SiteYoenetim
{
public partial class ManageRoles : Form
{
private FbCommand cmd = null;
public ManageRoles()
{
InitializeComponent();
FillUsersInRollsTree();
}
private void homeToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
private void AddNewRole_Click(object sender, EventArgs e)
{
string newName = string.Empty;
newName = NewRoleName.Text;
NewRoleName.Text = string.Empty; // clear the control
DataSet1.ROLESRow newRolesRow;
newRolesRow = DataSet1.ROLES.NewROLESRow();
newRolesRow.ROLENAME = newName;
this.DataSet1.ROLES.Rows.Add(newRolesRow);
try
{
this.rolesTableAdapter.Update(this.DataSet1.ROLES);
}
catch (Exception ex)
{
this.DataSet1.ROLES.Rows.Remove(newRolesRow);
MessageBox.Show("Unable to add role " + newName + ex.Message,
"Unable to add role!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
RolesListBox.SelectedIndex = -1;
}
private void DeleteRole_Click(object sender, EventArgs e)
{
string newName = string.Empty;
newName = NewRoleName.Text;
NewRoleName.Text = string.Empty; // clear the control
DataSet1.ROLESRow newRolesRow;
newRolesRow = DataSet1.ROLES.NewROLESRow();
newRolesRow.ROLENAME = newName;
this.DataSet1.ROLES.Rows.RemoveAt(RolesListBox.SelectedIndex);
this.rolesTableAdapter.Update(this.DataSet1.ROLES);
}
private void AddNewAppUser_Click(object sender, EventArgs e)
{
DataSet1.USERSRow newUsersRow;
newUsersRow = DataSet1.USERS.NewUSERSRow();
newUsersRow.NAME = NewUserName.Text;
NewUserName.Text = string.Empty;
this.DataSet1.USERS.Rows.Add(newUsersRow);
this.usersTableAdapter.Update(this.DataSet1.USERS);
AppUsersListBox.SelectedIndex = -1;
}
HERE IT DELETES FROM APPUSER but it is again here after restart application
private void DeleteAppUser_Click(object sender, EventArgs e)
{
DataSet1.USERSRow delUsersRow;
delUsersRow = DataSet1.USERS.NewUSERSRow();
delUsersRow.NAME = NewUserName.Text;
NewUserName.Text = string.Empty;
this.DataSet1.USERS.Rows.RemoveAt(AppUsersListBox.SelectedIndex);
this.usersTableAdapter.Update(this.DataSet1.USERS);
}
private void AddUsersToRole_Click(object sender, EventArgs e)
{
ConnectionStringSettingsCollection connectionStrings =
ConfigurationManager.ConnectionStrings;
string connString = connectionStrings["xxx.Properties.Settings.xxx"].ToString();
FbConnection conn = new FbConnection(connString);
conn.Open();
FbParameter param;
foreach (DataRowView userRow in AppUsersListBox.SelectedItems)
{
foreach (DataRowView roleRow in RolesListBox.SelectedItems)
{
int userID = Convert.ToInt32(userRow["UserID"]);
int roleID = Convert.ToInt32(roleRow["RoleID"]);
try
{
cmd = new FbCommand("INSERT INTO usersToRoles (FKUserID, FKRoleID) values
(#USERID, #RoleID)", conn);
param = cmd.Parameters.Add("#USERID", FbDbType.Integer);
param.Value = userID;
param.Direction = ParameterDirection.Input;
param = cmd.Parameters.Add("#RoleID", FbDbType.Integer);
param.Value = roleID;
param.Direction = ParameterDirection.Input;
int rowsInserted = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
conn.Close();
FillUsersInRollsTree();
}
private void DisplayError(int userID, int roleID, string message)
{
MessageBox.Show("Unable to add user (" + userID + ") to role (" + roleID + ")" + message,
"Unable to add user to role",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
private void FillUsersInRollsTree()
{
ConnectionStringSettingsCollection connectionStrings =
ConfigurationManager.ConnectionStrings;
string connString = connectionStrings["xxx.Properties.Settings.xxx"].ToString();
FbConnection conn = new FbConnection(connString);
conn.Open();
string queryString = "select u.Name, r.RoleName from userstoRoles utr " +
" join users u on u.userID = utr.FKUserID " +
" join Roles r on r.roleID = utr.FKRoleID ";
if (rbName.Checked)
{
queryString += "order by Name";
}
else
{
queryString += "order by RoleName";
}
UsersInRoles.BeginUpdate();
UsersInRoles.Nodes.Clear();
TreeNode parentNode = null;
TreeNode subNode = null;
DataSet ds = new DataSet();
FbDataAdapter dataAdapter = new FbDataAdapter(queryString, conn);
dataAdapter.Fill(ds, "usersInRoles");
DataTable dt = ds.Tables[0];
string currentName = string.Empty;
foreach (DataRow row in dt.Rows)
{
if (rbName.Checked)
{
subNode = new TreeNode(row["roleName"].ToString());
if (currentName != row["Name"].ToString())
{
parentNode = new TreeNode(row["Name"].ToString());
currentName = row["Name"].ToString();
UsersInRoles.Nodes.Add(parentNode);
}
}
else
{
subNode = new TreeNode(row["Name"].ToString());
if (currentName != row["RoleName"].ToString())
{
parentNode = new TreeNode(row["RoleName"].ToString());
currentName = row["RoleName"].ToString();
UsersInRoles.Nodes.Add(parentNode);
}
}
if (parentNode != null)
{
parentNode.Nodes.Add(subNode);
}
}
UsersInRoles.EndUpdate();
}
private void RadioButtonClick(object sender, EventArgs e)
{
FillUsersInRollsTree();
}
private void ManageRoles_Load(object sender, EventArgs e)
{
this.uSERSTOROLESTableAdapter.Fill(this.dataSet11.USERSTOROLES);
this.uSERSTOROLESTableAdapter.Fill(this.DataSet1.USERSTOROLES);
this.usersTableAdapter.Fill(this.DataSet1.USERS);
this.rolesTableAdapter.Fill(this.DataSet1.ROLES);
}
private void Save_Click(object sender, EventArgs e)
{
this.Validate();
this.usersBindingSource.EndEdit();
this.usersTableAdapter.Update(this.DataSet1);
}
HERE IT SHOULD DELETE FROM TREEVIEW, but it doesnt
private void RemoveUsersFromRole_Click(object sender, EventArgs e)
{
ConnectionStringSettingsCollection connectionStrings =
ConfigurationManager.ConnectionStrings;
string connString = connectionStrings["xxx.Properties.Settings.xxx"].ToString();
FbConnection conn = new FbConnection(connString);
conn.Open();
FbParameter param;
foreach (DataRowView userRow in AppUsersListBox.SelectedItems)
{
foreach (DataRowView roleRow in RolesListBox.SelectedItems)
{
{
int userID = Convert.ToInt32(userRow["UserID"]);
int roleID = Convert.ToInt32(roleRow["RoleID"]);
try
{
cmd = new FbCommand("DELETE FROM usersToRoles (FKUserID, FKRoleID) values (USERID, RoleID)", conn);
param = cmd.Parameters.Add("USERID", FbDbType.Integer);
param.Value = userID;
param.Direction = ParameterDirection.Input;
param = cmd.Parameters.Add("RoleID", FbDbType.Integer);
param.Value = roleID;
param.Direction = ParameterDirection.Input;
int rowsInserted = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
conn.Close();
FillUsersInRollsTree();
}
}
}
}
If your data is stored in a database, then deleting the data from the treeview and listboxes alone is not sufficient. You will have to delete the information in the database as well.
EDIT:
Your DELETE SQL command is wrong. Try to change it to:
DELETE FROM usersToRoles WHERE FKUserID = #USERID AND FKRoleID = #RoleID
(I was a mix between INSERT statement and DELETE statement.)

How to make one TextBox to update when ComboBox changes in .NET? [closed]

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.

Categories