Invalid attempt to call MetaData when reader is closed version2 - c#

I have a template of sqlconnection, and I have use this code before there was no problem. Until i want to use it in datagridview.
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentRow != null)
{
try
{
SQLConn.sqL = "SELECT ProductID,PCode,PName FROM Products WHERE PCode='" + txtBarcode.DataGridView.CurrentCell.Value.ToString() + "'";
SQLConn.ConnDB();
SQLConn.cmd = new SqlCommand(SQLConn.sqL, SQLConn.conn);
SQLConn.dr = SQLConn.cmd.ExecuteReader();
while (SQLConn.dr.Read())
{
dataGridView1.Rows[e.RowIndex].Cells[1].Value = SQLConn.dr["ProductID"].ToString();
dataGridView1.Rows[e.RowIndex].Cells[2].Value = SQLConn.dr["PName"].ToString();
}
}
catch (Exception ex)
{
Interaction.MsgBox(ex.ToString());
}
finally
{
SQLConn.cmd.Dispose();
SQLConn.conn.Close();
}
}
}

I think multiple calls getting in this function for that event which causing the issue. Please add SQLConn.dr.Close() to close open reader in finally clause.

Related

Webcam automatically capturing (Emgu.cv) c#

I have a project where when user login wrong for 3 times in login form, the webcam will start capturing automatically. It successfully saves the image in the database but there is one error which is Object Reference not set to an instance of an object. I know that there are a lot of questions and answers to this but I still can't solve it. Another problem is, when I just debug from the webcam form, it runs perfectly without the error message but when I debug from login form, the error appears. Another thing is it doesn't show the line of the error but I am sure that it comes somewhere from here:
private void webcam_Load(object sender, EventArgs e)
{
if ((imagecapture == null))
{
try
{
imagecapture = new Emgu.CV.VideoCapture();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Application.Idle += new EventHandler(loadimage);
}
and this is the loadimage()
public void loadimage(object sender, EventArgs e)
{
try
{
Emgu.CV.Mat imageviewer = this.imagecapture.QueryFrame();
pictureBox1.Image = imageviewer.Bitmap;
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] picture = ms.ToArray();
connection.Open();
DateTime dtime = DateTime.Now;
string qry = "INSERT INTO WebcamPhoto (ImageData,DateAndTime) VALUES(#ImageData,#dt)";
//Initialize SqlCommand object for insert.
SqlCommand cmd = new SqlCommand(qry, connection);
cmd.Parameters.AddWithValue("#ImageData", picture);
cmd.Parameters.AddWithValue("#dt", dtime);
cmd.ExecuteNonQuery();
connection.Close();
imagecapture.Dispose();
//Close form and return to list or images.
this.Close();
}
catch (NullReferenceException ex)
{
MessageBox.Show(ex.Message);
}
}
I have tried to put return and the error message is gone but the image is not saved in the database even though the webcam is working.
private void webcam_Load(object sender, EventArgs e)
{
if ((imagecapture == null))
{
try
{
imagecapture = new Emgu.CV.VideoCapture();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return;
}
Application.Idle += new EventHandler(loadimage);
}
Okay after few days finaly I found the answer myself. How? I try to change the way I wrote the code line by line and test it everytime I change the code and finally I found the culprit. So the culprit is:
public void loadimage(object sender, EventArgs e)
{
//my other code.....
imagecapture.Dispose(); <<<----here
}
So I change it to
private void ReleaseData()
{
if (imagecapture !=null)
{
imagecapture.Dispose();
}
}
and now the problem is solved :)

trying to make a textbox populate a variable that changes every three seconds

I am trying to make a text box in a WPF C# application populate a text box from a variable gathered from an external database using WCF and having little luck. Currently the text box states ScoreBoardClientTest.FeedServiceAgent instead of the value of agentsavailable. I was able to make this exact same code work in a console application when using this line of code inside of OnMessageReceived
console.writeline(e.cmsdata.skill.agentsavailable.tostring());
so I assumed I could do something similar here.
any help understanding where I'm going wrong would be great.
DisplayNumber is the name of the textbox.
public void TextBlock_Loaded(object sender, EventArgs e)
{
using (var data = new FeedServiceAgent())
{
data.MessageReceived += OnMessageReceived;
data.Subscribe("92", 3);
DisplayNumber.Text = data.ToString();
}
}
public static void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
try
{
if (e == null)
return;
if (e.CmsData == null)
{
e.CmsData.Skill.AgentsAvailable.ToString();
}
// if (!String.IsNullOrEmpty(e.Message))
// Console.WriteLine(e.Message);
}
catch (Exception ex)
{
// logger.Error(" Exception " + ex);
// throw ex;
}
}
Edit
Changed:
DisplayNumber.Text =e.CmsData.Skill.AgentsAvailable.ToString();
to:
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { DisplayNumber.Text = e.CmsData.Skill.AgentsAvailable.ToString() ; }
This will handle multithreaded calls. You might have to add a using System.Threading statement for the DispatcherPriority enum
EndEdit
It is still unclear how to get from the data of Type FeedServiceAgent to a Skill.AgentsAvailable property in your Loaded event handler. We need more information on how to make that navigation. Is the assignment even necessary in the Loaded handler? I've marked the location in the code below.
I've also made what appears to be the necessary changes to the message handler method.
public void TextBlock_Loaded(object sender, EventArgs e)
{
using (var data = new FeedServiceAgent())
{
data.MessageReceived += OnMessageReceived;
data.Subscribe("92", 3);
//DisplayNumber.Text = data.ToString();
//Is this assignment even necessary?
DisplayNumber.Text = /*Still unclear what goes here because we don't know what how to get from `data` to `Skill`*/
}
}
public static void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
try
{
if (e == null)
return;
if (e.CmsData == null)
{
//e.CmsData.Skill.AgentsAvailable.ToString();
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { DisplayNumber.Text = e.CmsData.Skill.AgentsAvailable.ToString() ; }));
}
// if (!String.IsNullOrEmpty(e.Message))
// Console.WriteLine(e.Message);
}
catch (Exception ex)
{
// logger.Error(" Exception " + ex);
// throw ex;
}
}

