How can i call a Oracle connection method in C# with paramaters? - c#

i have created a program in C# which inserts data into an Oracle database. It is pretty procedural though and i want to improve my program (and my knowledge) to use classes. I am having some trouble around calling a method with parameters. This is my code:
public class Oracle {
public void Insert() {
string oracleConnectionString = "User Id=" + l_orauser + "; Password=" + l_orapass + "; Data Source=" + l_oradb;
using (OracleConnection oracleConnection = new OracleConnection(oracleConnectionString)) {
oracleConnection.Open();
OracleGlobalization oracleSession = oracleConnection.GetSessionInfo();
oracleSession.DateFormat = "dd-mm-yyyy hh24:mi:ss";
oracleConnection.SetSessionInfo(oracleSession);
OracleTransaction oracleTransaction = oracleConnection.BeginTransaction();
OracleCommand oracleCommand = oracleConnection.CreateCommand();
oracleCommand.Transaction = oracleTransaction;
oracleCommand.CommandType = CommandType.Text;
string oracleCommandText = "insert into T1 (C1, C2, C3) values (:l_c1, :l_c2, :l_c3)";
oracleCommand.CommandText = oracleCommandText;
oracleCommand.BindByName = true;
oracleCommand.Parameters.Add("l_c1", OracleDbType.Byte, 3).Value = l_c1;
oracleCommand.Parameters.Add("l_c2", OracleDbType.Date).Value = l_c2;
oracleCommand.Parameters.Add("l_c3", OracleDbType.Varchar2, 1024).Value = l_c3;
try {
oracleCommand.ExecuteNonQuery();
oracleTransaction.Commit();
}
catch (Exception ex) {
oracleTransaction.Rollback();
MessageBox.Show(ex.Message);
}
finally {
oracleCommand.Parameters.Clear();
oracleCommand.Dispose();
oracleTransaction.Dispose();
oracleConnection.Close();
oracleConnection.Dispose();
}
}
}
}
I want to call this with some parameters - the variables: l_orauser, l_orapass, l_oradb, l_c1, l_c2, l_c3, which are taken from the elements of the form, for instance textbox, datetimepicker. How can i do that?
public static void Main(string[] args) {
var testOracle = new Oracle();
testOracle.Insert();
}

ok, so after discussing with Tim Freese i have decided to use constructors and an array of prameters.
For reference i have added the code, maybe somebody will find it useful:
public static void Main(string[] args) {
string oracleUser, oraclePassword, oracleDatabase;
List<string> oracleArguments = new List<string>();
//0 = oracleUser
//1 = oraclePassword
//2 = oracleDatabase
//3 = oracleCommandText
//4+ = oracleCommand.Parameters
l_orauser = "schema1";
l_orapass = "schema1pass";
l_oradb = "db1";
oracleArguments.Add(l_orauser);
oracleArguments.Add(l_orapass);
oracleArguments.Add(l_oradb);
Oracle testOracle = new Oracle();
testOracle.Insert(oracleArguments);
}
And the Oracle class:
public class Oracle {
public void Insert(List<string> oracleArguments) {
string oracleConnectionString = "User Id=" + oracleArguments[0] + "; Password=" + oracleArguments[1] + "; Data Source=" + oracleArguments[2];
using (OracleConnection oracleConnection = new OracleConnection(oracleConnectionString)) {
//do something
}
}
}

Related

ExecuteNonQuery Violation of Primary Key after putting value?

