Visual Stuido C# Access Violation while Using Anviz SDK - c#

I am trying to use "Anviz Original SDK"
i added simple looping to connect multiple devices.
it was running okay if i only run it for 1 times, but in the second (sometimes the third) it keep crashing and showing erorr "Access Violation" at the output box of Visual Studio.
I've read some posts here on stackoverflow which suggest that there might be a bad pointer somewhere, but i cannot find where. I think My pointers are not corrupt.
The DLL Import for the function are using this code:
[DllImport("tc-b_new_sdk.dll")]
here is the function to loop and connect to device:
private void pictureBox3_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in listViewDevice.Items)
{
if (item.Selected)
{
//int result = connectDevice(item.SubItems[3].Text, "5010");
int ret = 0;
byte[] Ipstr = new byte[16];
//string_to_byte(this.Add_dev_Ip.Text,Ipstr, (byte)Add_dev_Ip.Text.Length);
Ipstr = System.Text.Encoding.Default.GetBytes(item.SubItems[3].Text);
int Port = Convert.ToInt32("5010");
ret = AnvizNew.CCHex_ClientConnect(anviz_handle, Ipstr, Port);
}
}
}
and here is the Timer Tick function to get the data:
private void timer1_Tick(object sender, EventArgs e)
{
try
{
int ret = 0;
int[] Type = new int[1];
int[] dev_idx = new int[1];
IntPtr pBuff;
int len = 32000;
pBuff = Marshal.AllocHGlobal(len);
while (true)
{
if (anviz_handle == IntPtr.Zero)
{
break;
}
ret = AnvizNew.CChex_Update(anviz_handle, dev_idx, Type, pBuff, len);
//dbg_info("Update~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
if (ret > 0)
{
dbg_info("Msg Type : " + Type[0]);
switch (Type[0])
{
case (int)AnvizNew.MsgType.CCHEX_RET_DEV_LOGIN_TYPE:
{
AnvizNew.CCHEX_RET_DEV_LOGIN_STRU dev_info;
dev_info = (AnvizNew.CCHEX_RET_DEV_LOGIN_STRU)Marshal.PtrToStructure(pBuff, typeof(AnvizNew.CCHEX_RET_DEV_LOGIN_STRU));
string info_buff = "Dev Login --- [MachineId:" + dev_info.MachineId
+ " Version:" + byte_to_string(dev_info.Version)
+ " DevType:" + byte_to_string(dev_info.DevType)
+ " Addr:" + byte_to_string(dev_info.Addr)
+ "]";
//log_add_string(info_buff + " " + dev_info.DevTypeFlag.ToString());
log_add_string(info_buff + " " + Convert.ToString(dev_info.DevTypeFlag, 16));
ListViewItem foundItem = null;
if (foundItem == null)//just test has machineid
{
int i = 0;
for (i = 0; i < listViewDevice.Items.Count; i++)
{
foundItem = this.listViewDevice.Items[i];
if (foundItem.SubItems[1].Text.ToString() == dev_info.MachineId.ToString() && Convert.ToInt32(foundItem.Text.ToString()) != dev_info.DevIdx)
{
foundItem.Text = dev_info.DevIdx.ToString();
break;
}
else
{
}
//foundItem.Text = dev_info.DevIdx.ToString();
foundItem = null;
}
}
DevCount++;
//DevTypeFlag.Add(dev_info.DevIdx, (int)dev_info.DevTypeFlag);
}
break;
case (int)AnvizNew.MsgType.CCHEX_RET_DEV_LOGIN_CHANGE_TYPE:
{
AnvizNew.CCHEX_RET_DEV_LOGIN_STRU dev_info;
dev_info = (AnvizNew.CCHEX_RET_DEV_LOGIN_STRU)Marshal.PtrToStructure(pBuff, typeof(AnvizNew.CCHEX_RET_DEV_LOGIN_STRU));
string info_buff = "Login Change --- [MachineId:" + dev_info.MachineId
+ " Version:" + byte_to_string(dev_info.Version)
+ " DevType:" + byte_to_string(dev_info.DevType)
+ " Addr:" + byte_to_string(dev_info.Addr)
+ "]";
log_add_string(info_buff + " " + Convert.ToString(dev_info.DevTypeFlag, 16));
//log_add_string(info_buff + " " + dev_info.DevTypeFlag.ToString());
//DevTypeFlag[dev_info.DevIdx] = (int)dev_info.DevTypeFlag;
}
break;
case (int)AnvizNew.MsgType.CCHEX_RET_DEV_LOGOUT_TYPE:
{
AnvizNew.CCHEX_RET_DEV_LOGOUT_STRU dev_info;
dev_info = (AnvizNew.CCHEX_RET_DEV_LOGOUT_STRU)Marshal.PtrToStructure(pBuff, typeof(AnvizNew.CCHEX_RET_DEV_LOGOUT_STRU));
string info_buff = "Dev Logout --- [MachineId:" + dev_info.MachineId
+ " Version:" + byte_to_string(dev_info.Version)
+ " DevType:" + byte_to_string(dev_info.DevType)
+ " Live:" + dev_info.Live
+ " Addr:" + byte_to_string(dev_info.Addr)
+ "]";
log_add_string(info_buff);
DevCount--;
ListViewItem foundItem = null;
if (foundItem == null)//just test has machineid
{
int i = 0;
for (i = 0; i < listViewDevice.Items.Count; i++)
{
foundItem = this.listViewDevice.Items[i];
if (foundItem.SubItems[1].Text.ToString() == dev_info.MachineId.ToString() && Convert.ToInt32(foundItem.Text.ToString()) == dev_info.DevIdx)
{
break;
}
foundItem = null;
}
}
//ListViewItem foundItem = this.listViewDevice.FindItemWithText(dev_info.MachineId.ToString(), false, 0);
if (foundItem != null)
{
// DevTypeFlag.Remove(dev_idx[0]);
foundItem.Text = "0";
//this.listViewDevice.Items.Remove(foundItem);
}
}
break;
}
}
else if (0 == ret)
{
//MY_SLEEP(10);
//Marshal.FreeHGlobal(pBuff); // free the memory
break;
}
else if (0 > ret)
{
//buff to small
len = len * 2;
Marshal.FreeHGlobal(pBuff);
pBuff = Marshal.AllocHGlobal(len);
}
else
{
//没有找到消息类型
//Marshal.FreeHGlobal(pBuff); // free the memory
break;
}
//Marshal.FreeHGlobal(pBuff); // free the memory
}
//Marshal.FreeHGlobal(buff_fin);
Marshal.FreeHGlobal(pBuff); // free the memory
}
catch (Exception ex)
{
dbg_info("Error " + ex.Message);
}
}
Really appreciate for any helps.
Thanks.

