C# DataGridView BindingList - c#

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

Related

Data in the MySql database not displaying in the datagridview Windows form, C#

I did the following code, and when i insert data by clicking the 'addbtn', it inserts to the MYSQL database. I can view the inserted data by going to localhost/phpmyadmin. but the data doesn't show up in the windows form.
How can i fix this? The first code is the Dbconnection.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace dbtest
{
class Dbstudent
{
public static MySqlConnection GetConnection()
{
string sql = "datasource=localhost;port=3306;username=root;password=;database=student";
MySqlConnection con = new MySqlConnection(sql);
try
{
con.Open();
}
catch(MySqlException ex )
{
MessageBox.Show("MySql connection! \n"+ex.Message, "Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
return con;
}
public static void Addstudent(student std)
{
string sql = "INSERT INTO studentinfo VALUES(NULL,#Studentnic,#StudentName,#StudentAddress)";
MySqlConnection con = GetConnection();
MySqlCommand cmd = new MySqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#Studentnic", MySqlDbType.VarChar).Value = std.nic;
cmd.Parameters.Add("#StudentName", MySqlDbType.VarChar).Value = std.name;
cmd.Parameters.Add("#StudentAddress", MySqlDbType.VarChar).Value = std.address;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Added Succesfully.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(MySqlException ex)
{
MessageBox.Show("Student not inserted \n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
con.Close();
}
public static void DisplayAndSearch(String query,DataGridView dgv)
{
string sql = query;
MySqlConnection con = GetConnection();
MySqlCommand cmd = new MySqlCommand(sql, con);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataTable tbl = new DataTable();
adp.Fill(tbl);
dgv.DataSource = tbl;
con.Close();
}
}
}
The second code is the Form1.cs
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace dbtest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Display()
{
Dbstudent.DisplayAndSearch("SELECT ID,NIC,Name,Address FROM studentinfo",dataGridView1);
}
public void Clear()
{
txtnic.Text = txtname.Text = txtaddress.Text = string.Empty;
}
private void button1_Click(object sender, EventArgs e)
{
if(txtnic.Text.Trim().Length<11 || txtnic.Text.Trim().Length > 11)
{
MessageBox.Show("Student NIC must include 11 characters");
return;
}
if (txtname.Text.Trim().Length < 2 )
{
MessageBox.Show("Student name must not be empty");
return;
}
if (txtaddress.Text.Trim().Length < 2)
{
MessageBox.Show("Student address must not be empty");
return;
}
if(addbtn.Text=="ADD")
{
student std = new student(txtnic.Text.Trim(),txtname.Text.Trim(), txtaddress.Text.Trim());
Dbstudent.Addstudent(std);
Clear();
}
Display();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void idlabel_Click(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
Display();
}
}
}
try this >
DataTable dt = new DataTable("CharacterInfo");
& then
dgv.DataSource =tbl.DefaultView;

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

Working with datagridview across different forms

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

Delete and Update ms access database using a datagridview and navigator binding in c#

Hi i'm busy doing a project i'm trying to update and delete the data into y access database from my datagridview. it does delete it in the datagridview but it does not go save the change in the database thus never update or delete in the real database. thanks for your help. Here is y code:
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 Church_Network
{
public partial class Form11 : Form
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ELPARAISO\Desktop\icons\Church Network1\Church Network1\Church Network\Project.accdb");
OleDbDataAdapter ad = new OleDbDataAdapter();
DataSet ProjectDataSet3 = new DataSet();
public Form11()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
saveToolStripButton.PerformClick();
MessageBox.Show("updated");
}
private void button5_Click(object sender, EventArgs e)
{
try
{
ad.SelectCommand = new OleDbCommand("select* from Member ", con);
ProjectDataSet3.Clear();
ad.Fill(ProjectDataSet3);
dataGridView1.DataSource = ProjectDataSet3.Tables[0];
con.Open();
ad.SelectCommand.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form11_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'projectDataSet3.Member' table. You can move, or remove it, as needed.
this.memberTableAdapter.Fill(this.projectDataSet3.Member);
}
private void button6_Click(object sender, EventArgs e)
{
Form8 f8 = new Form8();
f8.Show();
}
private void button2_Click(object sender, EventArgs e)
{
bindingNavigatorDeleteItem.PerformClick();
MessageBox.Show("deleted");
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
You have to add commands for deleting and updating your Database. I can't see something like this in your code.
So try to add something like:
private void BtnDelete_Click(object sender, RoutedEventArgs e)
{
DataRowView drv = (DataRowView)dataGridView1.SelectedItem;
int id = drv.Row[0];
if(drv != null)
{
delete(id);
}
}
public void delete(int id)
{
try
{
con.Open();
OleDbCommand comm = new OleDbCommand("delete from Member where id=#id", con);
comm.Parameters.AddWithValue("#id", id);
comm.ExecuteNonQuery();
}
catch(OleDbException ex)
{
MessageBox.Show("DataConnection not found!", ex);
}
finally
{
con.Close();
}
And the same thing would be needed for updating the Db.

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