C# + SQL connection issue - c#

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;
}
}
}

Related

How to get different member of a datasource from Listbox.SelectedItem

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

C# - Change label text from another class

I am a total noob on C# and I'm stuck on changing the status label text from an other class.
When this class connects to db I want to change the label text to "Connected":
public class DBConnect
{
public void Connect()
{
MySqlConnection conn;
string myConnectionString;
myConnectionString = "server = 127.0.0.1; uid=cardb;" +
"pwd=cardb; database=test;";
try
{
Form form = new Form();
conn = new MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
form.setStatus();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
This is the method setStatus I created in Form class:
public partial class Form : System.Windows.Forms.Form
{
public Form()
{
InitializeComponent();
}
public void setStatus()
{
StatusTextLabel.Text = "Connected";
}
The label text doesnt change though.. :/
I see no code to create a DBConnect object, or to call its Connect() method, and no code that makes the Form object visible, e.g. form.Show().
Other than that you probably should not create the Form from the Connect method; instead call Connect() from the Form, e.g. in Form_Load(), let it return a status, or better: the conn object (which you are now throwing away after connection), and make Form_Load set the Label.Text based on that.
Example code:
private void Form1_Load(object sender, EventArgs e)
{
var conn = new DBConnect().Connect();
if (conn != null && conn.State == ConnectionState.Open)
{
StatusTextLabel.Text = "Connected";
}
}
public class DBConnect
{
public SqlConnection Connect()
{
SqlConnection conn = ...
// ...
return conn;
}
}
Instead of creating an instance of a new Form, you probably need an instance of already opened form and call the method from there. You can try:
(System.Windows.Forms.Application.OpenForms["Form"] as Form).setStatus();
Pass the form instead of creating a new one.
private Form form {get;set;}
public DBConnect(Form form)
{
this.form = form;
}
Then try this
form.Invoke(new MethodInvoker(() => form.setStatus()));

C# DataGridView BindingList

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());
}
}
}
}

C#: Class/Method That Builds Connection

Completely new to C#.
In my app, several buttons will connection to MySql and pass information to and from it. Each button has it's own connection string, which I find redundant and was curious if there was a way in C# to build a Class or Method, holding the connection string, and call the connection in each button, instead of establishing the connection, then calling it.
I tried building a Public Method which used MySqlConnection mycon parameter and had it return mycon, however, in the other buttons, it saw mycon as a method, not an object. From there I tried a Class (using syntax from dotnetperls and other sites), which have yielded other errors about type. Clearly, being new to this, I am approaching the wrong syntax to build a Class and Method, though I'm assuming that since a Method will be an action, I am actually seeking a class that will hold the objects and allow other parts of the program to access it.
See below pseudo-code as an example:
Current
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection mycon = new MySqlConnection();
mycon.ConnectionString = "Connection";
mycon.Open();
// Code
mycon.Close();
}
private void button2_Click(object sender, EventArgs e)
{
MySqlConnection mycon = new MySqlConnection();
mycon.ConnectionString = "Connection";
mycon.Open();
// Code
mycon.Close();
}
private void button3_Click(object sender, EventArgs e)
{
MySqlConnection mycon = new MySqlConnection();
con.ConnectionString = "Connection";
mycon.Open();
// Code
mycon.Close();
}
Goal:
Some Class
{
//MySqlConnection parameters establish mycon
}
private void button1_Click(object sender, EventArgs e)
{
mycon.Open();
// Code
mycon.Close();
}
private void button2_Click(object sender, EventArgs e)
{
mycon.Open();
// Code
mycon.Close();
}
private void button3_Click(object sender, EventArgs e)
{
mycon.Open();
// Code
mycon.Close();
}
Note: I am aware of the XML approach (and have used it in another one of my programs), but am trying to see if there's a Class/Method approach.
I'd suggest having a method (can probably be static, and exist in a place accessible from anywhere in your code) that deals with all the details of getting a connection, and returns it. Then anywhere you need a connection, call that method.
class SomeClass
{
private void button1_Click(object sender, EventArgs e)
{
using (var conn = Utilities.GetConnection())
{
conn.Open();
// Code
}
}
}
public static class Utilities
{
public static MySqlConnection GetConnection()
{
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = "Connection";
return conn;
}
}
And use using to ensure that the connection is always closed. It's usually good practice to do this with any IDisposable that you use.
For some info/duscussion on whether Open() should be in GetConnection() or not, see using statement with connection.open
Use a static method to create connection, and using shorthand to close/dispose it:
SomeClass
{
public static MySqlConnection CreateConnection()
{
MySqlConnection mycon = new MySqlConnection();
mycon.ConnectionString = "Connection";
mycon.Open();
return mycon;
}
}
private void button1_Click(object sender, EventArgs e)
{
using (MySqlConnection conn = SomeClass.CreateConnection())
{
}
}
class SomeClass : IDisposable
{
SqlConnection conn;
public SomeClass
{
conn = new SqlConnection("some connectionstring");
}
public void Open()
{
conn.Open()
}
public void Close()
{
conn.Close()
}
public void Dispose()
{
conn.Dispose()
}
}
I would do something like this:
public class DataBase
{
private static string DEFAULT_CONNECTION_STRING = "*your connection string*";
private string connectionString;
private DbProviderFactory factory;
public DataBase()
{
connectionString = DEFAULT_CONNECTION_STRING;
factory = DbProviderFactories.GetFactory("MySql.Data.MySql");
}
public IDataReader GetData(string sql)
{
using(var conn = factory.CreateConnection())
using(var command = factory.CreateCommand())
{
command.CommandText = sql;
command.CommandType = CommandType.Text;
conn.ConnectionString = this.connectionString;
conn.Open();
command.Connection = conn;
return cmd.ExecuteReader();
}
}
}

Connecting C# to MySQL and opening connection

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());
}
}
}
}
}

Categories

Resources