Flashing textbox - c#

For some reason, if I am changing the textbox's AutoCompleteCustomSource property, it disappears for a second and then shows up. I've tried to do it in another thread, but it doesn't seem to help, any ideas?
Code without external thread:
private void nickName_TextChanged(object sender, EventArgs e)
{
//Thread updateAC = new Thread(updateAutoComplete);
//updateAC.Start();
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
collection.AddRange(db.getUsersByLetters(nickName.Text).ToArray());
nickName.AutoCompleteCustomSource = collection;
((mainForm)Parent).currentNick = nickName.Text;
error.Visible = false;
}
Code with external thread:
private void nickName_TextChanged(object sender, EventArgs e)
{
Thread updateAC = new Thread(updateAutoComplete);
updateAC.Start();
((mainForm)Parent).currentNick = nickName.Text;
error.Visible = false;
}
public delegate void InvokeDelegate();
private void updateAutoComplete()
{
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
collection.AddRange(db.getUsersByLetters(nickName.Text).ToArray());
nickName.Invoke(new InvokeDelegate(() => { nickName.AutoCompleteCustomSource = collection;}));
}
Result:

Related

C# subscribe to event from another Task.Factory

could please help with that. I can not subscribe for event fired by an object from another Task.
Note: If i took the code outside the Task, it works fine. you can see the commented code
private void Form1_Load(object sender, EventArgs e)
{
_machines.Add(new Machine() { Ip = "192.168.1.10", Name = "Machine_01", Status = "Connected" });
dgvMachines.DataSource = _machines;
}
private void startLiveMonitoringToolStripMenuItem_Click(object sender, EventArgs e)
{
//if (_machines.Count <= 0) return;
//_fpMachine = new ZktFingerPrint(_machines[0].Ip, _machines[0].Name);
//_fpMachine.Connect();
//_fpMachine.EnableLiveFingerPrintDetection();
//_fpMachine.NewFingerPrintDetected += FpMachine_NewFingerPrintDetected;
foreach (var machine in _machines)
{
Task.Factory.StartNew(() =>
{
IFingerPrintMachine fpMachine = new ZktFingerPrint(machine.Ip, machine.Name);
fpMachine.Connect();
fpMachine.EnableLiveFingerPrintDetection();
fpMachine.NewFingerPrintDetected += FpMachine_NewFingerPrintDetected;
});
}
}
private void FpMachine_NewFingerPrintDetected(object sender, FingerPrintEventArgs e)
{
var fpr = new FingerPrintRecord(e.FingerPrintDateTime, e.UserId);
dgvMonitor.Rows.Add("Machine_01", fpr.FingerPrintDateTime, fpr.UserSn);
}

C#_Timer/Stopwatch unable to continue from time extracted from database