Related

C# RichTextBox edit count character deleted

I have a RichTextBox in a C# project. Adding characters and counting the number of characters per line works.
The issue comes when I try to delete characters with the Backspace Key
I have commented out the code I have tried while pressing the Backspace Key
I also tried to use a KeyPress event to manage counting characters deleted complete fail.
If anyone would like to test the code here are the properties of the RichTextBox Name rtbInfo.
Size 347 by 120 Font 10.8 Bold WordWrap False NO Scroll Bars Max Length 135
GOAL Increase the variable res by 1 for each character or space deleted with the press of the Backspace Key.
I would prefer to not use KeyPress KeyUp or KeyDown Events if at all possible.
Happy to consider code suggestions with those Event designs.
public partial class frmRTB : Form
{
int Count = 0;
int Lines = 0;
int cT = 0;
int res = 0;
public frmRTB()
{
InitializeComponent();
//rtbInfo.KeyPress += rtbInfo_KeyPress;
/*=== This Must be here to register rtbInfo ===*/
/*=============================================*/
}
private void frmRTB_Load(Object sender, EventArgs e)
{
ActiveControl = rtbInfo;
}
/*private void rtbInfo_KeyPress(object sender, KeyPressEventArgs e)
{
if (rtbInfo.TextLength == 0)
{
tbMessage.Text = "Nothing to Delete";
return;
}
if (e.KeyChar == ((char)Keys.Back) & (char.IsControl('\b')))
{
//rtbInfo.Text = rtbInfo.Text.Remove(rtbInfo.TextLength - 1, 0);
//rtbInfo.Select(rtbInfo.TextLength - 0, 0);
//rtbInfo.ScrollToCaret();
//cT = cT - 1;
//res = - 1;// Last edit was res - cT ?
//tbCount.Text = "Back Fire";
//e.Handled = true;
}
}*/
public void rtbInfo_TextChanged(Object sender, EventArgs e)
{
Count = rtbInfo.TextLength;
Lines = rtbInfo.Lines.Length;
foreach (char chr in rtbInfo.Text)
{
if (char.IsLetterOrDigit(chr))
{
cT = cT + 1;
res = 33 - cT;
}
/*
Regex regex = new Regex(#"^[\b]+$");
//Regex regex = new Regex(#"^[\b\S\t\D\W]+$");
if (regex.IsMatch(rtbInfo.Text))
{
tbCount.Text = "Use BACKSPACE Key to Edit";
}*/
//if (chr == '\b')
//if (chr == ((char)Keys.Back))
// tried above if statments they do not fire
// This fires when any key is entered NOT just the Backspace key
/*if (char.IsControl('\b'))// & !(char.IsLetterOrDigit(chr)))
{
//rtbInfo.Text = rtbInfo.Text.Remove(rtbInfo.TextLength - 1, 0);
//rtbInfo.Select(rtbInfo.TextLength - 0, 0);
//rtbInfo.ScrollToCaret();
res = +1;
tbCount.Text = "Use BACKSPACE Key to Edit";
}*/
if (Lines == 5 | Count == 135)
{
rtbInfo.ReadOnly = true;
}
if (rtbInfo.ReadOnly == true)
{
txtBoxMsg.Text = "";
tbMessage.Text = "";
tbCount.Text = "Use BACKSPACE Key to Edit";
}
if (rtbInfo.Text.EndsWith("\n"))
{
cT = 0;
res = 0;
}
if (cT == 33)
{
SendKeys.Send("{ENTER}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
cT = 0;
res = 0;
}
if (rtbInfo.ReadOnly == true)
{
string message = "Press YES to edit Notes" + '\n' + " NO Clear Notes";
string title = "Edit Notes";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result = MessageBox.Show(message, title, buttons);
if (result == DialogResult.Yes)
{
rtbInfo.ReadOnly = false;
SendKeys.Send("{BACKSPACE}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
cT = 0;
res = 0;
}
else
{
rtbInfo.ReadOnly = false;
rtbInfo.Clear();
tbCount.Text = "All Notes Remove";
}
}
if (res == 0)
{
res = 33;
}
txtBoxMsg.Text = "Total of " + (135 - Count) + " can be entered & " + (5 - Lines) + " Lines";
tbMessage.Text = "Total of " + res + " more char can be entered on line " + Lines;
//tbCount.Text = "Count is " + Count + " cT " + cT + " res " + res;// For Testing
return;
}
I solved this using both TextChanged & KeyPress events
While that solution worked I decided to put all the code in a KeyPress event ONLY.
One HUGE mistake in my original question was in InitializeComponent
Look up and read when & how to use this method. Enjoy the Code
public partial class frmKPO : Form
{
int rtbTotLen;
int linesTot;
int lineNum;
int res1;
int count1;
int res2;
int count2;
int res3;
int count3;
int res4;
int count4;
public frmKPO()
{
InitializeComponent();
}
private void rtbInfo_KeyPress(object sender, KeyPressEventArgs e)
{
rtbTotLen = rtbInfo.TextLength;
linesTot = rtbInfo.Lines.Length;
lineNum = (5 - linesTot);
txtBoxMsg.Text = "Total of " + (135 - rtbTotLen) + " can be entered on " + (5 - lineNum) + " Lines";
if (e.KeyChar == (char)Keys.Back)
{
if (lineNum == 1)
{
--res1;
}
if (lineNum == 2)
{
--res2;
}
if (lineNum == 3)
{
--res3;
}
if (lineNum == 4)
{
--res4;
}
}
else
{
if (lineNum == 1)
{
++res1;
}
if (lineNum == 2)
{
++res2;
}
if (lineNum == 3)
{
++res3;
}
if (lineNum == 4)
{
++res4;
}
}
if (lineNum == 4)
{
count4 = 33 - res4;
tbMessage.Text = "Total of " + count4 + " more char can be entered on line " + (5 - lineNum) + "";
if (count4 == 0)
{
SendKeys.Send("{ENTER}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
}
}
else if (lineNum == 3)
{
count3 = 33 - res3;
tbMessage.Text = "Total of " + count3 + " more char can be entered on line " + (5 - lineNum) + "";
if (count3 == 0)
{
SendKeys.Send("{ENTER}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
}
}
else if (lineNum == 2)
{
count2 = 33 - res2;
tbMessage.Text = "Total of " + count2 + " more char can be entered on line " + (5 - lineNum) + "";
if (count2 == 0)
{
SendKeys.Send("{ENTER}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
}
}
else if (lineNum == 1)
{
count1 = 33 - res1;
tbMessage.Text = "Total of " + count1 + " more char can be entered on line " + (5 - lineNum) + "";
if (count1 == 0)
{
SendKeys.Send("{ENTER}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
}
}
if (linesTot == 5 | rtbTotLen == 135)
{
rtbInfo.ReadOnly = true;
}
if (rtbInfo.ReadOnly == true)
{
txtBoxMsg.Text = "";
tbMessage.Text = "";
tbCount.Text = "Use BACKSPACE Key to Edit";
}
if (rtbInfo.ReadOnly == true)
{
txtBoxMsg.Text = "";
tbMessage.Text = "";
tbCount.Text = "Use BACKSPACE Key to Edit";
string message = "Press YES to edit Notes" + '\n' + " NO Clear Notes";
string title = "Edit Notes";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result = MessageBox.Show(message, title, buttons);
if (result == DialogResult.Yes)
{
rtbInfo.ReadOnly = false;
SendKeys.Send("{BACKSPACE}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
}
else
{
rtbInfo.ReadOnly = false;
rtbInfo.Clear();
tbCount.Text = "All Notes Remove";
}
}
}
private void btnToStart_Click(object sender, EventArgs e)
{
Close();
frmStart fS = new frmStart();
fS.Show();
}
private void frmKPO_Load(object sender, EventArgs e)
{
ActiveControl = rtbInfo;
tbMessage.Text = "Total of " + 33 + " more char can be entered on line " + 1 + "";
}
}

how I stop all threads using manualResetEvent or any other suggestion to stop my all threads?

I am using 10 threads each thread get 10 records whose Status is null and then
update status to "Q". Now these records is requested to different APIs and on success response i update the status to "C" all is doing nicely. As a stopper to stop all threads i Used ManualResetEvent after when (j>30) ManualResetEven.Set() i check a condition
if (_stopper.WaitOne(0, false))
{
break;
}
to stop my while loop and update status to null for the remaining records of each thread whose status is "Q".On stopping i update status with "Q" to null on all records of 10 threads, the problem is that one of my thread's record is not updating status to null from "Q"?
Here is my Code:
public void MainProcess()
{
int totalThread = 10;
Thread[] ThreadNum = new Thread[totalThread];
DataTable dt = new DataTable();
int j = 1;
while (true)
{
if (_stopper.WaitOne(0, false))
{
lov.LogWriter("MainProcess stopper. |" + dt.Rows[0]["que_batch"].ToString());
string var = sp_Queue_upd(dt.Rows[0]["que_batch"].ToString(), "Q");
lov.LogWriter("MainProcess stopper sp_Queue_upd " + var + " stopper call, current number is " + que_BatchNumberIndex + " Batch No. :" + que_BatchNumber + ": mainthread End of While");//+ (string)argArray.GetValue(1));
break;
}
if (j > 30)
{
_stopper.Set();
lov.LogWriter("MainProcess stopper.Set");
}
if (threadCount.ThreadCount < totalThread && threadCount.ThreadCount >= 0)
{
if (ThreadNum[threadCount.ThreadCount] == null)
{
dt = sp_get_entry_spool();
if (dt.Rows.Count <= 0)
{
Thread.Sleep(1000);
continue;
}
object[] objArr = { dt, threadCount.ThreadCount.ToString(), dt.Rows[0]["que_batch"].ToString() };
ThreadNum[threadCount.ThreadCount] = new Thread(new ParameterizedThreadStart(Process));
ThreadNum[threadCount.ThreadCount].Name = dt.Rows[0]["que_batch"].ToString();
ThreadNum[threadCount.ThreadCount].IsBackground = true;
ThreadNum[threadCount.ThreadCount].SetApartmentState(ApartmentState.MTA);
ThreadNum[threadCount.ThreadCount].Start(objArr);
lov.LogWriter("thread Start: Batch No. :" + dt.Rows[0]["que_batch"].ToString() + "|Actual Batch :" + j + "|ThreadCount" + threadCount.ThreadCount.ToString());
}
else if (!ThreadNum[threadCount.ThreadCount].IsAlive)
{
dt = sp_get_entry_spool();
if (dt.Rows.Count <= 0)
{
Thread.Sleep(1000);
continue;
}
object[] objArr = new object[3] { dt, threadCount.ThreadCount.ToString(), dt.Rows[0]["que_batch"].ToString() };
ThreadNum[threadCount.ThreadCount] = new Thread(new ParameterizedThreadStart(Process));
ThreadNum[threadCount.ThreadCount].Name = dt.Rows[0]["que_batch"].ToString();
ThreadNum[threadCount.ThreadCount].IsBackground = true;
ThreadNum[threadCount.ThreadCount].SetApartmentState(ApartmentState.MTA);
ThreadNum[threadCount.ThreadCount].Start(objArr);
lov.LogWriter("thread Start: Batch No. :" + dt.Rows[0]["que_batch"].ToString() + "|Actual Batch :" + j + "|ThreadCount" + threadCount.ThreadCount.ToString());
j++;
}
threadCount.ThreadCount++;
}
else if (threadCount.ThreadCount >= totalThread)
{
threadCount.ThreadCount = 0;
}
}
if (statusQueue)
{
string var = sp_Queue_upd(que_BatchNumber, "Q");
lov.LogWriter("Back to MainProcess" + var + " stopper call, current number is " + que_BatchNumberIndex + " Batch No. :" + que_BatchNumber + ": mainthread End of While" );//+ (string)argArray.GetValue(1));
}
}
public void Process(object ob)
{
Array argArray = new object[3];
argArray = (Array)ob;
DataTable Data = (DataTable)argArray.GetValue(0);
string var = "";
try
{
Core_Incor objCore = null;
int i = 0;
for (i = 0; i < Data.Rows.Count; i++)
{
#region Loop
var = "";
try
{
#region Loop
if (_stopper.WaitOne(0, false))
{ var = sp_Queue_upd(Data.Rows[i]["que_batch"].ToString(), "Q");
lov.LogWriter("sp_Queue_upd " + var + " stopper call, current number is " + i + " Batch No. :" + Data.Rows[i]["que_batch"].ToString() + ":" + (string)argArray.GetValue(1));
break;
}
if (Data.Rows[i]["mesg_type"].ToString() == "CQ")
{ // mark status to "C" }
else if (Data.Rows[i]["mesg_type"].ToString() == "IN")
{ // mark status to "C" }
else if (Data.Rows[i]["mesg_type"].ToString() == "CH")
{ // mark status to "C" }
else if (Data.Rows[i]["mesg_type"].ToString() == "IF")
{ // mark status to "C" }
else if (Data.Rows[i]["mesg_type"].ToString() == "IB")
{ // mark status to "C" }
else if (Data.Rows[i]["mesg_type"].ToString() == "IB")
{ // mark status to "C" }
else if (Data.Rows[i]["mesg_type"].ToString() == "BA")
{ // mark status to "C" }
else if (Data.Rows[i]["mesg_type"].ToString() == "RT")
{ // mark status to "C" }
else if (Data.Rows[i]["mesg_type"].ToString() == "CA" || Data.Rows[i]["mesg_type"].ToString() == "UB")
{ // mark status to "C" }
}
catch (Exception ex)
{
InsertReponce("1", ex.Message, Data.Rows[i]["rowid"].ToString());
}
#endregion
}
}
catch (Exception ex)
{
var = "1;MainException:FE Process :" + ex.Message;
lov.LogWriter(var);
}
}

For loop wait untill other task is complete

My problem is that I have this upload queue, and when I'm putting x number amount of files in the queue it only shows me the last file because the for loop goes around too fast.
for (i = 0; i < uploadFileList.Count; i++)
{
if (percentage == 100)
{
projects_tab.IsEnabled = true;
wait_for_upload_text.Visibility = Visibility.Hidden;
ModelUploadTXT.Text = "Upload done!";
FooterProgressBar.Value = 0;
FooterProgressBar.Foreground = Brushes.LimeGreen;
cancel_upload_model_button.Visibility = Visibility.Hidden;
SelectedFileText.Text = "Choose model(s) to import!";
try
{
uploadClient.Dispose();
}
catch (Exception asd)
{
}
}
else
{
choosedProjetName = uploadFileList[i];
ShowHome();
cancel_upload_model_button.Visibility = Visibility.Visible;
ModelUploadTXT.Text = "Uploading " + choosedProjetName + FooterProgressBar.Value.ToString("f0") + " % " + (bytesIn / 1000000).ToString("f2") + "Mb /" + (totalBytes / 1000000).ToString("f2") + "Mb";
FooterProgressBar.Foreground = Brushes.Orange;
}
}
I've tried to use
Task.Delay(1)
System.Theading.Thread.Sleep(1)
to work it around, but they haven't worked. So what I basically need is to wait percentage to go 100 and then go to next index.
Try using While condition to hold the code.
for (i = 0; i < uploadFileList.Count; i++)
{
choosedProjetName = uploadFileList[i];
ShowHome();
cancel_upload_model_button.Visibility = Visibility.Visible;
ModelUploadTXT.Text = "Uploading " + choosedProjetName + FooterProgressBar.Value.ToString("f0") + " % " + (bytesIn / 1000000).ToString("f2") + "Mb /" + (totalBytes / 1000000).ToString("f2") + "Mb";
FooterProgressBar.Foreground = Brushes.Orange;
while (percentage < 100)
{
continue;
}
projects_tab.IsEnabled = true;
wait_for_upload_text.Visibility = Visibility.Hidden;
ModelUploadTXT.Text = "Upload done!";
FooterProgressBar.Value = 0;
FooterProgressBar.Foreground = Brushes.LimeGreen;
cancel_upload_model_button.Visibility = Visibility.Hidden;
SelectedFileText.Text = "Choose model(s) to import!";
try
{
uploadClient.Dispose();
}
catch (Exception asd)
{
}
}

Why is there a difference in using for or foreach with TabPage.Controls?

I have the problem, that:
TabPage tab = new TabPage();
[...]
for (int i = 0; i < tab.Controls.Count; i++)
{
Debug.WriteLine(i + " - " + tab.Controls[i].Name + " - " + tab.Controls[i].Text);
}
has obviously not the same result than:
TabPage tab = new TabPage();
[...]
int j = 0;
foreach (Control ctl in tab.Controls)
{
Debug.WriteLine(j + " - " + ctl.Name + " - " + ctl.Text);
j++;
}
The for loop has in my case as result 53 items (Count shows 53) but the foreach loop has as result only 27 items.
I cannot understand this. What could be the reason?
I could solve the problem now by my own:
The second sourcecode wasn't like posted it was like this:
TabPage tab = new TabPage();
[...]
int j = 0;
foreach (Control ctl in tab.Controls)
{
Debug.WriteLine(j + " - " + ctl.Name + " - " + ctl.Text);
tab2.Controls.Add(ctl);
j++;
}
=> So I moved accidental my Control during foreach loop, but I want only clone it and this is the answer how to do it: Clone Controls - C# (Winform)
Now I fixed it like that:
foreach (Control ctl in tab1.Controls)
{
try
{
if (ctl != null)
{
object obj_clone = CloneObject(ctl);
if (obj_clone != null && obj_clone is Control)
{
Control ctl_clone = (Control)CloneObject(ctl);
tab2.Controls.Add(ctl_clone);
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Exception: " + ex.Message + " - TargetSite:" + ex.TargetSite + " - Source: " + ex.Source + " - InnerException: " + ex.InnerException.Message.ToString());
}
}
private Object CloneObject(Object obj)
{
var typ = obj.GetType();
var obj_clone = CreateInstanceOfType(typ);
PropertyInfo[] controlProperties = typ.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo propInfo in controlProperties)
{
if (propInfo.CanWrite && propInfo.Name != "WindowTarget")
{
try
{
if (propInfo.PropertyType.IsValueType || propInfo.PropertyType.IsEnum || propInfo.PropertyType.Equals(typeof(System.String)))
{
propInfo.SetValue(obj_clone, propInfo.GetValue(obj));
}
else
{
object value = propInfo.GetValue(obj);
if (value == null)
propInfo.SetValue(obj_clone, null);
else
propInfo.SetValue(obj_clone, CloneObject(value));
}
}
catch (Exception ex)
{
Debug.WriteLine("Exception: " + ex.Message + " - TargetSite:" + ex.TargetSite + " - Source: " + ex.Source + " - InnerException: " + ex.InnerException.Message.ToString());
}
}
}
return (Object)obj_clone;
}
public object CreateInstanceOfType(Type type)
{
// First make an instance of the type.
object instance = null;
// If there is an empty constructor, call that.
if (type.GetConstructor(Type.EmptyTypes) != null)
instance = Activator.CreateInstance(type);
else
{
// Otherwise get the first available constructor and fill in some default values.
// (we are trying to set all properties anyway so it shouldn't be much of a problem).
ConstructorInfo ci = type.GetConstructors()[0];
ParameterInfo[] parameters = ci.GetParameters();
object[] ciParams = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i].DefaultValue != null)
{
ciParams[i] = parameters[i].DefaultValue;
continue;
}
Type paramType = parameters[i].ParameterType;
ciParams[i] = CreateInstanceOfType(paramType);
}
instance = ci.Invoke(ciParams);
}
return instance;
}

resetting a dropdown combobox c#

I've created a form that allows for seat booking it has two dropdown menus and a label that changes showing them what seats they have booked. the label resets when I press the reset button but the drop down menus don't, they stay on the selected seats e.g. one menu saying "A" and the other saying "4" I need these to reset to blank can anyone help?
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 courseworkTask3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
if (comboBox1.SelectedIndex <= 0)
{
button1.Enabled = false;
}
else
{
button1.Enabled = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string temp = comboBox1.Text;
int dropBox1enter;
if (int.TryParse(temp, out dropBox1enter))
{
}
int i = 0;
int seatsFound = 0;
int maxFoundSeats = 0;
int maxFoundSeatsStart = 0;
int maxFoundSeatsEnd = 0;
bool[] rowA = new bool[10];
rowA[0] = true;
rowA[1] = true;
rowA[2] = false;
rowA[3] = false;
rowA[4] = false;
rowA[5] = true;
rowA[6] = true;
rowA[7] = false;
rowA[8] = false;
rowA[9] = false;
bool[] rowB = new bool[10];
rowB[0] = true;
rowB[1] = false;
rowB[2] = false;
rowB[3] = false;
rowB[4] = false;
rowB[5] = true;
rowB[6] = true;
rowB[7] = false;
rowB[8] = false;
rowB[9] = false;
bool[] rowC = new bool[10];
rowC[0] = true;
rowC[1] = false;
rowC[2] = false;
rowC[3] = false;
rowC[4] = false;
rowC[5] = true;
rowC[6] = true;
rowC[7] = false;
rowC[8] = false;
rowC[9] = false;
bool[] rowD = new bool[10];
rowD[0] = true;
rowD[1] = false;
rowD[2] = false;
rowD[3] = false;
rowD[4] = false;
rowD[5] = true;
rowD[6] = true;
rowD[7] = false;
rowD[8] = false;
rowD[9] = false;
bool[] rowE = new bool[10];
rowE[0] = true;
rowE[1] = false;
rowE[2] = false;
rowE[3] = false;
rowE[4] = false;
rowE[5] = true;
rowE[6] = true;
rowE[7] = false;
rowE[8] = false;
rowE[9] = false;
if (comboBox2.Text == "A")
{
while (i < 10 && maxFoundSeats < dropBox1enter)
{
if (rowA[i] == false)
{
seatsFound++;
if (seatsFound > maxFoundSeats)
{
maxFoundSeats = seatsFound;
maxFoundSeatsStart = 1 + i - seatsFound;
maxFoundSeatsEnd = i;
}
}
else
{
seatsFound = 0;
}
i++;
} if (maxFoundSeats == dropBox1enter)
{
label4.Text = "Booked for " + maxFoundSeats + " seat(s) in row A starting, seat " + maxFoundSeatsStart + " to seat " + maxFoundSeatsEnd + ".";
}
else
{
label4.Text = "The seats you have selected are unavailable. #The maximum available is " + maxFoundSeats + " in row A From " + maxFoundSeatsStart + " to " + maxFoundSeatsEnd + ".";
label4.Text = label4.Text.Replace("#", System.Environment.NewLine);
}
}
else
{
if (comboBox2.Text == "B")
{
while (i < 10 && maxFoundSeats < dropBox1enter)
{
if (rowB[i] == false)
{
seatsFound++;
if (seatsFound > maxFoundSeats)
{
maxFoundSeats = seatsFound;
maxFoundSeatsStart = 1 + i - seatsFound;
maxFoundSeatsEnd = i;
}
}
else
{
seatsFound = 0;
}
i++;
}
if (maxFoundSeats == dropBox1enter)
{
label4.Text = "Booked for " + maxFoundSeats + " seat(s) in row B starting, seat " + maxFoundSeatsStart + " to seat " + maxFoundSeatsEnd + ".";
}
else
{
label4.Text = "The seats you have selected are unavailable. #The maximum available is " + maxFoundSeats + " in row B From " + maxFoundSeatsStart + " to " + maxFoundSeatsEnd + ".";
label4.Text = label4.Text.Replace("#", System.Environment.NewLine);
}
}
else
{
if (comboBox2.Text == "C")
{
while (i < 10 && maxFoundSeats < dropBox1enter)
{
if (rowC[i] == false)
{
seatsFound++;
if (seatsFound > maxFoundSeats)
{
maxFoundSeats = seatsFound;
maxFoundSeatsStart = 1 + i - seatsFound;
maxFoundSeatsEnd = i;
}
}
else
{
seatsFound = 0;
}
i++;
}
if (maxFoundSeats == dropBox1enter)
{
label4.Text = "Booked for " + maxFoundSeats + " seat(s) in row C starting, seat " + maxFoundSeatsStart + " to seat " + maxFoundSeatsEnd + ".";
}
else
{
label4.Text = "The seats you have selected are unavailable. #The maximum available is " + maxFoundSeats + " in row C From " + maxFoundSeatsStart + " to " + maxFoundSeatsEnd + ".";
label4.Text = label4.Text.Replace("#", System.Environment.NewLine);
}
}
else
{
if (comboBox2.Text == "D")
{
while (i < 10 && maxFoundSeats < dropBox1enter)
{
if (rowD[i] == false)
{
seatsFound++;
if (seatsFound > maxFoundSeats)
{
maxFoundSeats = seatsFound;
maxFoundSeatsStart = 1 + i - seatsFound;
maxFoundSeatsEnd = i;
}
}
else
{
seatsFound = 0;
}
i++;
}
if (maxFoundSeats == dropBox1enter)
{
label4.Text = "Booked for " + maxFoundSeats + " seat(s) in row D starting, seat " + maxFoundSeatsStart + " to seat " + maxFoundSeatsEnd + ".";
}
else
{
label4.Text = "The seats you have selected are unavailable. #The maximum available is " + maxFoundSeats + " in row D From " + maxFoundSeatsStart + " to " + maxFoundSeatsEnd + ".";
label4.Text = label4.Text.Replace("#", System.Environment.NewLine);
}
}
else
{
if (comboBox2.Text == "E")
{
while (i < 10 && maxFoundSeats < dropBox1enter)
{
if (rowE[i] == false)
{
seatsFound++;
if (seatsFound > maxFoundSeats)
{
maxFoundSeats = seatsFound;
maxFoundSeatsStart = 1 + i - seatsFound;
maxFoundSeatsEnd = i;
}
}
else
{
seatsFound = 0;
}
i++;
}
if (maxFoundSeats == dropBox1enter)
{
label4.Text = "Booked for " + maxFoundSeats + " seat(s) in row E starting, seat " + maxFoundSeatsStart + " to seat " + maxFoundSeatsEnd + ".";
}
else
{
label4.Text = "The seats you have selected are unavailable. #The maximum available is " + maxFoundSeats + " in row E From " + maxFoundSeatsStart + " to " + maxFoundSeatsEnd + ".";
label4.Text = label4.Text.Replace("#", System.Environment.NewLine);
}
}
} //end E
} //end D
} //end C
}
}
private void dropBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void dropBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.Text != null && comboBox2.Text != null)
{
button1.Enabled = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
label4.Text = "";
}
}
}
As #Rohit Prakash pointed out in the comments to your question, setting the SelectedIndex of a ComboBox to -1 will reset any selections to the Combobox:
(I'm assuming "button2" is your Reset button, you should really name your controls more appropriately)
private void button2_Click(object sender, EventArgs e)
{
label4.Text = "";
comboBox1.SelectedIndex = -1;
comboBox2.SelectedIndex = -1;
}

Categories