I'm trying to write a CRUD app and I have a problem with the Create method. Program is crashing with error
System.Data.SqlClient.SqlException: 'Violation of PRIMARY KEY constraint 'PK_Pracownicy'. Cannot insert duplicate key in object 'dbo.Pracownicy'. The duplicate key value is (11).
The statement has been terminated.'
But I can see in my SQL Server that this position is added to Pracownicy table, so I don't know where is a problem. Its look like the error is generated after I put new values to table
class SqlHelper
{
public int RowsLenght { get; set; }
private SqlConnection sqlConnection;
public string Command { get; set; }
public SqlHelper(string connectionString)
{
sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
}
public int Create(string command, SqlParameter []parameters)
{
//wykonanie polecenia na bazie
using var cmd = new SqlCommand(command, sqlConnection);
cmd.Parameters.AddRange(parameters);
ShowTable(cmd);
return cmd.ExecuteNonQuery();
}
public int Read(string command)
{
//wykonanie polecenia na bazie
using var cmd = new SqlCommand(command, sqlConnection);
ShowTable(cmd);
return cmd.ExecuteNonQuery();
}
private int ShowTable(SqlCommand command)
{
var reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + "\t" + reader.GetString(2) + " " +
reader.GetString(1) + "\t" + reader.GetString(3));
RowsLenght++;
}
reader.Close();
return RowsLenght;
}
}
class Program
{
static void Main()
{
SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder
{
DataSource = #"HAL\MSSERVER",
InitialCatalog = "ZNorthwind",
IntegratedSecurity = true,
ConnectTimeout = 30,
Encrypt = false,
TrustServerCertificate = false,
ApplicationIntent = 0,
MultiSubnetFailover = false
};
var connectionS = connectionString.ConnectionString;
SqlHelper sql = new SqlHelper(connectionS);
var command = "SELECT * FROM dbo.Pracownicy";
sql.Read(command);
command = "INSERT INTO dbo.Pracownicy (IDpracownika, Nazwisko, Imię, Stanowisko) VALUES (#IDpracownika, #Nazwisko, #Imie, #Stanowisko)";
var parameters = SetUpParameters(sql.RowsLenght);
sql.Create(command, parameters);
}
private static SqlParameter[] SetUpParameters(int lenght)
{
//inicjalizacja zmiennych:
Console.WriteLine("Podaj imie nowego pracownika: ");
var fname = Console.ReadLine();
Console.WriteLine("Podaj nazwisko pracownika: ");
var lname = Console.ReadLine();
Console.WriteLine("Podaj stanowisko pracownika: ");
var position = Console.ReadLine();
SqlParameter []param = new SqlParameter[4];
param[0] = new SqlParameter("IDpracownika", lenght + 1);
param[1] = new SqlParameter("Imie", fname);
param[2] = new SqlParameter("Nazwisko", lname);
param[3] = new SqlParameter("Stanowisko", position);
return param;
}
}
Thanks

C# DataGridView can't display dataset stored in him

I'm trying to pull data from the database to DataGridView3, you can see it on the right column on image below. When i did debug, i saw that DataSet keeps correct values and on first try when i do cellClick on dataGrid1 it shows correct. But in subsequent attempts DataGridView3 does not display DataSet, although in debug there are correct values in DataSet. DataGridView3 display only header titles of tables, not records in database. Also when i click on this headers(thereby doing the sorting of rows) records appears. You can see this on picture 2. So problem is in DataGridView, which can't display data which is stored in him. I tried to use Update(), Refresh(), Show() methods on DataGridView3, but it's not helped.
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Windows.Forms;
namespace Lab3
{
public partial class Form1 : Form
{
private MySqlConnection connection = null;
private DataSet dataSet = null;
private DataSet dataSetOld = null;
private MySqlDataAdapter doctorDataAdapter = null;
private MySqlDataAdapter patientDataAdapter = null;
private MySqlDataAdapter appointmentDataAdapter = null;
public Form1()
{
InitializeComponent();
}
public void setConnection(MySqlConnection connection)
{
this.connection = connection;
}
//creating DataSet
private DataSet getDataSet()
{
if (dataSet == null)
{
dataSet = new DataSet();
dataSet.Tables.Add("Doctor");
dataSet.Tables.Add("Patient");
dataSet.Tables.Add("Appointment");
}
return dataSet;
}
//set connection with database
public MySqlConnection Connect(string host, int port, string database,
string username, string password)
{
string connStr = "Server=" + host + ";Database=" + database + ";port=" + port + ";User Id=" + username + ";password=" + password;
MySqlConnection connection = new MySqlConnection(connStr);
connection.Open();
return connection;
}
public void FillDataGridView1ByDoctors()
{
getDataSet().Tables["Doctor"].Clear();
doctorDataAdapter = new MySqlDataAdapter(
"SELECT * FROM Doctor", connection);
new MySqlCommandBuilder(doctorDataAdapter);
doctorDataAdapter.Fill(getDataSet(), "Doctor");
dataGridView1.DataSource = getDataSet().Tables["Doctor"];
this.dataGridView1.Columns["id_doctor"].Visible = false;
}
public void FillDataGridView2ByPatients()
{
getDataSet().Tables["Patient"].Clear();
patientDataAdapter = new MySqlDataAdapter(
"SELECT * FROM Patient", connection);
new MySqlCommandBuilder(patientDataAdapter);
patientDataAdapter.Fill(dataSet, "Patient");
dataGridView2.DataSource = getDataSet().Tables["Patient"];
this.dataGridView2.Columns["id_patient"].Visible = false;
dataGridView2.ClearSelection();
}
public void FillDataGridView3ByAppointment(string table, int id)
{
getDataSet().Tables["Appointment"].Reset();
if (table == "Doctor")
{
appointmentDataAdapter = new MySqlDataAdapter(
"SELECT patient.name_patient AS `Имя`, patient.surname_patient, appointment.datetime " +
"FROM patient, appointment, doctor " +
"WHERE doctor.id_doctor = appointment.id_doctor AND patient.id_patient = appointment.id_patient AND doctor.id_doctor = " +
id, connection);
}
else
{
appointmentDataAdapter = new MySqlDataAdapter(
"SELECT doctor.name_doctor, doctor.surname_doctor, doctor.speciality, appointment.datetime " +
"FROM doctor, appointment, patient " +
"WHERE patient.id_patient = appointment.id_patient AND doctor.id_doctor = appointment.id_doctor AND patient.id_patient = " +
id, connection);
}
new MySqlCommandBuilder(appointmentDataAdapter);
appointmentDataAdapter.Fill(dataSet, "Appointment");
dataGridView3.DataSource = getDataSet().Tables["Appointment"];
}
private void dataGridView1_CellClick(object sender,
DataGridViewCellEventArgs e)
{
int selectedRow = dataGridView1.SelectedCells[0].RowIndex;
int key = (int)dataGridView1.Rows[selectedRow].Cells[0].Value;
dataGridView2.ClearSelection();
FillDataGridView3ByAppointment("Doctor", key);
}
private void dataGridView2_CellClick(object sender,
DataGridViewCellEventArgs e)
{
int selectedRow = dataGridView2.SelectedCells[0].RowIndex;
int key = (int)dataGridView2.Rows[selectedRow].Cells[0].Value;
dataGridView1.ClearSelection();
FillDataGridView3ByAppointment("Patient", key);
}
}
}

