I am trying to load data into a textbox by using a DataReader depend on the Drop down list selection. Didn't get error from this code, but the data is not loaded into textbox. please correct me.
public void text()
{
cn1.Open();
string s;
s = "select Request_Type from component where Material_Code='" + Mcodeddl.SelectedItem.Text + "' ";
SqlCommand cd1 = new SqlCommand(s, cn1);
SqlDataReader rd;
try
{
rd = cd1.ExecuteReader();
while (rd.Read())
{
TextBox4.Text = rd["Request_Type"].ToString().Trim();
}
rd.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
cd1.Dispose();
cn1.Close();
}
}
public void MC()
{
Mcodeddl.Items.Clear();
ListItem li1 = new ListItem();
li1.Text = "-Select-";
Mcodeddl.Items.Add(li1);
Mcodeddl.SelectedIndex = 0;
cn1.Open();
string s1;
s1 = "select Material_Code from component";
SqlCommand cd1 = new SqlCommand(s1, cn1);
SqlDataReader dr1;
try
{
dr1 = cd1.ExecuteReader();
while (dr1.Read())
{
ListItem ni1 = new ListItem();
ni1.Text = dr1["Material_Code"].ToString().Trim();
Mcodeddl.Items.Add(ni1);
}
dr1.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
cd1.Dispose();
cn1.Close();
}
}
If everything works fine without exceptions that is mean the connection established correctly and the SQL command is correct. I think you have to make sure about your SQL statement. Maybe it returns nothing because there are no matches.
We need more explain about your issue.
Related
and sorry for the inconvenience. I hope you can help me! I have this code, which by selecting a combobox populates a series of textboxes. Now I would like to make sure to add, in addition to the textbox, also a picturebox, but I get the error as per the title. How can I proceed? Here is the code. Thanks everyone for the help.
// STRINGA CHE PERMETTE DALLA COMBOBOX VIA DI DETERMINARE IL REFERENTE
private void cboVia_SelectedIndexChanged(object sender, EventArgs e)
{
string str = constring;
SqlConnection con2 = new SqlConnection(str);
string query = "SELECT Referenti.IDReferenti, Referenti.CognomeRF, Referenti.NomeRF, Referenti.ZonaRF, Referenti.LinkRF, Referenti.CodiceFotoRF, Referenti.TelefonoRF, Referenti.EmailRF, Referenti.ImageRF, Vie.Settore, Vie.Zona, Vie.Via FROM Referenti FULL OUTER JOIN Vie ON Referenti.ZonaRF = Vie.Zona where Via = '" + cboVia.Text + "'";
SqlCommand cmd = new SqlCommand(query, con2);
SqlDataReader dbr;
try
{
con2.Open();
dbr = cmd.ExecuteReader();
while (dbr.Read())
{
//string sID = (string)dbr["IDReferenti"].ToString();
string CognomeReferente = (string)dbr["CognomeRF"]; // name is string value
string NomeReferente = (string)dbr["NomeRF"];
string ZonaReferente = (string)dbr["ZonaRF"];
string EmailReferente = (string)dbr["EmailRF"];
string CodiceFotoReferente = (string)dbr["CodiceFotoRF"];
string imageRF = (string)dbr["ImageRF"];
//txtID.Text = sID;
txtCognomeReferente.Text = CognomeReferente;
txtnomeReferente.Text = NomeReferente;
txtEmailReferente.Text = EmailReferente;
txtZona.Text = ZonaReferente;
txtcodiceFotoReferente.Text = CodiceFotoReferente;
// PICTUREBOX
imageRFPictureBox.ImageLocation = imageRF;
//PICTUREBOX
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Errore");
}
}
// FINE STRINGA CHE PERMETTE ALLA COMBOBOX VIA DI DETERMINARE IL REFERENTE
#SeanSkelly thanks! Thanks to your advice maybe I found the solution!
byte[] imageRF = (byte[])dbr["ImageRF"];
if (imageRF == null)
{
imageRFPictureBox.Image = null;
}
else
{
MemoryStream mstream = new MemoryStream(imageRF);
imageRFPictureBox.Image = System.Drawing.Image.FromStream(mstream);
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Errore");
}
I tried to get data from SQL Server (2 tables: Famille and Compte) into 2 comboboxes in the Form_Load().
But as you see the result, it works with the 1st combobox, but the 2nd it shows System.Data.SqlClient.SqlDataReader
This is the Code
private void Tresorerie_Load(object sender, EventArgs e)
{
conn = new SqlConnection(connstring);
conn.Open();
String queryCompte = "select NomCom from Compte";
String queryFamille = "select NomFam from Famille";
commCompte = new SqlCommand(queryCompte, conn);
commFamille = new SqlCommand(queryFamille, conn);
try
{
//Compte
commCompte.CommandType = CommandType.Text;
dreaderCompte = commCompte.ExecuteReader();
while (dreaderCompte.Read())
{
queryCompte = dreaderCompte[0].ToString();
TreComBoxCompte.Items.Add(queryCompte);
}
}
catch (Exception)
{
MessageBox.Show("Problem with load Compte");
}
finally
{
dreaderCompte.Close();
}
try
{
//Famille
commFamille.CommandType = CommandType.Text;
dreaderFamille = commFamille.ExecuteReader();
while (dreaderFamille.Read())
{
queryFamille = dreaderFamille[0].ToString();
TreComBoxFamille.Items.Add(dreaderFamille);
}
}
catch (Exception)
{
MessageBox.Show("Problem with load Famille");
}
finally
{
dreaderFamille.Close();
}
conn.Close();
}
For second combobox you are adding your datareader dreaderFamille:
TreComBoxFamille.Items.Add(dreaderFamille);
while you should add queryFamille:
queryFamille = dreaderFamille[0].ToString();
TreComBoxFamille.Items.Add(queryFamille);
If you pay attention to item texts in your ComboBox you will guess the problem and when you look at code, you will see your guess is true.
for 2nd comboxbox, you are using wrong object to add
TreComBoxFamille.Items.Add(queryFamille);
You should do it like this:
while (dreaderFamille.Read())
{
queryFamille = dreaderFamille[0].ToString();
TreComBoxFamille.Items.Add(queryFamille);
}
I have a MS-Access table in my database called "RichtingEnJaar".
This table has 2 columns: the "ID" and "Naam".
I need to get the whole column "Naam" to be in an array in C#.
I tried a lot already but can't seem to find the correct answer.
Can any of you help me out real quick?
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Project Officieel\Project_MagnusCurriculum\Project_MagnusCurriculum\Project.accdb";
connect.Open();
OleDbCommand cmdKlassen = new OleDbCommand("SELECT Naam FROM RichtingEnJaar WHERE ID = 1", connect);
if (connect.State == ConnectionState.Open)
{
try
{
OleDbDataReader KlasReader = null;
KlasReader = cmdKlassen.ExecuteReader();
while (KlasReader.Read())
{
Klas[0].Naam = KlasReader["Naam"].ToString();
}
connect.Close();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("Connection failed");
}
Tried a new one:
string connStringKlas = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Project Officieel\Project_MagnusCurriculum\Project_MagnusCurriculum\Project.accdb";
DataTable resultsKlas = new DataTable();
using (OleDbConnection connKlas = new OleDbConnection(connStringKlas))
{
OleDbCommand cmdKlas = new OleDbCommand("SELECT Naam FROM RichtingEnJaar", connKlas);
connKlas.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmdKlas);
adapter.Fill(resultsKlas);
for (int i = 0; i <= resultsKlas.Rows.Count - 1; i++)
{
Klas[i].Naam = resultsKlas.Rows[i].ToString();
}
connKlas.Close();
}
MessageBox.Show(Klas[0].Naam.ToString());
Got an error on line Klas[i].Naam = resultsKlas.Rows[i].ToString(); saying 'System.NullReferenceException'.
It is not quite clear what Klas is, but supposing it is some array.
It looks like Klas[0].Naam = KlasReader["Naam"].ToString(); is problem source. You're putting all results from query into the same variable.
It should be some list or another collection you're adding your query results to, not a single Klas[0].Naam variable.
For example (skipping irrelevant parts of your code)
var list = new List<KlasStruct>();
while (KlasReader.Read())
{
var k = new KlasStruct();
k.Naam = KlasReader["Naam"].ToString()
list.Add(k);
}
And later (if you really need array, not list) you can transform list to array using List.ToArray() method.
Like this:
Klas = list.ToArray();
Since you may not know how many records there are in your database, you can use a list to fill from the database, and convert this list to an array:
var klasList = new List<KlasStruct>();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Project Officieel\Project_MagnusCurriculum\Project_MagnusCurriculum\Project.accdb";
connect.Open();
OleDbCommand cmdKlassen = new OleDbCommand("SELECT Naam FROM RichtingEnJaar WHERE ID = 1", connect);
if (connect.State == ConnectionState.Open)
{
try
{
OleDbDataReader KlasReader = null;
KlasReader = cmdKlassen.ExecuteReader();
while (KlasReader.Read())
{
klasList2.Add(new KlasStruct() { Naam = KlasReader["Naam"].ToString());
}
connect.Close();
Klas = klasList.ToArray();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("Connection failed");
}
A few months ago I made a test program for a project and everything worked fine there.
Now I am working on the program itself, so I copied the code from the test program and
changed the the names of the columns,buttons etc. so it would fit the current program.
When I try to add something into the database it does nothing on the first click, on the
second pops up an error which says that the connection is open.. I really got no idea what's
the problem. I tried to check again if I made a mistake in a column name or the database name
but everything seems to be correct.
Note: I also have a function that show data from the database and it works without any problem.
private void InsertData()
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
Connection.Open();
DataAdd.ExecuteNonQuery();
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
string NewRowNum()
{
string Row = RowFind();
int CalcRow = int.Parse(Row) + 1;
Row = CalcRow.ToString();
return Row;
}
The connection that appears to be open is the one in the string RowFind().
Here are the other related things to the database:
public partial class frmShop : Form
{
System.Data.SqlClient.SqlConnection Connection;
public frmShop()
{
string DatabaseConnection = WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1;
Connection = new System.Data.SqlClient.SqlConnection();
Connection.ConnectionString = DatabaseConnection;
InitializeComponent();
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
Connection.Open();
SqlDataReader ReadSentence = null;
Int32 BinaryInt = Int32.Parse(txtBinaryString.Text);
string CommandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
SqlCommand Command = new SqlCommand(CommandString, Connection);
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
ReadSentence = Command.ExecuteReader();
while (ReadSentence.Read())
{
txtSentence.Text = (ReadSentence["Sentence"].ToString());
Fit = 1;
}
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You are getting errors because you are reusing the same connection Connection.Open(); several times.
Your method InsertData() is doing this 3 times in the same method.
You should create a new instance of the connection object and dispose it on your methods.
Using Statement are the way to go.
private void InsertData()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
Connection.Open();
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
DataAdd.ExecuteNonQuery();
//Connection.Close(); no need to close
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You can save one more connection if you store the row returned by RowFind()
string RowFind()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
//Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
So you would connect once instead of twice:
var Row = RowFind();
string NewCode = GenerateCode(Row);
string NewRow = NewRowNum(Row);
string NewSentence = txtSentence.Text;
Declare your connection string variable to a property so you can reuse it:
private string DatabaseConnection {get; set;}
Instead using an instance level SqlConnection you should only provide a common factory for creating a connection:
public partial class frmShop : Form
{
private string ConnectionString
{
get { return WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1; }
}
public frmShop()
{
InitializeComponent();
}
private SqlConnection CreateConnection()
{
var conn = new SqlConnection(ConnectionString);
conn.Open();
return conn;
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
using (var conn = CreateConnection())
{
var BinaryInt = int.Parse(txtBinaryString.Text);
var commandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
using (var Command = new SqlCommand(commandString, conn))
{
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
using (var readSentence = Command.ExecuteReader())
{
while (readSentence.Read())
{
txtSentence.Text = (readSentence["Sentence"].ToString());
Fit = 1;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void InsertData()
{
try
{
using (var conn = CreateConnection())
{
var commandString = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
using (var comm = new SqlCommand(commandString, conn))
{
comm.Parameters.AddWithValue("#NewBinaryString", GenerateCode());
comm.Parameters.AddWithValue("#NewNewSentence", txtSentence.Text);
comm.Parameters.AddWithValue("#NewRowNumber", NewRowNum());
comm.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
using (var conn = CreateConnection())
{
var commandString = "SELECT * FROM ShopSentences";
using (var comm = new SqlCommand(commandString, conn))
{
using (var sda = new SqlDataAdapter(queryString, Connection))
{
using (DataTable dt = new DataTable("ShopSentences"))
{
sda.Fill(dt);
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
}
}
}
string NewRowNum()
{
var Row = RowFind();
var CalcRow = int.Parse(Row) + 1;
return CalcRow.ToString();
}
}
But this is just the beginning you should not have any hard SQL dependency in your Form classes.
When sharing same SqlConnection instance several times in your code, instead of directly opening the you can rather check the connection state first and then open it if not already opened. For example:
if(Connection.State!= ConnectionState.Open)
Connection.Open();
While I am running the code below, the compiler is giving me the error: "object reference not set to an instance of an object". Please can you tell what mistakes I have made in this code.
public void text()
{
cn1.Open();
string s;
//error came here
s = "select Request_Type from dbo.component where Material_Code='" +
Mcodeddl.SelectedItem.Text + "' ";
//end
SqlCommand cd1 = new SqlCommand(s, cn1);
SqlDataReader rd;
try
{
rd = cd1.ExecuteReader();
while (rd.Read())
{
TextBox4.Text = rd["Request_Type"].ToString().Trim();
}
rd.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
cd1.Dispose();
cn1.Close();
}
}
Just a hunch, but either Mcodeddl or Mcodeddl.SelectedItem is null.
There is probably no selected item in the (assuming) dropdown control.
Add a null check on the Mcodeddl.SelectedItem object before the code with the error to prevent that from happening.
var code = Mcodeddl.SelectedItem.Text; // you may need to check Mcodeddl.SelectedItem != null here, if you not set default selected item
if (string.IsNullOrEmpty(code)) return; // return if code type empty, or show message. depending on your requirement
using (SqlConnection connection = new SqlConnection(connectionString)) // using statement will dispose connection automatically
{
connection.Open();
using (SqlCommand command = new SqlCommand("select Request_Type from dbo.component where Material_Code= #MaterialCode", connection))
{
command.Parameters.AddWithValue("#MaterialCode", code); // use parameters
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var request = reader["Request_Type"];
TextBox4.Text = request != DBNull.Value ? request.ToString().Trim() :string.Empty;// check null before ToString
}
}
}
}
catch (Exception e)
{
Response.Write(e.Message);
}