My problem is that I can't print out all the data from the table in my mysql database, I got out just last row in the given table "teacher". is there anyone who can help me find the error?
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 MySql.Data.MySqlClient;
namespace ReadDataFromMysql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string sql = " SELECT * FROM teacher ";
MySqlConnection con = new MySqlConnection("host=localhost;user=root;password=859694;database=projekt;");
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) {
data2txt.Text = reader.GetString("id");
datatxt.Text = reader.GetString("userId");
}
}
private void btnclose_Click(object sender, EventArgs e)
{
Close();
}
}
}
Your problem is that you are overwriting data2txt.Text and datatxt.Text on each row of data. if you want to see all of the data in those fields, something like this should do what you need:
data2txt.Text = string.Empty;
datatxt.Text = string.Empty;
while (reader.Read())
{
data2txt.Text += $"{reader.GetString("id")};";
datatxt.Text += $"{reader.GetString("userId")};";
}
You're assigning the value of each field instead of the value of the existing control's text plus the new value. Add a breakpoint to make sure you're getting multiple rows, but as your code is written, you would only see the result of one row in your form because you're overwriting on each iteration through the loop.
This code works.
private void getdata()
{
MySqlConnection connect = new MySqlConnection("SERVER=localhost; user id=root; password=; database=databasename");
MySqlCommand cmd = new MySqlCommand("SELECT ID, name FROM data WHERE ID='" + txtid.Text + "'");
cmd.CommandType = CommandType.Text;
cmd.Connection = connect;
connect.Open();
try
{
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while(dr.Read())
{
txtID.Text = dr.GetString("ID");
txtname.Text = dr.GetString("name");
}
dr.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if(connect.State == ConnectionState.Open)
{
connect.Close();
}
}
Obviously your code shows the last row values of teacher table into your text fields on form.Because your are looping throught the datareader and assigning the values to textfiled.So each iteration it will overwright the previous values in textbox.
You should output the data before again writing in it:
data2txt.Text = reader.GetString("id");
datatxt.Text = reader.GetString("userId");
Or use a var to store all the data in with each 'read' and then output that var
varexample.Text += reader.GetString("id");
Related
I wrote the following program in C#
I have no problem when inserting information in the database
But when deleting information and during debugging, it gets an error on the following
line
cmd.executenonquery();
using System;
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;
using System.Data.OleDb;
namespace _01_AccessTestDB
{
public partial class frmUser : Form
{
public frmUser()
{
InitializeComponent();
}
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=TestDB.accdb");
OleDbCommand cmd = new OleDbCommand();
void display()
{
DataSet ds = new DataSet();
OleDbDataAdapter adp = new OleDbDataAdapter();
cmd.CommandType = CommandType.Text;
adp.SelectCommand=new OleDbCommand();
adp.SelectCommand.Connection= con;
adp.SelectCommand.CommandText="select * from TBLUser";
adp.Fill(ds, "TBLUser");
dgvUser.DataSource=ds;
dgvUser.DataMember=("TBLUser");
dgvUser.Columns[0].HeaderText="کد";
dgvUser.Columns[1].HeaderText="نام کاربری";
dgvUser.Columns[2].HeaderText="کلمه عبور";
}
private void frmUser_Load(object sender, EventArgs e)
{
display();
}
private void btnSave_Click(object sender, EventArgs e)
{
cmd.Parameters.Clear();
cmd.Connection = con;
con.Open();
cmd.CommandText="insert into TBLUser(ID,UserN,Pass)values(#a,#b,#c)";
cmd.Parameters.AddWithValue("#a", txtCode.Text);
cmd.Parameters.AddWithValue("#b", txtUser.Text);
cmd.Parameters.AddWithValue("#c", txtPass.Text);
cmd.ExecuteNonQuery();
con.Close();
string message, title;
title="تعریف کاربران";
message="اطلاعات جدید با موفقیت ثبت گردید";
MessageBox.Show(message, title, MessageBoxButtons.OK,
MessageBoxIcon.Information);
txtCode.Clear();
txtUser.Clear();
txtPass.Clear();
display();
}
The program is running correctly so far, but it encountered a problem in the data deletion section
private void btnDelet_Click(object sender, EventArgs e)
{
int h = Convert.ToInt32(dgvUser.SelectedCells[0].Value);
cmd.Parameters.Clear();
cmd.Connection=con;
cmd.CommandText="delet from TBLUser Where ID=#N";
cmd.Parameters.AddWithValue("#N", h);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
string message, title;
title="تعریف کاربران";
message="اطلاعات حذف گردید";
MessageBox.Show(message, title, MessageBoxButtons.OK,
MessageBoxIcon.Information);
display();
}
}
}
Change from
cmd.CommandText="delet from TBLUser Where ID=#N";
To
cmd.CommandText="delete from TBLUser Where ID=#N";
Also follow #user18387401 recommendations
In regards to cmd.Parameters.AddWithValue, use cmd.Parameters.Add instead.
Edit
Here is a model to use for removing a record use SQL-Server in .NET Core. Since you are using Access the connection and command change to OleDb. So don't copy-n-paste this code, adapt to your current code. The Remove method should reside in a separate class but can reside in the form.
Best to add in a BindingSource, this way cast someBindingSource.Current to whatever the current row in the DataGridView is e.g. if the source is a DataTable use ((DataRow)someBindingSource.Current).Row.Field... to get the primary key to use for deleting. Once the record is removed use someBindingSource.RemoveCurrent() to remove the record from your DataGridView.
public static (bool success, Exception exception) Remove(int identifier)
{
using var cn = new SqlConnection("TODO");
using var cmd = new SqlCommand
{
Connection = cn,
CommandText = "DELETE FROM TBLUser WHERE Id = #Identifier;"
};
try
{
cn.Open();
cmd.Parameters.Add("#Identifier", SqlDbType.Int).Value = identifier;
cmd.ExecuteNonQuery();
return (true, null);
}
catch (Exception localException)
{
return (false, localException);
}
}
Usage in your form (DataOperations is a separate class)
var (success, exception) = DataOperations.Remove(identifier);
if (success)
{
// record removed
}
else
{
// deal with exception using exception variable
}
I am trying to select data from multiple MySQL tables in one simple statement, my problem however is when I try to run it I get the following error:
An exception of type 'System.Exception' occurred in MySql.Data.dll but was not handled in user code
Additional information: No current query in data reader
The code I am using to run the statement is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class RetrieveCars : System.Web.UI.Page
{
String Model;
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String queryStr;
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["model_id"] != null)
{
Model = Request.QueryString["model_id"];
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "SELECT c.CarID, c.RegNumber, c.Colour , m.CarModel, m.CarMake, m.CostPerDay FROM car c INNER JOIN model m ON m.ModelID=c.ModelID WHERE c.ModelID = '" + Model + "'";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
reader = cmd.ExecuteReader();
reader.Close();
conn.Close();
CarN.Text = reader.GetString(reader.GetOrdinal("CarModel"));
}
}
}
}
You are closing the reader and connection before getting any data. Just move the .Close() calls to the end of the function.
You also need to call Read() on the reader to actually get a row of data.
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
reader = cmd.ExecuteReader();
// Read() will return a bool indicating whether a new row has been read
// false signals no more data
while (reader.Read()) {
// Do something with the row data
CarN.Text = reader.GetString(reader.GetOrdinal("CarModel"));
}
reader.Close();
conn.Close();
I have two tables in my database. Let's say table A and table B. table A values are put in checkedlistbox. The selected values in checkedlistbox then are put into table B. I tried to make a code however it wont work. Do you have any idea on how to make this problem work?
thanks ahead guys.
by the way im using c#.
using System;
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;
using Npgsql;
namespace WindowsFormsApplication1
{
public partial class Form8 : Form
{
public Form8()
{
InitializeComponent();
this.Load += Form8_Load;
button2.Click += button2_Click;
}
private void Form8_Load(object sender, EventArgs e)
{
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("SELECT conname FROM condition", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
using (NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
((ListBox)checkedListBox1).DataSource = dt;
((ListBox)checkedListBox1).DisplayMember = "conname";
((ListBox)checkedListBox1).DisplayMember = "conid";
string[] condition = dt.Rows[0]["conname"].ToString().Split(',');
}
}
private void button2_Click(object sender, EventArgs e)
{
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("Insert into famhistory(famid) Values (#famid)", conn);
conn.Open();
cmd.Parameters.AddWithValue("#famid", checkedListBox1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data has been saved");
conn.Close();
}
}
}
You have to iterate through all the selected items:
//check if any item is selected
if (checkedListBox1.SelectedItems.Count > 0)
{
//connect to database
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
//loop through all selected items
foreach (object item in checkedListBox1.CheckedItems)
{
//convert item to string
string checkedItem = item.ToString();
//insert item to database
NpgsqlCommand cmd = new NpgsqlCommand("Insert into famhistory(famid) Values (#famid)", conn);
cmd.Parameters.AddWithValue("#famid", checkedItem); //add item
cmd.ExecuteNonQuery();
}
//close connection
conn.Close();
MessageBox.Show("Data has been saved");
}
Note: I am executing all insert commands in one open connection, because opening and closing connection frequently is not best practice.
i want to delete the row of data from the database, currently i can delete the row of data by clicking on the delete button, but the database Table is not updated, how do i do so?
using System;
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 project
{
public partial class frmTestPrint : Form
{
public frmTestPrint()
{
InitializeComponent();
}
private void frmTestPrint_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'usersDataSet1.Booking' table. You can move, or remove it, as needed.
this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);
}
private void btnDelete_Click(object sender, EventArgs e)
{
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
}
}
}
private void Delete()
{
int i = 0;
con1 = getConnection();
con1.Open();
SqlCommand storedProcedureCommand = con1.CreateCommand();
storedProcedureCommand.CommandType = CommandType.Text;
storedProcedureCommand.CommandText = "DELETE FROM name of your table WHERE pkeyID = #pkeyID";
SqlParameter inparam2 = new SqlParameter("#pkeyID", SqlDbType.Int);
inparam2.Direction = ParameterDirection.Input;
inparam2.Value = Convert.ToInt32(dataGridView2.Rows[i].Cells[0].Value);
storedProcedureCommand.Parameters.Add(inparam2);
storedProcedureCommand.ExecuteNonQuery();
}
This is only to delete one at a time. I am still working on multiple deletes.
if (MessageBox.Show("Sure you wanna delete?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
{
//get the index from the dataGridView
int rowIndex = table1DataGridView.CurrentCell.RowIndex;
//Remove from both the actual database & datagridview
table1BindingSource.RemoveAt(rowIndex);
//update table 1
this.table1TableAdapter.Update(this.maquinasDataSet.Table1);
//load table 1
this.table1TableAdapter.Fill(this.maquinasDataSet.Table1);
}
You're not actually impacting the database at all. Perhaps this will help:
How to delete a selected DataGridViewRow and update a connected database table?
Have you explored the .Update method you get with the TableAdapter? I think that should cover what you're after. http://msdn.microsoft.com/en-us/library/bz9tthwx(v=vs.100).aspx
Does this work:
private void btnDelete_Click(object sender, EventArgs e)
{
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
this.bookingTableAdapter.Update(this.usersDataSet1.Booking);
}
if that doesn't work, you're going to have to come back w/ an error message or hopefully someone who knows what they're doing can come bail me out...
Delete a value from the data grid using DataGridviewBUttonColumn
private void delete_record()
{
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
{
try
{
//am taking connection string using a class called "sqlconnection_imventory()"
SqlConnection conn = Connection.sqlconnection_imventory();
//Cell[0] is my button column & Cell[1] is SID coumn
string a = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
string sql = "DELETE FROM grades WHERE SID='" + a + "'";
conn.Open();
SqlCommand delcmd = new SqlCommand(sql, conn);
delcmd.Connection = conn;
delcmd.ExecuteNonQuery();
conn.Close();
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
MessageBox.Show("deleted");
}
catch (Exception)
{
throw;
}
}
}
I'm getting the error 'Object reference not set to an instance of an object'. I've tried looking at similar problems but genuinely cannot see what the problem is with my program. The line of code that I am having an error with is:
labelQuestion.Text = table.Rows[0]["Question"].ToString();
Here is my code in its entirety:
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;
using System.Data.Sql;
using System.Data.SqlClient;
namespace Quiz_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String chosenAnswer, correctAnswer;
DataTable table;
private void Form1_Load(object sender, EventArgs e)
{
//declare connection string using windows security
string cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\QuizQuestions.accdb";
//declare Connection, command and other related objects
OleDbConnection conGet = new OleDbConnection(cnString);
OleDbCommand cmdGet = new OleDbCommand();
//try
//{
//open connection
conGet.Open();
//String correctAnswer;
cmdGet.CommandType = CommandType.Text;
cmdGet.Connection = conGet;
cmdGet.CommandText = "SELECT * FROM QuizQuestions ORDER BY rnd()";
OleDbDataReader reader = cmdGet.ExecuteReader();
reader.Read();
labelQuestion.Text = table.Rows[0]["Question"].ToString();
radioButton1.Text = table.Rows[0]["Answer 1"].ToString();
radioButton2.Text = table.Rows[0]["Answer 2"].ToString();
radioButton3.Text = table.Rows[0]["Answer 3"].ToString();
radioButton4.Text = table.Rows[0]["Answer 4"].ToString();
correctAnswer = table.Rows[0]["Correct Answer"].ToString(); ;
conGet.Close();
}
private void btnSelect_Click(object sender, EventArgs e)
{
String cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\QuizQuestions.accdb";
//declare Connection, command and other related objects
OleDbConnection conGet = new OleDbConnection(cnString);
OleDbCommand cmdGet = new OleDbCommand();
//try
{
//open connection
conGet.Open();
cmdGet.CommandType = CommandType.Text;
cmdGet.Connection = conGet;
cmdGet.CommandText = "SELECT * FROM QuizQuestions ORDER BY rnd()"; // select all columns in all rows
OleDbDataReader reader = cmdGet.ExecuteReader();
reader.Read();
if (radioButton1.Checked)
{
chosenAnswer = reader["Answer 1"].ToString();
}
else if (radioButton2.Checked)
{
chosenAnswer = reader["Answer 2"].ToString();
}
else if (radioButton3.Checked)
{
chosenAnswer = reader["Answer 3"].ToString();
}
else
{
chosenAnswer = reader["Answer 4"].ToString();
}
if (chosenAnswer == reader["Correct Answer"].ToString())
{
//chosenCorrectly++;
MessageBox.Show("You have got this answer correct");
//label2.Text = "You have got " + chosenCorrectly + " answers correct";
}
else
{
MessageBox.Show("That is not the correct answer");
}
}
}
}
}
I realise the problem isn't too big but I can't see how my declaration timings are wrong
You never initialize table, so it will be null when you try to access its Rows property.
You don't actually need the DataTable in this instance, though. You can access the properties directly from the OleDbDataReader (which you do initialize.) See here for details (look at the Get***() family of methods.)
Something like:
labelQuestion.Text = reader.GetString(reader.GetOrdinal("Question"));
And so forth for the rest of the columns.
If you do choose to use table, then omit the reader.Read() line and add:
table = new DataTable();
table.Load(reader);
The problem is that your table is not initialized. Therefore, when you try to access table.row[0] you get this error message.
And If there was no question column, you would probably get an error like
Column ‘Question’ does not belong to table.
Hence, at this point it is not ok. to say whether there is 'Question' column or not. First, you need to fill your table.
Right after you call ExecuteReader () in Form1_Load you need
table = new DataTable();
table.Load (reader);
Error object reference Null:
try
{
OleDbCommand com;
// OleDbConnection con = new OleDbConnection(ConnectionString);
cn.Open();
string str = "select *from DatabaseLogin where user_id='" + textBox2.Text + "'";
com = new OleDbCommand(str, cn);
OleDbDataReader reader = com.ExecuteReader();
while (reader.Read())
{
checkedListBox1.Items.Add(reader["stckdemge"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(" " + ex);
}
Either the table has no rows, or there is no "Question" column, or that the column has a Null value in it.
Consider breaking the assignment up into multiple steps to help you diagnose the issue.
EDIT:
Or, as sharper eyes have already noted, it's because you've not assigned anything to 'table' (d'oh).
The comment about breaking up the assignment is a useful diagnostic method, though.