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();
}
}
Related
i'M in a small project that needs to Screenshot a game.
I made it Screenshot the game,and I need to make it Start and Stop the Screenshooter.
But I 've a problem now...
Code:
public string path = "";
public Form1()
{
InitializeComponent();
}
private static string _path = "C:\\temp\\not posted";
private static int _timespan = 3000;
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = true;
var path =#"FPSS";
if (path != string.Empty)
_path = path;
_timespan = 3000;
DirectoryInfo dir = new DirectoryInfo(_path);
PrintScreen ps = new PrintScreen();
if (!dir.Exists) dir.Create();
var countScreens = 0;
while (true)
{
var task=StartPrinting(ps);
task.Wait();
Thread.Sleep(_timespan);
if (countScreens == 20)
{
System.GC.Collect();
countScreens = 0;
}
countScreens++;
}
}
private static async Task StartPrinting(PrintScreen ps)
{
var name = DateTime.Now.ToString("yyyyMMddhhmmss");
ps.CaptureScreenToFile($"{_path}\\{name}.png", ImageFormat.Png);
Console.WriteLine($"Printed {name}");
}
private void button2_Click(object sender, EventArgs e)
{
button1.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
But in this way (with button1 start the infinite loop) I can't turn this off because the loop is running...
Any ideas? :)
Thanks!
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:
I try to upload into and extract stopwatch time from a SQL Server database with code shown below, but I get an error:
"System.IndexOutOfRangeException: 'currentTimeVASN".
The code works fine if I remove the code for uploading and extracting stopwatch text into database
I posted the code below.
Appreciate your help.
public partial class TestWindowMLCC : Window
{
String SNconnectionstring = (#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SNDB.mdf;Integrated Security=True;");
DispatcherTimer dtVASN = new DispatcherTimer();
Stopwatch swVASN = new Stopwatch();
string currentTimeVASN = string.Empty;
public TestWindowMLCC()
{
InitializeComponent();
}
private void mlccSNCreate_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("#SerialNumber", sNtxtbox.Text);
sqlCmdSN.Parameters.AddWithValue("#Test1", SNTest1.Text.Trim());
sqlCmdSN.Parameters.AddWithValue("#Test2", txtVASN.Text.Trim());
sqlCmdSN.ExecuteNonQuery();
MessageBox.Show("SN has been created! You may proceed to key in the data!");
}
}
private void mlccOpen_Click(object sender, RoutedEventArgs e)
{
using (SqlConnection sqlConSN = new SqlConnection(SNconnectionstring))
{
sqlConSN.Open();
String sqlSelectQuerySN = ("Select * FROM tblSN WHERE SerialNumber = #serialNumber");
SqlCommand sqlCmdSNLoad = new SqlCommand(sqlSelectQuerySN, sqlConSN);
sqlCmdSNLoad.Parameters.Add("#serialNumber", System.Data.SqlDbType.VarChar).Value = sNtxtbox.Text;
SqlDataReader drSNReader = sqlCmdSNLoad.ExecuteReader();
if (drSNReader.Read())
{
SNTest1.Text = (drSNReader["Test1"].ToString());
txtVASN.Text = (drSNReader["currentTimeVASN"].ToString());
}
else
{
SNTest1.Text = "";
txtVASN.Text = "";
MessageBox.Show("The SN you keyed in is not exist. Please click Create Button to Create.");
}
}
}
private void sNbtn_Click(object sender, RoutedEventArgs e)
{
mLCCTabControl.SelectedIndex = 1;
dtVASN.Tick += new EventHandler(dtVASN_Tick);
dtVASN.Interval = new TimeSpan(0, 0, 0, 0, 1);
}
void dtVASN_Tick(object sender, EventArgs e)
{
if (swVASN.IsRunning)
{
TimeSpan tsVASN = swVASN.Elapsed;
currentTimeVASN = String.Format("{0:00}:{1:00}:{2:00}",
tsVASN.Hours, tsVASN.Minutes, tsVASN.Seconds);
txtVASN.Text = currentTimeVASN;
}
}
private void btnTimeStartSN_Click(object sender, RoutedEventArgs e)
{
swVASN.Start();
dtVASN.Start();
}
private void btnTimeStopSN_Click(object sender, RoutedEventArgs e)
{
if (swVASN.IsRunning)
{
swVASN.Stop();
}
}
}
}
Here is the contents of the SNAdd SP:
CREATE PROC SNadd #SerialNumber VARCHAR (50)
, #Test1 VARCHAR (50)
, #currentTimeVASN VARCHAR (50)
AS
INSERT INTO tblSN(SerialNumber,Test1,currentTimeVASN) VALUES (#SerialNumber,#Test1,#currentTimeVASN)
i got a WinForm Project in C# 4.0.
i want to when the user click the button enter then it call onclick event of this button.
my code:
public XtraForm_Main()
{
InitializeComponent();
...
this.AcceptButton = (Button)this.Controls["button_Valider"];
}
private void Main_Load(object sender, EventArgs e)
{
this.AcceptButton = (Button)this.Controls["button_Valider"];
}
private void button_Valider_Click(object sender, EventArgs e)
{
try
{
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
string SqlSyntax = "SELECT * FROM ORDRE WHERE REF_EXPED = #REFERENCE";
SqlCommand comm_InsUpt = new SqlCommand(SqlSyntax, connectionWrapper.conn);
comm_InsUpt.Parameters.AddWithValue("#REFERENCE", textEdit_ref.Text);
SqlDataAdapter adapt_SelectAll = new SqlDataAdapter();
adapt_SelectAll.SelectCommand = comm_InsUpt;
DataSet dSet_SelectAll = new DataSet();
adapt_SelectAll.Fill(dSet_SelectAll, "BON_ETIKET");
var xtraReport_Pricipal = new Zebra_Web();
xtraReport_Pricipal.Parameters["Count_Ordre"].Value = 1;
xtraReport_Pricipal.Parameters["IdPacket"].Value = 1;
xtraReport_Pricipal.DataSource = dSet_SelectAll;
xtraReport_Pricipal.DataMember = dSet_SelectAll.Tables[0].TableName;
xtraReport_Pricipal.CreateDocument();
xtraReport_Pricipal.PrintingSystem.ShowMarginsWarning = false;
xtraReport_Pricipal.PrintingSystem.ContinuousPageNumbering = true;
//xtraReport_Pricipal.ShowPreviewDialog();
xtraReport_Pricipal.Print(Properties.Settings.Default.Zebra);
dSet_SelectAll.Dispose();
adapt_SelectAll.Dispose();
}
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message, excThrown);
}
}
i have tried to put this line:
this.AcceptButton = (Button)this.Controls["button_Valider"];
in constructor and onLoad From event but still not work.
when the user click the button it nothing happen. i have to clic it with the mouse.
You need to set KeyPreview Property of your Form to True.
and then write a KeyDown Event to Handle Enter Key on Form
as Below:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button_Valider_Click(sender,e);
}
}
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