I have below code to start and stop timer/stopwatch and load value into database.
The stopwatch works fine, and time is able to load into database and extract from database into textbox.
the problem is after i extract the time from database and insert into text box, then i start timer, it didnt start from current time. It always start from 0.
there is no error when running the program.
Could anyone help for troubleshoot please? Thanks in advance!
public partial class TestWindow : Window
{
String SNconnectionstring = (#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SNDB.mdf;Integrated Security=True;");
DispatcherTimer dtSN = new DispatcherTimer();
Stopwatch swSN = new Stopwatch();
string currentTimeSN = string.Empty;
public TestWindow()
{
InitializeComponent();
}
private void SNCreate_Click(object sender, RoutedEventArgs e)
{
using (SqlConnection sqlConSN = new SqlConnection(SNconnectionstring))
{
sqlConSN.Open();
SqlCommand sqlCmdSN = new SqlCommand("SNadd", sqlConSN);
sqlCmdSN.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmdSN.Parameters.AddWithValue("#SN", sNtxtbox.Text);
sqlCmdSN.Parameters.AddWithValue("#Time", SNTime.Text.Trim());
sqlCmdSN.ExecuteNonQuery();
}
private void Open_Click(object sender, RoutedEventArgs e)
{
using (SqlConnection sqlConSN = new
SqlConnection(SNconnectionstring))
{
sqlConSN.Open();
String sqlSelectQuerySN = ("Select * FROM tblSN WHERE SN = #SN");
SqlCommand sqlCmdSNLoad = new SqlCommand(sqlSelectQuerySN, sqlConSN);
sqlCmdSNLoad.Parameters.Add("#SN", System.Data.SqlDbType.VarChar).Value = sNtxtbox.Text;
SqlDataReader drSNReader = sqlCmdSNLoad.ExecuteReader();
if (drSNReader.Read())
{
SNTime.Text = (drSNReader["Time"].ToString());
}
else
{
SNTime.Text = "";
}
}
private void sNbtn_Click(object sender, RoutedEventArgs e)
{
TabControl.SelectedIndex = 1;
dtSN.Tick += new EventHandler(dtSN_Tick);
dtSN.Interval = new TimeSpan(0, 0, 0, 0, 1);
}
void dtSN_Tick(object sender, EventArgs e)
{
if (swSN.IsRunning)
{
TimeSpan tsSN = swVASN.Elapsed;
currentTimeSN = string.Format("{0:00}:{1:00}:{2:00}", tsSN.Hours, tsSN.Minutes, tsSN.Seconds);
txtSN.Text = currentTimeSN;
}
}
private void btnTimeStartSN_Click(object sender, RoutedEventArgs e)
{
swSN.Start();
dtSN.Start();
}
private void btnTimeStopSN_Click(object sender, RoutedEventArgs e)
{
if (swSN.IsRunning)
{
swSN.Stop();
}
}

How to wait two BackgrandWorker's RunWorkerCompleted event finished?

That's the code:
private void button1_Click(object sender, EventArgs e)
{
ParaClass pcs = new ParaClass();
pcs.strPath = textBox1.Text;
pcs.sendedGrid = ugSrc;
this.backgroundWorker1.RunWorkerAsync(pcs);
ParaClass pcsB = new ParaClass();
pcsB.strPath = textBox2.Text;
pcsB.sendedGrid = ultraGrid2;
this.backgroundWorker2.RunWorkerAsync(pcsB);
doSomething();
}
and in both backgrandworker1 & backgrandworker2 ' complet event ,i write code like this:
private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
doSomethingelsebk1();
}
private void backgroundWorker2_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
doSomethingelsebk2();
}
now the problem is : the function doSomething() in button1's click event must wait both backgrandworker's complete event finish.
if i change doSomething() to
private void backgroundWorker2_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
doSomethingelsebk2();
doSomething();
}
then,because there are two thread,i don't know which thread will finish first,so what is the solution
Create 2 flags which represent complete state of 2 BackgroundWorker.
Turn each flag on in the RunWorkerCompleted event, then call doSomething() method.
In doSomething method, check if both flags is on, then continue to do, otherwise, return.
Create 2 AutoResetEvents, set them when each Background worker finishes and wait for them all in the main method with a WaitHandle.
WaitHandle[] handles = new WaitHandle[] { new AutoResetEvent(false), new AutoResetEvent(false)};
private void button1_Click(object sender, EventArgs e)
{
ParaClass pcs = new ParaClass();
pcs.strPath = textBox1.Text;
pcs.sendedGrid = ugSrc;
this.backgroundWorker1.RunWorkerAsync(pcs);
ParaClass pcsB = new ParaClass();
pcsB.strPath = textBox2.Text;
pcsB.sendedGrid = ultraGrid2;
this.backgroundWorker2.RunWorkerAsync(pcsB);
WaitHandle.WaitAll(this.handles);
doSomething();
}
private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
doSomethingelsebk1();
((AutoResetEvent)this.handles[0]).Set();
}
private void backgroundWorker2_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
doSomethingelsebk2();
((AutoResetEvent)this.handles[1]).Set();
}

DevExpress DataBinding, Add new Record

