how to update image in a different form c# - c#

Beginner here, I'm trying to update the image and the image's name from a different form and it's not updating. Also it doesn't give any errors. Is there something wrong in the code?
Form 2. this is where i update
private void btnStockEdit_Click_1(object sender, EventArgs e)
{
try
{
sqlCon.Open();
string qry = "Update SMStocksTb Set SmStockImgName=#SmStockImgName,SmStockImage=#SmStockImage where SmStockId=#SmStockId";
SqlCommand cmd = new SqlCommand(qry, sqlCon);
cmd.Parameters.AddWithValue("#SmStockId", SmStockId);
cmd.Parameters.AddWithValue("#SmStockImgName", txtUPImgName.Text);
cmd.Parameters.AddWithValue("#SmStockImage", Savephoto());
cmd.ExecuteNonQuery();
sqlCon.Close();
MessageBox.Show("Update Successfully","Updated",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private byte[] Savephoto()
{
MemoryStream ms = new MemoryStream();
pbxUpdateImg.Image.Save(ms, pbxUpdateImg.Image.RawFormat);
return ms.GetBuffer();
}
**Form1 ** this is where i open form 2 after selecting a row in datagrid
private void btnStockEdit_Click(object sender, EventArgs e)
{
SMStockUpdateForm cfrmStockUpdateForm = new SMStockUpdateForm();
try
{
if (StockListDG.CurrentRow.Index != -1)
{
SmStockId = Convert.ToInt32(StockListDG.CurrentRow.Cells[0].Value.ToString());
cfrmStockUpdateForm.txtUPImgName.Text = StockListDG.CurrentRow.Cells[11].Value.ToString();
byte[] ImageArray = (byte[])StockListDG.CurrentRow.Cells[12].Value;
if (ImageArray.Length == 0)
cfrmStockUpdateForm.pbxUpdateImg.Image = DefaultImage;
else
{
ImageByteArray = ImageArray;
cfrmStockUpdateForm.pbxUpdateImg.Image = Image.FromStream(new MemoryStream(ImageArray));
}
}
}
catch (Exception ex)
{
}
cfrmStockUpdateForm.ShowDialog(this);
if (isWindowOpen == false)
{
this.ParentForm.Opacity = 100;
}
}

You should learn how to send data between two forms. From form1 you should only send the name of image and in form two should bind it according to its name you received from form1

Related

Unable update PLC tag value using Linx OPC server?

PLC :- Allen-Bradley ,
App :- Linx OPC server
Language :- C#.Net
Working with an emulator in the "Studio 5000 Compact Logics L33ER" of Allen-Bradley PLC.
Unable to update the PLC value through a Linx OPC server using "groupStateWrite/groupWrite", I can read the data from AB PLC but sending value "(write item)" is not working ().
public partial class Form1 : Form
{
#region OPC Privete Fields
private Server server;
private OpcCom.Factory fact = new OpcCom.Factory();
private Subscription groupRead;
private SubscriptionState groupState;
private Subscription groupWrite;
private bool connectStatus;
#endregion OPC Privete Fields
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
bool Connect;
Connect = ConnectOpcServer();
if (Connect == true)
{
tbxConnStatus.BackColor = System.Drawing.Color.Black;
tbxConnStatus.ForeColor = System.Drawing.Color.Lime;
tbxConnStatus.Text = "Connected :-) .....";
ReadValue();
}
else
{
tbxConnStatus.BackColor= System.Drawing.Color.Black;
tbxConnStatus.ForeColor = System.Drawing.Color.Red;
tbxConnStatus.Text = "Not Connected :-/ ";
}
}
public bool ConnectOpcServer()
{
try
{
//CONNECT PLC SERVER
server = new Opc.Da.Server(fact, null);
server.Url = new Opc.URL("opcda://localhost/RSLinx OPC Server");
server.Connect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
return false;
}
return true;
}
public void ReadValue()
{
try
{
//READ GROUP SUBSCRIPTION
groupState = new Opc.Da.SubscriptionState();
groupState.Name = "New2";
groupState.UpdateRate = 1000;
groupState.Active = true;
//READ GROUP CREATION
groupRead = (Opc.Da.Subscription)server.CreateSubscription(groupState);
Opc.Da.Item[] items = new Opc.Da.Item[1];
//REPORT_DTS - TRIGGER
items[0] = new Opc.Da.Item();
items[0].ItemName = "[MYPLC]RT_BOOL";
items = groupRead.AddItems(items);
Opc.Da.ItemValueResult[] values = groupRead.Read(items);
//ADD TRIGGER VALUES
if (!String.IsNullOrEmpty(values[0].Value.ToString()))
{
tbxReadValue.Text = values[0].Value.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnWrite_Click(object sender, EventArgs e)
{
try
{
//WRITE ITEM
SubscriptionState groupStateWrite = new Opc.Da.SubscriptionState();
groupStateWrite = new Opc.Da.SubscriptionState();
groupStateWrite.Name = "GroupWrite";
groupStateWrite.Active = true;
groupWrite = (Opc.Da.Subscription)server.CreateSubscription(groupStateWrite);
//CREATE THE ITEM TO WRITE
Opc.Da.Item[] itemtoadd = new Opc.Da.Item[1];
itemtoadd[0] = new Opc.Da.Item();
itemtoadd[0].ItemName = "[MYPLC]RT_BOOL";
//CREATE THE ITEM THAT CONTAINS THE VALUE TO WRITE
Opc.Da.ItemValue[] writevalues = new Opc.Da.ItemValue[1];
writevalues[0] = new Opc.Da.ItemValue(itemtoadd[0]); -->I need to send or update the value from 1 to 0
groupWrite.AddItems(itemtoadd);
writevalues[0].Value = Convert.ToInt32(tbxWriteValue.Text.ToString());
groupWrite.Write(writevalues);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}

Retrieving a hidden column image in datagridview error

I am new in C# Windows Forms and MS SQL Server. So any help is much appreciated. I am trying to retrieve a hidden image in my datagridview however when I run the code and select a specific cell in the datagridview and display all the data including the image, I got an error that says,
'Unable to cast object of type 'system.string' to type 'system.byte '.
Here is my code,
if (dataGVInventory.SelectedRows.Count != 0)
{
Byte[] dataImg = new byte[0];
dataImg = (Byte[])dataGVInventory.SelectedRows[0].Cells[1].Value;
MemoryStream memoryStream = new MemoryStream(dataImg);
pbInvImg.Image = Image.FromStream(memoryStream);
txtProdName.Text = dataGVInventory.SelectedRows[0].Cells[2].Value.ToString();
txtProdDesc.Text = dataGVInventory.SelectedRows[0].Cells[3].Value.ToString();
txtQuantity.Text = dataGVInventory.SelectedRows[0].Cells[4].Value.ToString();
cmbAddCategory.Text = dataGVInventory.SelectedRows[0].Cells[5].Value.ToString();
//Set enable fields of textbox and button to true.
btnInvChooseImg.Enabled = true;
txtProdName.Enabled = true;
txtProdDesc.Enabled = true;
txtQuantity.Enabled = true;
cmbAddCategory.Enabled = true;
btnUpdate.Enabled = true;
btnDelete.Enabled = true;
}
This is how I load the data to the datagridview.
private void frmInventory_Load(object sender, EventArgs e)
{
loadInventory();
}
private void loadInventory()
{
dataGVInventory.Rows.Clear();
con.Open();
cmd = new SqlCommand(#"SELECT PRODUCTS.PID, PRODUCTS.ProductImage, PRODUCTS.ProductName, PRODUCTS.ProductDescription, PRODUCTS.Quantity, CATEGORY.CategoryName FROM PRODUCTS INNER JOIN
CATEGORY ON PRODUCTS.CID = CATEGORY.CID;", con);
try
{
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
dataReader();
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void dataReader()
{
dataGVInventory.Rows.Add(rdr[0].ToString(),
rdr[1].ToString(),
rdr[2].ToString(),
rdr[3].ToString(),
rdr[4].ToString(),
rdr[5].ToString());
}
The datatype of the image in the SQL is varbinary(MAX). Any idea what did I miss?

Best way to handle error catching

I am creating an app which does some SQL server config, which part of a bigger system
There is a config table in the database of the system as follows:
CREATE TABLE Config
(
ConfigItem NVARCHAR(255) PRIMARY KEY NOT NULL,
ConfigValue NVARCHAR(255) NOT NULL
)
INSERT INTO Config
VALUES
('LinkedServerName','MYLINKEDSERVER'),
('DatabaseName','APPLICATIONDATABASE')
My app is a Windows form with two textboxes and a button. The form also has an initially blank label which is used to display error messages to the user.
In the first text box, the value for the linked server name is shown, in the second, the value for the database is shown. Both are shown on form load.
On clicking the submit button, the two values are updated in the database based on what is in the text boxes.
I have the following code to populate the two textboxes with current values at form load:
private void Form1_Load(object sender, EventArgs e)
{
// populate the textboxes
txtLinkedServer.Text = GetConfigValue("LinkedServerName");
txtDatabase.Text = GetConfigValue("DatabaseName");
}
private string GetConfigValue(string ConfigItem)
{
// get the value for the given config item from the database
using (SqlConnection conn = new SqlConnection(connectionString))
{
DataTable dt = new DataTable();
SqlCommand com = new SqlCommand();
com.CommandText = "SELECT ConfigValue FROM Config WHERE ConfigItem = #ConfigItem";
com.Parameters.AddWithValue("ConfigItem", ConfigItem);
com.Connection = conn;
try
{
conn.Open();
dt.Load(com.ExecuteReader());
if (dt.Rows.Count == 0)
{
return "Error retrieving " + ConfigItem + " name from config table";
}
else
{
return dt.Rows[0]["ConfigValue"].ToString();
}
}
catch
{
return "Error in GetConfigValueMethod when retrieving " + ConfigItem;
}
finally
{
conn.Close();
}
}
}
If there is a problem with retrieving the config data (caught by the catch block in GetConfigValue) I want the label to show the string returned from GetConfigValue.
What is the best / neatest way to do this? I was thinking
private void Form1_Load(object sender, EventArgs e)
{
string message;
// populate the textboxes
try
{
message = GetConfigValue("LinkedServerName");
txtLinkedServer.Text = message
}
catch
{
lblFeedback.Text = message;
}
// do the same for the database here
}
however, I cannot do that as I get
Use of unassigned local variable 'Message'
Or am i best to change the GetConfigValue method so that it throws it's own exception in the catch block rather than returning a string and catching that in the Load method as follows;
private string GetConfigValue(string ConfigItem)
{
// get the value for the given config item from the database
using (SqlConnection conn = new SqlConnection(connectionString))
{
// same code here
try
{
// same code here
}
catch
{
Throw new Exception ("Error in GetConfigValueMethod when retrieving " + ConfigItem);
}
finally
{
conn.Close();
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
// populate the textboxes
try
{
txtLinkedServer.Text = GetConfigValue("LinkedServerName");
}
catch (Exception e)
{
lblFeedback.Text = e.Message;
}
// do the same for the database here
}
Or some other way completely?
Looking at your second example, if that's the result you want, then it looks like you just need to replace
catch
{
lblFeedback.Text = message;
}
in your first example with
catch (Exception e)
{
lblFeedback.Text = e.Message;
}
from your second example.
As error message says you tried to use unassigned variable 'message' and because of that you were getting that error.
Try this:
private void Form1_Load(object sender, EventArgs e)
{
string message = String.Empty;
// populate the textboxes
try
{
message = GetConfigValue("LinkedServerName");
txtLinkedServer.Text = message
}
catch (Exception ex)
{
if (!String.IsNullOrEmpty(message))
lblFeedback.Text = message;
else
lblFeedback.Text = ex.Message;
}
// do the same for the database here
}

Serializing Aysnchronous SQLCommand

I have the code below which works fine when the Session state is InProc. However when the Session state is Sql Server, HandleCallback never gets called. How do I change the code so HandleCallBack gets called?
private void TAdata(object sender, EventArgs e)
{
if (((Form)sender).DialogResult == DialogResult.No)
{
return;
}
if (Changed)
{
MessageBox.Show(this.ParentForm, "Save Payroll Changes First", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
SqlConnection dbconnAS = new SqlConnection(strDBconnAS);
{
try
{
AsyncCallback callback = new AsyncCallback(HandleCallback);
using (SqlCommand SQLcmd = new SqlCommand("dbo.KronosTaData", dbconnAS))
{
SQLcmd.CommandType = CommandType.StoredProcedure;
dbconnAS.Open();
Changed = true;
SQLcmd.BeginExecuteNonQuery(callback, SQLcmd);
strResult = "";
ExportProgress.Visible = true;
ExportProgress.Value = 0;
ExportProgress.Maximum = 120;
ExportTimer.Start();
}
}
catch (Exception ex)
{
Changed = false;
strResult = ex.Message;
if (dbconnAS != null)
{
dbconnAS.Close();
}
}
}
}
}
private void HandleCallback(IAsyncResult result)
{
try
{
using (SqlCommand SQLcmd = (SqlCommand)result.AsyncState)
{
int rowCount = SQLcmd.EndExecuteNonQuery(result);
strResult = "OK";
SQLcmd.Connection.Close();
}
}
catch (Exception ex)
{
strResult = ex.Message;
}
}
private void ExportTimer_Tick(object sender, EventArgs e)
{
//Timer Exists on UI thread
if (strResult == "")
{
if (cmdKronos.Enabled) cmdKronos.Enabled = false;
if (ExportProgress.Value > ExportProgress.Maximum - 10) ExportProgress.Maximum += 10;
ExportProgress.Value += 1;
}
else if (strResult == "OK")
{
Changed = false;
cmdKronos.Enabled = true;
ExportProgress.Visible = false;
ExportTimer.Stop();
MessageBox.Show(ParentForm, "Kronos data succesfully imported", "Data Import", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
Changed = false;
cmdKronos.Enabled = true;
ExportProgress.Visible = false;
ExportTimer.Stop();
MessageBox.Show(ParentForm, Text, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
You are disposing the command as soon as you've finished starting it:
using (SqlCommand SQLcmd = new SqlCommand("dbo.KronosTaData", dbconnAS))
{
//...
SQLcmd.BeginExecuteNonQuery(callback, SQLcmd);
//...
}
that will abort everything - so indeed: it will never complete. Basically; using doesn't play nicely with Begin*/End*, so don't do that. You might find it much easier to do this using async/await, by the way (via ExecuteNonQueryAsync).
You also probably want to close and dispose the connection somewhere; again, async/await would make this much easier to get right.
The solution is to declare the variable strResult as static.
See Visual Webgui Variable Scope

Ctrl F5 exception and ignored on F5

I am getting this unhandled exception error shown: See screen shot.
I am getting this error only when I run with Ctrl+ F5 and not in F5(debug mode). Not sure if this is helpful, my computer is a windows 7- 64bit and running a 32 bit build
According to this discussion: How can I get WinForms to stop silently ignoring unhandled exceptions?, adding Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException) it wll cause Windows to ignore the error.
EDIT:
frmPlant_Load Event
public partial class frmPlant : Form
{
DatabaseConnection _DbConnection = new DatabaseConnection();
string conString = ConfigurationManager.ConnectionStrings["RVESTConnString"].ConnectionString;
SQLQueries _SQlQueries = new SQLQueries();
DataSet ds;
SQLiteDataAdapter da;
static DataTable gdt;
int gSelectedPlant;
string gSelectedPlantName = "";
bool ignoreSelChg = false;
bool DataDirty = false;
public frmPlant()
{
InitializeComponent();
}
public frmPlant(int sSelectedPlant)
{
InitializeComponent();
}
private void frmPlant_Load(object sender, EventArgs e)
{
ds = FillData();
gdt = ds.Tables[0];
bindingSource1.DataSource = gdt;
dataGridView1.DataSource = bindingSource1;
gSelectedPlant = StaticClass.GlobalValue;
dataGridView1.AutoGenerateColumns = true;
dataGridView1.Columns["PlantId"].Visible = false;
dataGridView1.Columns["NSSS_Design"].Width = 70;
}
private DataSet FillData()
{
ignoreSelChg = true;
SQLiteConnection con = new SQLiteConnection(conString);
DataSet dPlant;
try
{
con.Open();
SQLiteCommand cmd = new SQLiteCommand("select * from Plant", con);
da = new SQLiteDataAdapter("select * from Plant", con);
dPlant = new DataSet();
da.Fill(dPlant, "plant");
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
return dPlant;
}
I should also add another concern: When I say continue here in the dialog, it works fine but leaves a background process running. I have to manually go and kill it in the task manager
Question: Suppose I add this line in the Program.cs, will it ignore ANY- even genuine errors which need to be fixed?
More Code:
This dialog pops up on button click on the second screen- Initial Setup screen . The first being a splash screen. Initial setup takes me to the Plant form
Here's the code for the initial setup screen
public partial class frmInitialSetUp : Form
{
public frmInitialSetUp()
{
InitializeComponent();
}
private void btnOK_Click(object sender, EventArgs e)
{
Program.fPlant = new frmPlant();
Program.fPlant.Show();
this.Hide();
}
private void frmInitialSetUp_Load(object sender, EventArgs e)
{
Program.LoadAllForms();
}
}
}
Program.cs
static public void LoadAllForms()
{
try
{
Program.fInitialSetUp = new frmInitialSetUp();
Program.fPlant = new frmPlant();
Program.frm*** = new frm***();
Program.frm*** = new frm***();
Program.frm*** = new frm***();
}
catch (Exception ex)
{
throw ex;
}
}
On button click on the
Enclosed the frmload in a try { } catch(unhandledexception ex) {} and ran it in debug mode
This time the debugger caught it. It was a small problem with datagridview columns

Categories

Resources