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)
Related
Timer1 not start when add new User Control.I have 1 User Control (UC_Machine).And when load Form Main I using timer execute SQL query in query variable to get data from table [tbl_FF_Trigger]
I have 1 User Control (UC_Machine).And when load Form Main I using timer execute SQL query in query variable to get data from table [tbl_FF_Trigger]
-Code in UC_Machine:
private void UC_Machine_Load(object sender, EventArgs e)
{
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
string query = "SELECT CRDName, PartNumber ,DefectName FROM [tbl_FF_Trigger] where Machine = '" + Machine + "'";
db.fillDataGridView(query, dataGridView1);
dataGridView1.BackgroundColor = Color.White;
dataGridView1.RowHeadersVisible = false;
dataGridView1.Update();
dataGridView1.Refresh();
}
Code in form MAIN. Will get the information of the machines from the function Machine_Infor.GetMachine_Infors(). It will then create a UC_Machine array from that information. If the machine in the array does not already exist in the panellayout, it will be added to the panellayout.
In addition, it also checks if the machine exists in the tbl_FF_Trigger table. Otherwise it will delete the machine from the panellayout.
private void Main_Load(object sender, EventArgs e)
{
Get_Infor();
}
private void Get_Infor()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 3000; // Thời gian chạy (5000 milliseconds = 5 second)
timer.Elapsed += Timer_Elapsed;
timer.Start();
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
// Add new item to panellayout if machine have falsecall
var data = Machine_Infor.GetMachine_Infors();
var list = new UC_Machine[data.Count];
int i = 0;
itemFoods = new List<UC_Machine>();
itemFoodsFilter = new List<UC_Machine>();
HashSet<string> existingMachine = new HashSet<string>();
foreach (var item in data)
{
if (!existingMachine.Contains(item.Machine))
{
bool isExisting = false;
foreach (UC_Machine uc in myFlowLayoutPanel1.Controls)
{
if (uc.Machine == item.Machine)
{
isExisting = true;
break;
}
}
if (!isExisting)
{
list[i] = new UC_Machine();
list[i].CRDName = item.CRDName;
list[i].Model = item.Model;
list[i].Machine = item.Machine;
list[i].PartNumber = item.PartNumber;
list[i].Workcell = item.Workcell;
list[i].CRDName = item.CRDName;
list[i].Date = item.Date;
itemFoods.Add(list[i]);
itemFoodsFilter.Add(list[i]);
existingMachine.Add(item.Machine);
i++;
}
}
}
if (myFlowLayoutPanel1.InvokeRequired)
{
myFlowLayoutPanel1.Invoke((MethodInvoker)delegate
{
myFlowLayoutPanel1.Controls.AddRange(list.Where(x => x != null).ToArray());
});
}
else
{
myFlowLayoutPanel1.Controls.AddRange(list.Where(x => x != null).ToArray());
}
// Remove machine if Falsecall not found
string maincon = ConfigurationManager.ConnectionStrings["Connstring"].ConnectionString;
// Connect to the SQL Server database and execute the query to check for the existence of "vnhcmsleaoi05" in the "tbl_FF_Trigger" table.
using (SqlConnection connection = new SqlConnection(maincon))
{
connection.Open();
foreach (UC_Machine uc in myFlowLayoutPanel1.Controls)
{
string query = "SELECT COUNT(*) FROM tbl_FF_Trigger WHERE Machine = '"+ uc.Machine+"'";
using (SqlCommand command = new SqlCommand(query, connection))
{
int count = (int)command.ExecuteScalar();
if (count == 0)
{
if (myFlowLayoutPanel1.InvokeRequired)
{
myFlowLayoutPanel1.Invoke((MethodInvoker)delegate
{
myFlowLayoutPanel1.Controls.Remove(uc);
itemFoods.Remove(uc);
uc.Dispose();
});
}
else
{
myFlowLayoutPanel1.Controls.Remove(uc);
itemFoods.Remove(uc);
uc.Dispose();
}
break;
}
}
}
}
}
Code working OK when load Form. when tbl_FF_Trigger add new value myFlowLayoutPanel1 new UC_Machine
but timer1 not start. I know this because the datagirdview has no data in the newly added UC_Machine.I want when myFlowLayoutPanel1 adds 1 UC_Machine, timer1 will start
Anyone have any advise or solution for this case, please help me. Thanks a lot!
Your question is how to call timer in UC Control in Form Main. The main form is trying to GetInfo from the UC but consider that this might be "backwards" and that the UC Control should be notifying Form Main when it gets the new info instead. Here's what I mean:
Your UC has its own timer1 (we'll get timer1 started don't worry). What main form needs is to be notified when a new query is available in one of the UCs. Giving main form its own timer will interfere with an otherwise-orderly process. Consider making an event in your UC as shown and fire it whenever UC is done getting a new query.
UserControlMachine
Example: UC starts its own timer1 and fires RecordsChanged event when new query completes.
public partial class UserControlMachine : UserControl
{
public UserControlMachine()=>InitializeComponent();
public BindingList<Record> Records { get; } = new BindingList<Record>();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
timer1 = new Timer { Interval = 2500 };
timer1.Tick += onTimer1Tick;
timer1.Start();
dataGridView1.DataSource = Records;
Records.Add(new Record()); // <- Auto-generate columns
dataGridView1.Columns[nameof(Record.DefectName)].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
private System.Windows.Forms.Timer timer1;
private void onTimer1Tick(object sender, EventArgs e) => queryDB();
private void queryDB()
{
// S I M U L A T E D Q U E R Y R E S U L T
Records.Clear();
for (int i = 0; i < Rando4Test.Next(1,5); i++)
{
Records.Add(new Record
{
CRDName = $"CRD-{(char)Rando4Test.Next(65,70)}{Rando4Test.Next(100, 200)}"
});
}
// Notify the Main Form that something has changed.
RecordsChanged?.Invoke(this, EventArgs.Empty);
}
public event EventHandler RecordsChanged;
// For testing purposes
public static Random Rando4Test { get; } = new Random();
}
Main Form
All the main form has to do is listen for RecordsChanged events.
public partial class Form1 : Form
{
public Form1() => InitializeComponent();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Simulation: Add 2 machines
for (int i = 0; i < 2; i++)
{
var machine = new UserControlMachine
{
Size = new Size(myFlowLayoutPanel1.Width - SystemInformation.VerticalScrollBarWidth, 200),
BorderStyle = BorderStyle.FixedSingle,
};
myFlowLayoutPanel1.Controls.Add(machine);
// Listen for new query results
machine.RecordsChanged += onAnyUCRecordsChanged;
}
}
private void onAnyUCRecordsChanged(object sender, EventArgs e)
{
int totalDefects = 0;
foreach (var machine in myFlowLayoutPanel1.Controls.OfType<UserControlMachine>())
{
totalDefects += machine.Records.Count;
}
Text = $"Main Form - Total Defects: {totalDefects}";
}
}
WHERE Record class represents a DataGridViewRow
public class Record
{
public string PartNumber { get; set; } =
Guid.NewGuid().ToString().Substring(0, 13).ToUpper();
public string CRDName { get; set; }
public string DefectName { get; set; } = "Unknown Error";
}
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();
}
}
I am trying to convert English text to Hindi text. For that I am using Microsoft Text translator API. But some of my text is not translating.
After googling I have found below code.
public string GetHindiText(string textToTranslate)
{
Carrier.ErrorCode = 0;
string TranslatedText = string.Empty;
try
{
Translator.LanguageServiceClient objTranslate = new Translator.LanguageServiceClient();
TranslatedText = objTranslate.Translate("***************", textToTranslate, "en", "hi");
}
catch (WebException ex)
{
Carrier.ErrorCode = 1;
return ex.Message;
}
return TranslatedText;
}
And I have added below service reference
http://api.microsofttranslator.com/V1/SOAP.svc
Most of the text is not translating. I need your suggestions to move forward.
Am I doing in correct way or anything I need to change. Any help is greatly helpful to me.
Thanks in advance.
Refer to the NuGet package NequeoNetTranslator, this contains text and speech translation APIs.
Sample of text translation this uses the new Cognitive version, first get your access token, through your translation [KEY]:
Nequeo.Net.Translator.Microsoft.Cognitive.Api apiat = new Nequeo.Net.Translator.Microsoft.Cognitive.Api(new Uri("https://api.cognitive.microsoft.com/sts/v1.0/"));
apiat.Credentials = new System.Net.NetworkCredential("[KEY]", "[KEY]");
string token = apiat.GetAccessToken();
Now call the translate method , this will translate en tode:
Nequeo.Net.Translator.Microsoft.Cognitive.Api api = new Nequeo.Net.Translator.Microsoft.Cognitive.Api(new Uri("https://api.microsofttranslator.com/v2/http.svc/"));
api.Credentials = new System.Net.NetworkCredential("[KEY]", "[KEY]");
byte[] data = api.Translate("hello", "de", "en", null, token);
Translation[] tran = api.Translate(data);
string tranText = System.Text.Encoding.Default.GetString(data);
If you are using speech to text then sample code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Nequeo.Net.Translator.Microsoft.Cognitive.SpeechApi apiat = null;
private void button1_Click(object sender, EventArgs e)
{
apiat = new Nequeo.Net.Translator.Microsoft.Cognitive.SpeechApi(new Uri("wss://dev.microsofttranslator.com/speech/"));
apiat.Credentials = new System.Net.NetworkCredential("[KEY]", "[KEY]");
string token = apiat.GetAccessToken(new Uri("https://api.cognitive.microsoft.com/sts/v1.0/"));
apiat.OnRecording += Apiat_OnRecording;
apiat.OnStopRecording += Apiat_OnStopRecording;
apiat.OnTranslationReceived += Apiat_OnTranslationReceived;
Nequeo.IO.Audio.Device device_in = Nequeo.IO.Audio.Devices.GetDeviceIn(0);
apiat.AudioDevice = device_in;
apiat.WriteStream = new System.IO.MemoryStream();
apiat.Translate("hr-HR", "en-US", token);
}
private void Apiat_OnTranslationReceived(object sender, EventArgs e)
{
System.IO.MemoryStream jj = (System.IO.MemoryStream)apiat.WriteStream;
string gg = Encoding.Default.GetString(jj.ToArray());
Nequeo.Net.Translator.Microsoft.Cognitive.SpeechTranslation dffddf = apiat.GetSpeechTranslation();
}
private void Apiat_OnStopRecording(object sender, EventArgs e)
{
bool kk = true;
}
private void Apiat_OnRecording(object sender, EventArgs e)
{
bool kk = true;
}
private void button2_Click(object sender, EventArgs e)
{
apiat.StopTranslate();
}
}
I have create a win forms with a datagridview. Where i can insert update delete
articles from the database.
But i need a wpf not a win forms project. The problem is in wpf you don't have a datagridview.
Now i have try for let work it with a datagrid but there are no row options.
i have already found how i can load the data from the wcf in my datagrid with this DgArtikel.ItemsSource = ds.Tables[0].DefaultView;
but how can i let work the insert update and delete button ?
public partial class Form1 : Form
{
ServiceReference1.Service1Client objService = new ServiceReference1.Service1Client(); // Add service reference
public Form1()
{
InitializeComponent();
showdata();
}
private void showdata() // To show the data in the DataGridView
{
DataSet ds,ds2 = new DataSet();
ds = objService.SelectUserDetails();
ds2 = objService.SelectCombobox();
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
ComboBoxCategorie.DataSource = ds2.Tables[0];
ComboBoxCategorie.DisplayMember = "Categorie";
}
private void btnClear_Click(object sender, EventArgs e)
{
int i = dataGridView1.SelectedCells[0].RowIndex;
textBoxArtikel.Text = dataGridView1.Rows[i].Cells[1].Value.ToString();
textBoxOmschrijving.Text = dataGridView1.Rows[i].Cells[2].Value.ToString();
textBoxVerkoopprijs.Text = dataGridView1.Rows[i].Cells[3].Value.ToString();
textBoxInStock.Text = dataGridView1.Rows[i].Cells[4].Value.ToString();
ComboBoxCategorie.SelectedValue = dataGridView1.Rows[i].Cells[5].Value.ToString();
}
private void btnSave_Click(object sender, EventArgs e)
{
ServiceReference1.UserDetails objuserdetail = new ServiceReference1.UserDetails(); // Add type reference
// objuserdetail.UserID = count;
objuserdetail.Artikel = textBoxArtikel.Text;
objuserdetail.Omschrijving = textBoxOmschrijving.Text;
objuserdetail.Verkoopprijs = Convert.ToInt32(textBoxVerkoopprijs.Text);
objuserdetail.Instock = Convert.ToInt32(textBoxInStock.Text);
objuserdetail.Cat_id = ComboBoxCategorie.SelectedIndex;
objService.InsertUserDetails(objuserdetail); // To insert the data
showdata();
}
private void btnDelete_Click(object sender, EventArgs e)
{
ServiceReference1.UserDetails objuserdetail = new ServiceReference1.UserDetails();
if (dataGridView1.Rows.Count > 1)
{
DataTable dt = new DataTable();
// objuserdetail.UserID = (int)dataGridView1.CurrentRow.Cells[0].Value;
objService.DeleteUserDetails(objuserdetail); // To Delete the data
showdata();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
ServiceReference1.UserDetails objuserdetail = new ServiceReference1.UserDetails();
objuserdetail.Artikel_id = (int)dataGridView1.CurrentRow.Cells[0].Value;
objuserdetail.Artikel = textBoxArtikel.Text;
objuserdetail.Omschrijving = textBoxOmschrijving.Text;
objuserdetail.Verkoopprijs = Convert.ToInt32(textBoxVerkoopprijs.Text);
objuserdetail.Instock = Convert.ToInt32(textBoxInStock.Text);
objService.UpdateRegistrationTable(objuserdetail); // To Update the Data
showdata();
textBoxArtikel.Text = "";
textBoxOmschrijving.Text = "";
textBoxVerkoopprijs.Text = "";
textBoxInStock.Text = "";
}
}
}
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