This is my simple code just to read something from MySQL. But want I want is to create connection and command when Form is opened and just to open connection when button is clicked and do the rest. But It says:
"The name 'konekcija' does not exist in the current context"
Could someone explain me please.
namespace mysql_windows_console
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
/*========MYSQL KONEKCIJA===========*/
string baza = "server=localhost;database=test;user=root;password=;";
MySqlConnection konekcija = new MySqlConnection(baza);
MySqlCommand comm = konekcija.CreateCommand();
/*========MYSQL KONEKCIJA===========*/
}
private void button1_Click(object sender, EventArgs e)
{
konekcija.Open();
string sql = "SELECT IME,PREZIME FROM tabela";
MySqlDataAdapter adapter = new MySqlDataAdapter(sql,konekcija);
DataTable tab = new DataTable();
adapter.Fill(tab);
dataGridView1.DataSource = tab;
konekcija.Close();
}
}
}
You should declare MySqlConnection outside of the Form_Load EventHandler so you can access it from other methods. Also I would suggest to initialize it in a Form constructor. Since you are using DataAdapter you don't need to use MySqlCommand. Here is the revised code;
namespace mysql_windows_console
{
public partial class Form1 : Form
{
MySqlConnection konekcija;
string baza = "server=localhost;database=test;user=root;password=;"; //so you can access it again if you need it b any chance
public Form1()
{
InitializeComponent();
konekcija = new MySqlConnection(baza);
}
private void button1_Click(object sender, EventArgs e)
{
konekcija.Open();
string sql = "SELECT IME,PREZIME FROM tabela";
MySqlDataAdapter adapter = new MySqlDataAdapter(sql,konekcija);
DataTable tab = new DataTable();
adapter.Fill(tab);
dataGridView1.DataSource = tab;
konekcija.Close();
}
}
}
You're storing konekcija as a local variable. Make it a property like:
private MySqlConnection konekcija { get; set; }
public void Form1_Load(object sender, EventArgs e)
{
//...
this.konekcija = new MySqlConnection(baza);
}
private void button1_click(object sender, EventArgs e)
{
this.konekcija.Open();
//...
}
it simply means that konekcija is not found on the scope of button1_Click.
Minimize the scope of the variable as much as possible. Why not connect only when needed? Example,
const string baza = "server=localhost;database=test;user=root;password=;";
private void button1_Click(object sender, EventArgs e)
{
using (MySqlConnection _conn = new MySqlConnection(baza))
{
using (MySqlCommand _comm = new MySqlCommand())
{
_comm.Connection = _conn;
_comm.CommandText = "SELECT IME,PREZIME FROM tabela";
_comm.CommandType = CommandType.Text;
using (MySqlDataAdapter _adapter = new MySqlDataAdapter(_comm))
{
DataTable _table = new DataTable;
try
{
_adapter.Fill(_table);
dataGridView1.DataSource = _table;
}
catch (MySqlException e)
{
MessageBox.Show(e.Message.ToString());
}
}
}
}
}
Related
I have a listbox on a winform that is bound to a datasource with 5 fields on it.
ID,
Dbase,
Schema,
Table,
Security_Groups
The listbox DisplayMember is Table and the ValueMember is ID
Based on the selection made in the list box, I would like to return Dbase and Schema to variables.
Can anyone please advise how this can be achieved?
Table = Tbl_List.GetItemText(Tbl_List.SelectedItem);
Dbase = Tbl_List.GetItemText(Tbl_List.SelectedItem);
Schema = Tbl_List.GetItemText(Tbl_List.SelectedItem);
Many thanks,
Dave
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System;
using System.Data.SqlClient;
namespace Reference_Table_Updater
{
public partial class FrmMain : Form
{
DataTable dt;
String ComboString;
String Dbase;
String Schema;
String strConnection = "server=uk;" +
"Database='Scratchpad';" +
"Integrated Security=SSPI";
public FrmMain()
{
InitializeComponent();
this.Load += Form1_Load;
}
//public class DataSource_Items
//{
// public Int16 Key { get; set;}
// public String Table { get; set; }
// public String Schema { get; set; }
// public String Dbase { get; set; }
//}
public void BindGridView(string field)
{
dt = new DataTable();
SqlConnection connection = new SqlConnection(strConnection);
try
{
connection.Open();
ComboString = Tbl_List.GetItemText(Tbl_List.SelectedItem);
Schema = ((FrmMain)Tbl_List.SelectedItem).Schema;
Dbase = ((FrmMain)Tbl_List.SelectedItem).Dbase;
MessageBox.Show(Dbase + "." + Schema + "." + ComboString);
string sqlStatement = "Select * from " + ComboString;
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
sqlCmd.Parameters.AddWithValue("#Value1", field);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
dataGridView1.DataSource = dt;
}
else
{
// NO RECORDS FOUND
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.updateable_TablesTableAdapter.Fill(this.scratchpadDataSet.Updateable_Tables);
BindGridView(Tbl_List.GetItemText(Tbl_List.SelectedItem));
}
private void Tbl_List_SelectedIndexChanged(object sender, EventArgs e)
{
if (Tbl_List.SelectedValue != null)
{
BindGridView(Tbl_List.GetItemText(Tbl_List.SelectedItem));
}
}
private void BtnUpdate_Click(object sender, EventArgs e)
{
dt.AcceptChanges();
//PASS INSERT/UPDATE/DELETES TO SQL SERVER HERE Passing datatable to a stored procedure if possible -
//I like the TVP option
https://stackoverflow.com/questions/12320594/passing-datatable-to-a-stored-procedure
BindGridView(Tbl_List.GetItemText(Tbl_List.SelectedItem));
}
private void button1_Click(object sender, EventArgs e)
{
FrmAbout F2 = new FrmAbout();
F2.ShowDialog();
}
}
}
OK so I figured it out eventually:
Declared:
DataRowView d1;
String Dbase;
String Schema;
Set:
d1 = Tbl_List.SelectedItem as DataRowView;
Set:
Dbase = d1["Database"].ToString();
Schema = d1["Schema"].ToString();
Punched Dbase and Schema out to two temp text boxes on the form to prove it worked:
this.TBDbase.Text = Dbase;
this.TBSchema.Text = Schema;
Cheers all,
Dave
I have a problem with connecting SQL base with c# code. I have done the database and tried to display if my columns are visible, there aren't any problems, warnings, messages in visual studio, but i can't see data from my base. It is very simple database. I used those tutorial to do this connection: https://www.youtube.com/watch?v=p2UeT7dBTEg] But, i have made one database. Here is the SQL connection part of the program:
public partial class MainWindow : Window
{
SqlConnection connection;
string connectionString;
public MainWindow()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["projekt1.Properties.Settings.Database1ConnectionString"].ConnectionString;
}
private void MainWindow_Load(object sender, EventArgs e)
{
DisplayBMI();
}
private void DisplayBMI()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Table ", connection))
{
DataTable tabelabmi = new DataTable();
adapter.Fill(tabelabmi);
listbmi.DisplayMemberPath = "bmi";
listbmi.SelectedValue = "Id";
listbmi.ItemsSource = tabelabmi.DefaultView;
}
}
Could you try this. I moved DisplayBMI() to MainWindow() constructor.
public partial class MainWindow : Window
{
SqlConnection connection;
string connectionString;
public MainWindow()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["projekt1.Properties.Settings.Database1ConnectionString"].ConnectionString;
DisplayBMI();
}
//private void MainWindow_Load(object sender, EventArgs e)
//{
// DisplayBMI();
//}
private void DisplayBMI()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Table ", connection))
{
DataTable tabelabmi = new DataTable();
adapter.Fill(tabelabmi);
listbmi.DisplayMemberPath = "bmi";
listbmi.SelectedValuePath = "Id";
listbmi.ItemsSource = tabelabmi.DefaultView;
}
}
}
Could someone help me with explaining why I'm getting a null value for DataBoundItem in the following code:
public partial class ucInstanceSearch : UserControl
{
private IStorage tempStorage;
private BindingList<IInstance> instanceData;
public ucInstanceSearch(IStorage new_Storage)
{
InitializeComponent();
this.tempStorage = new_Storage;
instanceData = new BindingList<IInstance>(tempStorage.Instance);
InitalizeInstanceTable();
}
private void InitalizeInstanceTable()
{
dgInstanceTable.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgInstanceTable.MultiSelect = false;
dgInstanceTable.AutoGenerateColumns = false;
dgInstanceTable.RowHeadersVisible = false;
dgInstanceTable.DataSource = instanceData;
}
private void PopulateInstanceTable(String searchFilter)
{
dgInstanceTable.Update();
}
private void dgInstanceTable_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void btnSearch_Click(object sender, EventArgs e)
{
if (txtSearch.Text != "")
{
PopulateInstanceTable(txtSearch.Text);
}
else
{
MessageBox.Show("Enter Data");
}
}
private void btnSelect_Click(object sender, EventArgs e)
{
MessageBox.Show(dgInstanceTable.SelectedRows[0].Cells[2].Value + string.Empty);
DataRow row = (dgInstanceTable.SelectedRows[0].DataBoundItem as DataRowView).Row;
IInstance selected = (IInstance)row;
textBox1.Text = selected.URL;
}
private void ucInstanceSearch_Load(object sender, EventArgs e)
{
}
}
You need to cast your DataBoundItem to type IInstance not DataRowView.
The 'as' opeartor will return null if the type conversion fails. It's safer to cast this directly to the type you expect so that your code will fail if you make a mistake.
I didn't notice a data source in your script. Can you try this?
SQL Server:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string connetionString;
SqlConnection connection;
SqlDataAdapter adapter;
SqlCommandBuilder cmdBuilder;
DataSet ds = new DataSet();
DataSet changes;
string Sql;
Int32 i;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
Sql = "select * from Product";
try
{
connection.Open();
adapter = new SqlDataAdapter(Sql, connection);
adapter.Fill(ds);
connection.Close();
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
cmdBuilder = new SqlCommandBuilder(adapter);
changes = ds.GetChanges();
if (changes != null)
{
adapter.Update(changes);
}
MessageBox.Show("Changes Done");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
MS Access:
using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string connetionString;
OleDbConnection connection;
OleDbDataAdapter oledbAdapter;
OleDbCommandBuilder oledbCmdBuilder;
DataSet ds = new DataSet();
DataSet changes;
int i;
string Sql;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
Sql = "select * from tblUsers";
try
{
connection.Open();
oledbAdapter = new OleDbDataAdapter(Sql, connection);
oledbAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
oledbCmdBuilder = new OleDbCommandBuilder(oledbAdapter);
changes = ds.GetChanges();
if (changes != null)
{
oledbAdapter.Update(ds.Tables[0]);
}
ds.AcceptChanges();
MessageBox.Show("Save changes");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
I need some help. I've been working with a colleague, trying to refresh datagridview on form1 each time form 2 is closed. Unfortunately, none of the previous questions he has asked on have been helpful in working towards our solution because we're both new to C#. As a result, I've opted to copy and paste the entirety of our code here.
We're not too sure what goes into public void RefreshGridView (to refresh datagridview1 on form1) and how to have it run from the form2 closing action i.e. private void Form2_FormClosed.
Form 1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PGPTool
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dbDataSet.PGP' table. You can move, or remove it, as needed.
this.pGPTableAdapter.Fill(this.dbDataSet.PGP);
}
// new
private void new_btn_Click(object sender, EventArgs e)
{
var cell1 = "";
var cell2 = "";
Form2 Form2 = new Form2(cell1, cell2);
Form2.Show();
}
// clear
private void clear_btn_Click(object sender, EventArgs e)
{
search_txt.Text = "";
}
// search
private void search_btn_Click(object sender, EventArgs e)
{
searchData();
}
private void search_txt_TextChanged(object sender, EventArgs e)
{
searchData();
}
private void searchData()
{
BindingSource bs = new BindingSource();
bs.DataSource = dataGridView1.DataSource;
bs.Filter = "PGP like '%" + search_txt.Text + "%' or Team like '%" + search_txt.Text + "%'";
dataGridView1.DataSource = bs;
}
// edit
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
var selectedRow = dataGridView1.CurrentRow;
var cell1 = Convert.ToString(selectedRow.Cells[0].Value);
var cell2 = Convert.ToString(selectedRow.Cells[1].Value);
Form2 Form2 = new Form2(cell1, cell2);
Form2.Show();
}
// copy to clipboard
private bool isCellClicked = false;
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
var hit = dataGridView1.HitTest(e.X, e.Y);
isCellClicked = (hit.Type == DataGridViewHitTestType.Cell);
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
e.Cancel = !isCellClicked;
}
private void copyToolStripMenuItem1_Click(object sender, EventArgs e)
{
Clipboard.SetText(Convert.ToString(dataGridView1.CurrentCell.Value));
}
// refresh grid
public void RefreshGridView()
{
}
}
}
Form 2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace PGPTool
{
public partial class Form2 : Form
{
public Form2(string cell1, string cell2)
{
InitializeComponent();
pgpText.Text = cell1;
pgpOld.Text = cell1;
teamText.Text = cell2;
}
private void pgpText_TextChanged(object sender, EventArgs e)
{
pgpText.CharacterCasing = CharacterCasing.Upper;
}
private void teamText_TextChanged(object sender, EventArgs e)
{
teamText.CharacterCasing = CharacterCasing.Upper;
}
private void save_btn_Click(object sender, EventArgs e)
{
if (pgpText.Text.Trim().Length == 0)
{
MessageBox.Show("Please fill the following textbox: PGP");
}
else if (teamText.Text.Trim().Length == 0)
{
MessageBox.Show("Please fill the following textbox: Team");
}
else
{
using (OleDbConnection conn = new OleDbConnection())
{
string pgp_new = pgpText.Text;
string pgp_old = pgpOld.Text;
string team = teamText.Text;
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='db.mdb'";
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText = "UPDATE PGP SET PGP=?,Team=? WHERE PGP=?";
command.Parameters.Add("pgp_new", OleDbType.VarChar).Value = pgp_new;
command.Parameters.Add("team", OleDbType.VarChar).Value = team;
command.Parameters.Add("pgp_old", OleDbType.VarChar).Value = pgp_old;
conn.Open();
int affectedRows = (int)command.ExecuteNonQuery();
if (affectedRows == 0)
{
command.CommandText = "INSERT INTO PGP (PGP,Team) VALUES (?, ?)";
command.Parameters.RemoveAt(2);
command.ExecuteNonQuery();
if (MessageBox.Show("Table Saved!", "Update", MessageBoxButtons.OK) == DialogResult.OK)
{
this.Close();
}
}
if (affectedRows > 0)
{
if (MessageBox.Show("Table Saved!", "Update", MessageBoxButtons.OK) == DialogResult.OK)
{
this.Close();
}
}
}
}
}
private void cancel_btn_Click(object sender, EventArgs e)
{
this.Close();
}
private Form1 Form1Instance
{
get;
set;
}
public Form2(Form1 form1Instance)
{
Form1Instance = form1Instance;
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
}
}
}
You can simply capture the close event of Form2 from Form1.
It is really easy
private void new_btn_Click(object sender, EventArgs e)
{
var cell1 = "";
var cell2 = "";
Form2 Form2 = new Form2(cell1, cell2);
Form2.FormClosed += Form2HasBeenClosed;
Form2.Show();
}
private void Form2HasBeenClosed(object sender, FormClosedEventArgs e)
{
// Inside the form1 call your RefreshGridView
}
You should raise an event in Form2 when it is closing in either FormClosing or FormClosed events. Then your Form1 should subscribe to that event and handle it. In the event handler you can then refresh your grid view.
Refer to this article in MSDN for further information about events: http://msdn.microsoft.com/en-us/library/awbftdfh.aspx
I'm trying to access an event in my main form by clicking a button (btnsearch_Click) and everytime I clicked it, it says 'object reference not set to an instance of an object'.
Here is my code:
USER CONTROL
namespace Purchase_Order
{
public partial class Search : UserControl
{
public event EventHandler btnSearchClicked;
public Search()
{
InitializeComponent();
}
private void btnsearch_Click(object sender, EventArgs e)
{
btnSearchClicked(sender, e);
}
}
}
MAIN FORM
namespace Purchase_Order
{
public partial class formMain : Form
{
public formMain()
{
InitializeComponent();
}
private void formMain_Load(object sender, EventArgs e)
{
Search searchbox = new Search();
searchbox.btnSearchClicked += new EventHandler(SearchClicked);
}
void SearchClicked(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(serverstring);
try
{
string query = "SELECT * FROM tblclassification WHERE INSTR(class_name, #search)";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
Search content = new Search();
cmd.Parameters.AddWithValue("#search", content.btnsearch.Text);
DataTable dt = new DataTable();
da.Fill(dt);
classification control = new classification();
control.dataGridView1.DataSource = dt;
control.dataGridView1.DataMember = dt.TableName;
panelMain.Controls.Clear();
panelMain.Controls.Add(control);
MessageBox.Show("OK");
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
You are creating a new instance of your user control in SearchClicked method and you are not registering the event against it.
Search content = new Search();
Also its better if you check whether any control has register your event before raising it like:
private void btnsearch_Click(object sender, EventArgs e)
{
if(btnSearchClicked != null)
btnSearchClicked(sender, e);
}
That means that you haven't got an instance of the type you want to use.
public event EventHandler btnSearchClicked; is just a reference for the "real" object you want to use.
It's like you trying to open a door of a house you only have a blueprint. This isn't really possible (at least not in our universe). You will first need to build the house and then try to enter it. Something like this is the case with your problem.
You will have to read a few tutorials about C#
Edit:
The thing about null is that there is nothing the reference you have is pointing too. If you haven't created anything then there isn't anything to reference...
Because you are trying to use something that doesn't exists (is null) you are getting an exception.
To try and expand a little on Habib's answer (I was going to post this as a comment but it's a little lengthy), you are first creating an instance of Search and registering the event in formMain_Load here:
private void formMain_Load(object sender, EventArgs e)
{
Search searchbox = new Search();
searchbox.btnSearchClicked += new EventHandler(SearchClicked);
}
This is all fine and dandy. However, in SearchClicked, you create a new instance of Search like so:
Search content = new Search();
This is a separate object to the one you created in formMain_Load and you never register the event to this object. It looks like what you want to do is share the Search instance from formMain_Load with the SearchClicked method. To do this, create a property in your codebehind:
public partial class formMain : Form
{
private Search _searchbox;
...
}
Then, in formMain_Load:
private void formMain_Load(object sender, EventArgs e)
{
_searchbox = new Search();
_searchbox.btnSearchClicked += new EventHandler(SearchClicked);
}
Now, you can reuse this object with the event registered in SearchClicked by changing this:
Search content = new Search();
To this:
Search content = _searchbox;
You should find that the exception goes away. Hopefully, this will have provided a little more insight and will help you to understand the cause of the error and how to circumvent it.
Share the Search instance from formMain_Load with the SearchClicked method
MAIN FORM
public partial class formMain : Form
{
private Search _searchbox;
...
private void formMain_Load(object sender, EventArgs e)
{
_searchbox = new Search();
_searchbox.btnSearchClicked += new EventHandler(SearchClicked);
}
void SearchClicked(object sender, EventArgs e)
{
Search content = _searchbox;
MySqlConnection con = new MySqlConnection(serverstring);
try
{
string query = "SELECT * FROM tblclassification WHERE INSTR(class_name, #search)";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("#search", content.btnsearch.Text);
DataTable dt = new DataTable();
da.Fill(dt);
classification control = new classification();
control.dataGridView1.DataSource = dt;
control.dataGridView1.DataMember = dt.TableName;
panelMain.Controls.Clear();
panelMain.Controls.Add(control);
MessageBox.Show("OK");
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
}
USER CONTROL
public partial class Search : UserControl
{
public event EventHandler btnSearchClicked;
public Search()
{
InitializeComponent();
}
private void btnsearch_Click(object sender, EventArgs e)
{
btnSearchClicked(sender, e);
}
}