I am using DevExpress in my winform application, I have a gridview, data entry form, datanavigator, all bound to dataset.
I want to add new record, if using datanavigator "Add" it works good, how to do the same using a "New Record" button?
BindingSource.AddNew()
is not working, it usually does, but with devexpress its not working.
If you want to use binding then use your objects with binding source..
and use the binding list .AddingNew += new AddingNewEventHandler(listOfParts_AddingNew);
event to add new entity object ..
See the example of BindingList on MSDN.
void listOfParts_AddingNew(object sender, AddingNewEventArgs e)
{
e.NewObject = new Part(textBox1.Text, int.Parse(textBox2.Text));
}
DevExpress WinForm Controls works so fast with binding sources as compare to typed datasources etc... YOu can implement bindingSources using these example..
set gridview and the associcated controls datasource to bindsouce that you have created...
process your form with the this MSDN example..
have a look on this code snippet.. may be you will get some idea from this..
private void BindingLIstDemo_Load(object sender, EventArgs e)
{
InitializeListOfEmployees();
BindlstEmp();
listofEmp.AddingNew += new AddingNewEventHandler(listOfEmp_AddingNew);
listofEmp.ListChanged += new ListChangedEventHandler(listofEmp_ListChanged);
}
private void BindlstEmp()
{
lstEmpList.Items.Clear();
lstEmpList.DataSource = listofEmp;
lstEmpList.DisplayMember = "Name";
}
void listofEmp_ListChanged(object sender, ListChangedEventArgs e)
{
MessageBox.Show(e.ListChangedType.ToString());
//throw new NotImplementedException();
}
//declare list of employees
BindingList<Emp> listofEmp;
private void InitializeListOfEmployees()
{
//throw new NotImplementedException();
// Create the new BindingList of Employees.
listofEmp = new BindingList<Emp>();
// Allow new Employee to be added, but not removed once committed.
listofEmp.AllowNew = true;
listofEmp.AllowRemove = true;
// Raise ListChanged events when new Employees are added.
listofEmp.RaiseListChangedEvents = true;
// Do not allow Employee to be edited.
listofEmp.AllowEdit = false;
listofEmp.Add(new Emp(1, "Niranjan", 10000));
listofEmp .Add (new Emp (2,"Jai", 8000));
}
// Create a new Employee from the text in the two text boxes.
void listOfEmp_AddingNew(object sender, AddingNewEventArgs e)
{
e.NewObject = new Emp (Convert.ToInt32(txtId.Text), txtName.Text,Convert.ToInt32(txtSalary.Text));
}
private void btnAdd_Click(object sender, EventArgs e)
{
Emp empItem = listofEmp.AddNew();
txtId.Text = txtName.Text = txtSalary.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
Form1 obj = new Form1();
obj.Show();
}
private void btnDelete_Click(object sender, EventArgs e)
{
var sg = (from sc in listofEmp.ToList<Emp>() where sc.Name == ((Emp)lstEmpList.SelectedValue).Name select sc);
}
private void lstEmpList_SelectedIndexChanged(object sender, EventArgs e)
{
Emp se = listofEmp[lstEmpList.SelectedIndex];
txtId.Text = se.Id.ToString();
txtName.Text = se.Name;
txtSalary.Text = se.Salary.ToString();
}
Here I am using BindingList as datasouce BindingList<Emp> listofEmp; and on the place of grid listing of records are shown in a listbox control.. but all same...try this with your gridview..

objects in datagridview