Entity Framework - Casting the retrieved Combobox value to string

Using Entity Framework, I have a Combobox showing a list of data retrieved from a database.
using System; //I removed the other using statements here to preserve space
namespace ExTea_BackEnd
{
public partial class frmAddBreakdown : Form
{
ExTeaEntities Breakdowns;
Breakdown_Type BreakdownTypes;
public frmAddBreakdown()
{
InitializeComponent();
}
private void cmbBreakdownType_SelectedIndexChanged(object sender, EventArgs e)
{
Breakdown_Type breakdownType = (Breakdown_Type)cmbBreakdownType.SelectedItem;
string selectedBreakdownTypeId = breakdownType.BrkdwnId;
IQueryable<Breakdown_Type> breakdownTypeQuery = from t in Breakdowns.Breakdown_Types
where t.BrkdwnId == selectedBreakdownTypeId
select t;
List<Breakdown_Type> selectedBreakdownId = breakdownTypeQuery.ToList();
if (selectedBreakdownId != null && selectedBreakdownId.Count > 0)
{
BreakdownTypes = selectedBreakdownId.First();
txtBreakdownId.Text = BreakdownTypes.BrkdwnId.ToString();
}
else
{
BreakdownTypes = null;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
Breakdown newBreakdown = new Breakdown();
Breakdown_Type breakdownType = (Breakdown_Type)cmbBreakdownType.SelectedItem;
newBreakdown.BrkdwnType = breakdownType.ToString(); //this is where the error occurs
newBreakdown.MachineId = txtMachineId.Text.Trim();
newBreakdown.MachineType = txtMachineType.Text.Trim();
newBreakdown.ReportedDate = dtpDate.Value;
newBreakdown.JobStatus = "I";
Breakdowns.AddToBreakdowns(newBreakdown);
int rowsAffected = Breakdowns.SaveChanges();
if (rowsAffected > 0)
{
MessageBox.Show(rowsAffected + " records added!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("Error occured! " + ex.Message);
}
}
}
}
I'm trying to save the data in the form back to the database, an error occurs when trying to cast the value selected from the Combobox. Even when I've casted it to the right type, it does not save the selected value! But this,
I'm clueless on what I'm doing wrong here? Can anyone please tell me how to correct this?
Thank you.
newBreakdown.BrkdwnType = breakdownType.ToString();
Here you are just calling .ToString() Method of your object, so it is returning the Type Name, which you are able to view in database table record, for getting the BrkDwnType Property value you should change statement to
newBreakdown.BrkdwnType = breakdownType.BrkdwnType;
it should just be:
newBreakdown.BrkdwnType = cmbBreakdownType.SelectedItem.ToString();
no need for casting selectedItem if you just want the string value. From a design point of view, you should probably normalize your database and use an ID for breakDownType that references another table with BreakDown types.

Saving changes from a combobox in a database

I have a combobox and want to save the changes in the database.
What I want to do is if the combobox is selected and it is true it must run the code below. If it is false it must then skip the code and go further.
The code below is checking if the combobox is enabled. But when I'm compiling it's saying true when not selected
private void Log()
{
if (kaartburgerlijkestand.Enabled)
{
veranderingBurgelijkestaat();
}
}
The code below is saving the data in the database
private string veranderingBurgerlijkestaat()
{
string gebruiker = curMedewerker.Behandelnaam;
string bekeken = prodermaform.pKaart();
string tabblad = tabControl1.SelectedTab.Text;
string pat = CPatient.GeefPatientNaam(patient.Id);
string wijz = "Burgerlijkestaat: " + kaartBurgerlijkestand.Text;
CDb dcon = new CDb();
try
{
if (dcon.Open())
{
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.loggen(Gebruiker, Bekeken, Tabblad, Patientnaam, Wijziging, Datum) VALUES(#gebruiker, #bekeken, #tabblad, #pat, #wijz, #datum)", dcon.Conn);
cmd.Parameters.AddWithValue("#gebruiker", gebruiker);
cmd.Parameters.AddWithValue("#bekeken", bekeken);
cmd.Parameters.AddWithValue("#tabblad", tabblad);
cmd.Parameters.AddWithValue("#pat", pat);
cmd.Parameters.AddWithValue("#wijz", wijz);
cmd.Parameters.AddWithValue("#datum", DateTime.Now);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
dcon.Close();
}
return wijz;
}
Could someone show me a example how to do it
I Found the solution
I have made a check
private void doCheck(object sender, EventArgs e)
{
cmbox = false;
if (kaartBurgerlijkestaat.Focused)
{
veranderingBurgerlijkestand();
}
cmbox = true;
}
Then I used the SelectedValueChanged Event
private void kaartBurgerlijkestand_SelectedValueChanged(object sender, EventArgs e)
{
if (cmbox)
doCheck(sender, e);
}
And it works fine.
I want to thank you all for helping me!
Add an Event Listener, the kaartburgerlijkestand.Enabled only check your combobox is enabled to select or not.
Add this line after your InitializeComponent(); line of Form.cs file
kaartburgerlijkestand.SelectedIndexChanged += new System.EventHandler
(this.kaartburgerlijkestand_SelectedIndexChanged);
Also add a function for above code :
private void kaartburgerlijkestand_SelectedIndexChanged(object sender, EventArgs e)
{
veranderingBurgelijkestand();
}

C# child form not refreshing

I have this code that works fine when I call it from within the form, however, when I call the same from the Parent it runs through the code without results:
public void hideHelp()
{
//Check in db if panel1 is visible
SqlCeCommand checkHelp = new SqlCeCommand("Select Show_Help from Options where Opt_Id = 1", this.optionsTableAdapter.Connection);
if (this.optionsTableAdapter.Connection.State == ConnectionState.Closed)
{ this.optionsTableAdapter.Connection.Open(); }
try
{
bool showHelp = (bool)(checkHelp.ExecuteScalar());
this.panel1.Visible = showHelp;
this.Refresh();
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
On Main form I have a toggle button with the following code:
private void tglHelp_Click(object sender, EventArgs e)
{
if (tglHelp.ToggleState.ToString() == "On")
{
HRDataSet.OptionsRow updateHelp = hRDataSet.Options.FindByOpt_Id(1);
try
{
updateHelp.Show_Help = true;
this.optionsTableAdapter.Update(this.hRDataSet);
Form activeChild = this.ActiveMdiChild;
if (activeChild.Name == "frmAddEmployees")
{
frmAddEmployees chForm = new frmAddEmployees();
chForm.MdiParent = this;
chForm.hideHelp();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName);
}
tglHelp.Text = "Help Panel \nOFF";
}
Any ideas?
In this piece of code
if (activeChild.Name == "frmAddEmployees")
{
frmAddEmployees chForm = new frmAddEmployees();
chForm.MdiParent = this;
chForm.hideHelp();
}
you open another frmAddEmployees and add to the MDI, but you don't show it.
If your intent was to call the code in the current frmAddEmployees identified by the activeChild you should use something like this
if (activeChild.Name == "frmAddEmployees")
{
((frmAddEmployees)activeChild).hideHelp();
}

Categories