file already in use exception after using dispose and SuppressFinalize on MS access File

I am working on software that make changes in database through GUI. I want to compact database after user clicks save. After save user can continue to use software or close, so I am not using "using". I have created databaseAccess object which holds OleDbConnection connection object with few others. This is my database access class.
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Data;
using System.Diagnostics;
using System.Windows.Forms;
namespace TreeTool
{
public class DataBaseAccess
{
#region Properties
private string m_directory;
public List<string> selectedTableNames;
private Dictionary<String, DataTable> selectedTables;
private OleDbConnection mdbConnection;
DataTable dataTable;
//Constructor
public DataBaseAccess()
{
selectedTableNames = new List<string>();
selectedTables = new Dictionary<string, DataTable>();
}
public string directory
{
get
{
return m_directory;
}
set
{
m_directory = value;
}
}
#endregion
public List<string> GetAllTableNames()
{
if (dataTable != null)
{
List<string> tableList = new List<string>();
for (int i = 0; i < dataTable.Rows.Count; i++)
{
string TableName = dataTable.Rows[i][2].ToString();
tableList.Add(TableName);
}
return tableList;
}
return null;
}
/// <summary>
/// Returns Table Columns
/// </summary>
/// <returns></returns>
public DataTable GetTable(string TableName)
{
DataTable mdbTable;
if (selectedTables.TryGetValue(TableName, out mdbTable))
{
return mdbTable;
}
else
{
mdbTable = new DataTable();
//mdbConnection.Open();
string mdbCommandString = "SELECT * FROM [" + TableName + "]";
OleDbDataAdapter QueryCommand = new OleDbDataAdapter(mdbCommandString, mdbConnection);
QueryCommand.Fill(mdbTable);
//mdbConnection.Close();
selectedTables.Add(TableName, mdbTable);
return mdbTable;
}
}
public void SetTable(String TableName, DataTable dataTable)
{
//mdbConnection.Open();
OleDbCommand ac = new OleDbCommand("delete from [" + TableName + "]", mdbConnection);
ac.ExecuteNonQuery();
foreach (DataRow row in dataTable.Rows)
{
String query = "INSERT INTO [" + TableName + "] (TaskID, HTMLTopic, nRelative, [Group], nKey,"
+ " [nText], nImage, nSelImage, nFontName, nFontInfo, Keywords) VALUES (#TaskID,"
+ " #HTMLTopic, #nRelative, #Group, #nKey, #nText, #nImage, #nSelImage, #nFontName, "
+ " #nFontInfo, #Keywords)";
OleDbCommand command = new OleDbCommand(query, mdbConnection);
command.Parameters.AddWithValue("#TaskID", row["TaskID"]);
command.Parameters.AddWithValue("#HTMLTopic", row["HTMLTopic"]);
command.Parameters.AddWithValue("#nRelative", row["nRelative"]);
command.Parameters.AddWithValue("#Group", row["Group"]);
command.Parameters.AddWithValue("#nKey", row["nKey"]);
command.Parameters.AddWithValue("#nText", row["nText"]);
command.Parameters.AddWithValue("#nImage", row["nImage"]);
command.Parameters.AddWithValue("#nSelImage", row["nSelImage"]);
command.Parameters.AddWithValue("#nFontName", row["nFontName"]);
command.Parameters.AddWithValue("#nFontInfo", row["nFontInfo"]);
command.Parameters.AddWithValue("#Keywords", row["Keywords"]);
command.ExecuteNonQuery();
}
//mdbConnection.Close();
}
internal bool validTable(string TableName)
{
DataTable mdbTable = new DataTable();
//mdbConnection.Open();
string mdbCommandString = "SELECT * FROM [" + TableName + "]";
OleDbDataAdapter QueryCommand = new OleDbDataAdapter(mdbCommandString, mdbConnection);
QueryCommand.Fill(mdbTable);
//mdbConnection.Close();
// check if table contains all columns necessary
String[] columnNames = new string[] { "TaskID" , "HTMLTopic", "nRelative", "Group", "nKey",
"nText", "nImage", "nSelImage", "nFontName", "nFontInfo", "Keywords"};
Boolean missingColumn = false;
DataColumnCollection columns = mdbTable.Columns;
foreach (String columnName in columnNames)
{
if (columns.Contains(columnName) == false)
{
// print the message
MessageBox.Show("Database: " + directory + " Table: " + TableName + " is missing column \"" + columnName
+ "\". Add it to make changes.",
"Missing column",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
missingColumn = true;
}
}
if (missingColumn == true)
{
return false;
}
return true;
}
public void insertTable(String tableName)
{
selectedTableNames.Add(tableName);
}
public List<String> getSelectedTables()
{
return selectedTableNames;
}
public Boolean isConnected()
{
if (mdbConnection == null)
{
return false;
}
return true;
}
public void connect()
{
if (mdbConnection == null)
{
String m_mdbDirectory = #"Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + m_directory;
mdbConnection = new OleDbConnection(m_mdbDirectory);
mdbConnection.Open();
string[] restrictions = new string[4];
restrictions[3] = "Table";
dataTable = mdbConnection.GetSchema("TABLES", restrictions);
//mdbConnection.Close();
}
}
public void disconnect()
{
mdbConnection.Close();
mdbConnection.Dispose();
GC.SuppressFinalize(mdbConnection);
mdbConnection = null;
}
public void clearSelectedTables()
{
selectedTableNames.Clear();
}
}
}
Save and compact functions are like this
private void save()
{
foreach(DataBaseAccess database in databases)
{
// save changes code
database.disconnect();
CompactAndRepairAccessDB(database.directory);
database.connect();
}
}
private void CompactAndRepairAccessDB(string accessFile)
{
string tempFile = #"temp.mdb";
FileInfo temp = new FileInfo(tempFile);
// Required COM reference for project:
// Microsoft Office 14.0 Access Database Engine Object Library
var dbe = new Microsoft.Office.Interop.Access.Dao.DBEngine();
try
{
dbe.CompactDatabase(accessFile, tempFile);
temp.CopyTo(accessFile, true);
temp.Delete();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
The exception happens on line "dbe.CompactDatabase(accessFile, tempFile);".
In the code in all the methods where you use OleDbDataAdapter and OleDbCommand make sure to use the using-Pattern on these objects. They can keep the mdb file open even though the actual connection is already disposed.
Methods that require modification seem to be GetTable, SetTable and ValidTable.

nested data reader issue mysql c#

I have written a custom class to handle database queries to a remote and local MySQL database, however when I do a nested loop I receive the below error:
MySql.Data.MySqlClient.MySqlException was unhandled
Message=There is already an open DataReader associated with this Connection which must be closed first.
Source=MySql.Data
ErrorCode=-2147467259
Number=0
My class currently looks like this
public class MySQLManager
{
private MySqlConnection _MySQLRemoteConnection { get; set; }
public void setup(string remoteUser, string remotePass, string remoteServerAddress, string remoteDb, string localUser, string localPass, string localServerAddress, string localDb)
{
_remote_server_address = remoteServerAddress;
_remote_database = remoteDb;
_remote_username = remoteUser;
_remote_password = remotePass;
}
public void connect()
{
try
{
_MySQLRemoteConnection = new MySqlConnection() { ConnectionString = string.Format("server={0};database={1};uid={2};password={3};", _remote_server_address, _remote_database, _remote_username, _remote_password) };
_MySQLRemoteConnection.Open();
_RemoteConnection = true;
}
catch (MySqlException ex)
{
_RemoteConnection = false;
}
}
public MySqlCommand run(string query, List<MySqlParameter> dbparams = null)
{
connect();
MySqlCommand sql = getConnection().CreateCommand();
sql.CommandText = query;
if (dbparams != null)
{
if (dbparams.Count > 0)
{
sql.Parameters.AddRange(dbparams.ToArray());
}
}
//disconnect();
return sql;
}
public MySqlDataReader fetch(MySqlCommand cmd)
{
//connect();
var t = cmd.ExecuteReader();
//disconnect();
return t;
}
And the code that I'm running to create the error, now I understand I can do the below example in a single query, this is an EXAMPLE query to re-create the error, writing it into a single query will not work with live examples.
query = "SELECT field1 FROM tmp WHERE field1 < 3";
using (var sql = db.run(query))
{
txtResponse.Text += "Query ran" + nl;
using (var row = db.fetch(sql))
{
txtResponse.Text += "Query fetched" + nl;
db.connect();
while (row.Read())
{
txtResponse.Text += "Row : " + row[0].ToString() + nl;
query = "SELECT val1 FROM tmp2 WHERE field1 = '" + row[0].ToString() + "'";
//db.disconnect();
using (var sql2 = db.run(query))
{
txtResponse.Text += "Query ran" + nl;
db.disconnect();
using (var row2 = db.fetch(sql))
{
txtResponse.Text += "Query fetched" + nl;
db.connect();
while (row.Read())
{
txtResponse.Text += " Val : " + row2[0].ToString() + nl;
}
}
}
}
}
}
So how would I go about getting the second loop to work?
For SQL Server, you could use MultipleActiveResultSets=true on connection string, but this most likely won't work for MySQL.
The other option is to use 2 connections, one for each data reader.

Displaying a progressbar while executing an SQL Query

I want to inform the user while data is being read from an SQL database
and I decided to create a form with a progressbar but it doesn't work - maybe because a thread is needed. I want to create the form programmatically
ProgressBar pb = new ProgressBar();
pb.MarqueeAnimationSpeed = 30;
pb.Style = ProgressBarStyle.Marquee;
pb.Dock = DockStyle.Fill;
progressForm.ClientSize = new Size(200, 50);
progressForm.FormBorderStyle = FormBorderStyle.FixedDialog;
progressForm.StartPosition = FormStartPosition.CenterScreen;
progressForm.Controls.Add(pb);
progressForm.ControlBox = false;
progressForm.TopMost = true;
progressForm.Show();
//do data processes here (all queries and executes)
progressForm.close();
How do I modify the code above to achieve my stated goals?
edit: Btw, I want to use this progressbar form in every data functions in my project. For example: fillGrid, runQuery..
#Will thank you very much for your answers. I meant how can I use a function of class for example my gridFill function is in that connection class:
class ConnectionClass
{
public static SqlConnection connection = new SqlConnection();
public string sorgu;
public static string server;
public static string userId;
public static string catalog;
public static string password;
public static string accessMethod;
public DataSet ds = new DataSet();
Form progressForm = new Form();
public bool Open()
{
try
{
if (connection.State != ConnectionState.Open)
{
connection.ConnectionString = "Data Source = " + server + ";" +
"Initial Catalog=" + catalog + ";" +
"User ID=" + userId + ";" +
"Password=" + password + ";" +
"Connect Timeout=0";
connection.Open();
return true;
}
else
{
return true;
}
}
catch (Exception ex)
{
MessageBox.Show("System message:" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
public DataTable Dt(string query)
{
DataTable dt = new DataTable();
if (Open())
{
SqlDataAdapter da = new SqlDataAdapter(query, connection);
try
{
//progressForm.Showdialog() is this possible???
da.Fill(dt);
//progressForm.close(); ??
}
catch (Exception ex)
{
MessageBox.Show("Sistem Mesajı:" + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return dt;
}
public bool Run(string query, string hataMsj)
{
Form activeForm = Form.ActiveForm;
query = " SET DATEFORMAT DMY " + query;
SqlCommand sc = new SqlCommand(query, connection);
try
{
Open();
sc.ExecuteNonQuery();
return true;
}
catch (Exception )
{
return false;
}
}
public void fillComboBox(string sorgu, ComboBox cb, string text, string value)
{
DataTable dt = Dt(sorgu);
cb.DisplayMember = text;
cb.ValueMember = value;
cb.DataSource = dt;
if (cb.Items.Count > 0)
{
cb.SelectedIndex = 0;
}
}
public int fillGridView(string sorgu, DataGridView dgv)
{
DataTable dtGrvw = Dt(sorgu);
dgv.DataSource = dtGrvw;
return 1;
}
}
and example queries from another form(class)
ConnectionClass cc = new ConnectionClass();
query= " INSERT INTO tblPersonel (" +
" [sqlUserName] " +
",[personelNo] " +
",[ad] " +
",[soyad] " +
",[departmanId] " +
",[emailadres] " +
",[tcKimlikNo],[kangurubu],[dokumaciNo])VALUES" +
"('" + tbSqlUserName.Text +
"','" + tbPersonelNo.Text +
"','" + tbAd.Text +
"','" + tbSoyad.Text +
"','" + cbDepartman.SelectedValue.ToString() +
"','" + tbMail.Text +
"','" + tbKimlikno.Text +
"','" + tbKangrubu.Text +
"','" + tbDokumaciNo.Text + "' ) ";
if (cc.Run(query, "Unexpected error on insert new person"))
{
fillGrid();
this.Close();
}
public void fillGrid()
{
query= " select * from View_Personel order by personelNo desc";
cc.fillGridView(query, gridviewPersonel);
}
and I cant imagine how can I use it in bw_DoWork event. because my function has parameters.(query, gridview) when I call it from another class I can use it with parameters...
p.s. : this Method is pretty good for me but it didnt worked. I didnt understand the problem
Use the BackgroundWorker class to fill your DataGrid.
Form progressForm;
public void func() {
BackgroundWorker bw = new BackgroundWorker ();
bw.DoWork += new DoWorkEventHandler (bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler (bw_RunWorkerCompleted);
progressForm = new Form ();
ProgressBar pb = new ProgressBar ();
pb.MarqueeAnimationSpeed = 30;
pb.Style = ProgressBarStyle.Marquee;
pb.Dock = DockStyle.Fill;
progressForm.ClientSize = new Size (200, 50);
progressForm.FormBorderStyle = FormBorderStyle.FixedDialog;
progressForm.StartPosition = FormStartPosition.CenterScreen;
progressForm.Controls.Add (pb);
progressForm.ControlBox = false;
progressForm.TopMost = true;
progressForm.Show ();
string queryString = "SELECT ...."; // fill query string here
var params = new KeyValuePair<GridControl, string>(sorgu, queryString);
bw.RunWorkerAsync (params);
}
void bw_DoWork (object sender, DoWorkEventArgs e) {
KeyValuePair<GridControl, string> params = e.Argument as KeyValuePair<GridControl, string>;
ConnectionClass cc = new Connection Class();
cc.fillGrid(params.Value, params.Key);
}
void bw_RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e) {
progressForm.Close (); //
}
It is possible to send a parameter to the BackgroundWorker. If you need more than one parameter, you can send a Tuple which contains any objects you need.
EDIT: If you're on 3.5, you can use a KeyValuePair instead. Code is updated for that.
Just as Ash Burlaczenko recommended, you'll have to use a BackgroundWorker for that purpose.
Since, however, you'd like to tie it in with a ProgressBar, I'd recommend looking at this article on CodeProject: ProgressWorker.
It's fairly easy to use and it updates the progress bar for you automatically. All you'll have to do is remember to call the ProgressWorker.ReportProgress method from time to time in order to update the associated progress bar.

Categories