Im adding objects to a datagridview ( only one kind) through a list
ej.
List<Material> mater = new List<Material>();
DataGridView dgvMAterial = new DataGridView();
dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
dgvMaterial.DataSource = mater;
But every time I click over the datagrid I get an indexoutofrangeexeption.
Can somone tell me why?
thanks
here is my whole code for the form
public partial class inicio : Form
{
private string ConnectionString = "Data Source=localhost\\sqlexpress;Initial Catalog=data.mdf;Integrated Security=SSPI;";
//private string ConnectionString = "Server=.\\SQLExpress;AttachDbFilename=|DataDirectory|\\data\\data_data.mdf.mdf; Database=data.mdf;Trusted_Connection=Yes;";
private ISessionFactory sessionFactory;
List<Material> mater = new List<Material>();
List<Salarios> salar = new List<Salarios>();
IBindingList mind = new BindingList<Salarios>();
Productos prod;
public inicio()
{
InitializeComponent();
sessionFactory = nhn.BusinessObjects.Initialize.CreateSessionFactory(ConnectionString);
dgvMaterial.DataSource = mater;
}
private void materialToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmMaterial material = new costeos.Catalogos.frmMaterial(ConnectionString);
material.ShowDialog(this);
material.Dispose();
}
private void salariosToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmSalarios salarios = new costeos.Catalogos.frmSalarios(ConnectionString);
salarios.ShowDialog(this);
salarios.Dispose();
}
private void agregarToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmAddRemuneraciones rem = new costeos.Catalogos.frmAddRemuneraciones(ConnectionString);
rem.ShowDialog(this);
rem.Dispose();
}
private void agregarToolStripMenuItem1_Click(object sender, EventArgs e)
{
Catalogos.frmAddAdmin adm = new costeos.Catalogos.frmAddAdmin(ConnectionString);
adm.ShowDialog(this);
adm.Dispose();
}
private void agregarToolStripMenuItem2_Click(object sender, EventArgs e)
{
Catalogos.frmAddInsumosInd insumos = new costeos.Catalogos.frmAddInsumosInd(ConnectionString);
insumos.ShowDialog(this);
insumos.Dispose();
}
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) || char.IsPunctuation(e.KeyChar) || char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
private void inicio_Load(object sender, EventArgs e)
{
LlenaCampos();
}
private void LlenaCampos()
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var mat = session.CreateCriteria(typeof(Material))
.List<Material>();
var sal = session.CreateCriteria(typeof(Salarios))
.List<Salarios>();
transaction.Commit();
cmbMaterial.DataSource = mat;
cmbMaterial.DisplayMember = "Nombre";
cmbSalarios.DataSource = sal;
cmbSalarios.DisplayMember = "Nombre";
cmbMIndirecta.DataSource = sal;
cmbMIndirecta.DisplayMember = "Nombre";
}
}
}
private void btnAddMaterial_Click(object sender, EventArgs e)
{
materialBindingSource.DataSource = null;
//dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
//dgvMaterial.DataSource = mater;
dgvMaterial.DataSource = materialBindingSource;
materialBindingSource.DataSource = mater;
materialBindingSource.ResetBindings(false);
}
private void button2_Click(object sender, EventArgs e)
{
dgvSalarios.DataSource = null;
salar.Add((Salarios)cmbSalarios.SelectedValue);
dgvSalarios.DataSource = salar;
}
private void button3_Click(object sender, EventArgs e)
{
dgvMIndirecta.DataSource = null;
mind.Add((Salarios)cmbMIndirecta.SelectedValue);
dgvMIndirecta.DataSource = mind;
}
private void button1_Click(object sender, EventArgs e)
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
if (prod == null)
{
prod = new Productos { CargasTurno = float.Parse(txtCargasTurno.Text), CavidadesMolde = int.Parse(txtCavidadesMolde.Text), Clave = txtClave.Text, Comentarios = txtComentarios.Text, MezclasTurno = float.Parse(txtMezclasTurno.Text), Moldes = int.Parse(txtMoldes.Text), Nombre = txtNombre.Text, Peso = float.Parse(txtPesoTotal.Text), TotalPza = int.Parse(txtPzasTotales.Text), Turnos = int.Parse(txtTurnos.Text) };
session.Save(prod);
transaction.Commit();
}
foreach (DataGridViewRow dr in dgvMaterial.Rows)
{
Material m = dr.DataBoundItem as Material;
m.Materiales
PMaterial mat = new PMaterial { Material = dr.DataBoundItem as Material, Cantidad = float.Parse(dr.Cells["Cantidad"].Value.ToString()), Fecha = DateTime.Now, Producto = prod };
session.Save(mat);
}
transaction.Commit();
session.Close();
}
}
}
}
}
That's probably not DGV problem, but with this combo box. Show us the code that fills combo box and sets its properties.
If you are casting to Material class you should probably use SelectedItem instead of SelectedValue. (unless you exactly know what you're doing)
I would guess that you have an event-handler that isn't happy. What exactly does the message say?
You might also be having problems if you are adding the same Material instance to the list multiple times; since IndexOf will only find the first occurrence. This line makes me very suspicious:
mater.Add((Material)cmbMaterial.SelectedValue);
since it could potentially (on consecutive clicks / etc) do exactly this.
Note: if you used BindingList<T> instead all you'd have to doo is Add(...) - no resetting required:
field:
BindingList<Material> mater = new BindingList<Material>();
init grid:
dgvMaterial.DataSource = mater;
add item:
mater.Add(newInstance);
If you assign data source to the DGV you should check element count - if zero then assign null. I don't know why this is the way it is, but I'm doing it in all my forms.
//I'm still analysing the rest of the code

Categories

Resources