I tried to check some similar post about this, but I didn't find a proper solution to this, I have the following code
if(dgvOC.Rows.Count == 0)
{
dgvOC.Rows.Add(txtProd.Text, numCant.Value, txtTipo.Text, precioGuardado, precioGuardado * (int)numCant.Value);
}
for (int i = 0; i <= dgvOC.Rows.Count; i++)
{
if (txtProd.Text == dgvOC.Rows[i].Cells[0].Value.ToString())
{
MessageBox.Show("Usted ya ha agregado un producto con el mismo nombre" +
", modifique la cantidad o borre el producto para agregarlo" +
" de nuevo.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtProd.Clear();
txtTipo.Clear();
numCant.Value = 0;
return;
}
dgvOC.Rows.Add(txtProd.Text, numCant.Value, txtTipo.Text, precioGuardado, precioGuardado * (int)numCant.Value);
}
First If is at the start I don't need to compare it to nothing because there is nothing to compare it with so I just add it (My DGV has "AddingRows" property to false)
I use the for to run on all the DGV, then in the 2nd If what I would like to do is compare the textbox to each row that is in the DGV and if it matches a MessageBox will pop out saying that you've added a product with the same name, then it clears some TextBoxes and a numericupdown, then it returns and if it doesn't match the row adds
...my problem is, using this code the first insert into the DGV works fine, but at the second it displays the warning (even if I add a name that doesn't match with the product) and in the 3rd one it adds a row in blank
Thanks for the help
Try something like this
Create a method to verify content of datagridview and if there are rows in.
// Call this in your event.
If(NoRowOrNoDuplicate())
{
dgvOC.Rows.Add(txtProd.Text, numCant.Value, txtTipo.Text, precioGuardado, precioGuardado * (int)numCant.Value);
}
//The method be like
private bool NoRowOrNoDuplicate()
{
// Add condition s here
for (int i = 0; i <= dgvOC.Rows.Count; i++)
{
if (txtProd.Text == dgvOC.Rows[i].Cells[0].Value.ToString())
{
MessageBox.Show("Usted ya ha agregado un producto con el mismo nombre" +
", modifique la cantidad o borre el producto para agregarlo" +
" de nuevo.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtProd.Clear();
txtTipo.Clear();
numCant.Value = 0;
return false;
}
}
Return true;
}
Related
i have a problem, im trynin to modify the model before send it to save, adding some data to the model, but the model its not getting the change, and the modelState.IsValid propierty stay in false. Why?
public ActionResult EditarTipoArchivo(TipoArchivos tipoarchivos)
{
TipoArchivos tipoArchivos = TipoArchivoRepository.GetTipoArchivosById(tipoarchivos.TipoArchivoId);
TipoSolicitud tiposolicitud = TipoSolicitudRepository.GetTipoSolicitudById(tipoarchivos.TipoSolicitudId);
tipoarchivos.CodigoTipoSolicitud = tiposolicitud.Codigo;
tipoarchivos.TipoArchivoId = tipoArchivos.TipoArchivoId;
tipoarchivos.Codigo = tipoArchivos.Codigo;
if (ModelState.IsValid)
{
TipoArchivoRepository.GuardarTipoArchivos(tipoarchivos);
TempData["message"] = String.Format("El {0} ha sido actualizado correctamente", tipoarchivos.TipoArchivoId);
return RedirectToAction("Index");
}
else
{
TempData["message"] = string.Format("Ha sucedido un inconveniente al intentar actualizar el Tipo de Archivo");
return View(tipoarchivos);
}
}
You have to clear ModelState (ModelState.Clear()), then
validate it again
Ex:
if (TryValidateModel(modelVM))
{
...
}
What I am trying to do is take the values from a SQL Query and display it in a ListView - which I have successfully done with the code below, which has worked well. However, what I need to do is convert ceaPercentage and boxPercentage from the decimals that they are in the SQL table into a percentage that is displayed in the ListView.
try
{
connect.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
string prevItem = string.Empty;
ListViewGroup currGroup = null;
int row = 0;
while (reader.Read())
{
ListViewItem item = new ListViewItem(reader["WO"].ToString());
item.SubItems.Add(reader["StartQty"].ToString());
item.SubItems.Add(reader["Assembly"].ToString());
item.SubItems.Add(reader["Mfg Family"].ToString());
item.SubItems.Add(reader["ceaQty"].ToString());
item.SubItems.Add(reader["ceaPercentage"].ToString("#0.##%"));
item.SubItems.Add(reader["boxQty"].ToString());
item.SubItems.Add(reader["boxPercentage"].ToString());
listView1.Items.Add(item);
if (row % 2 == 0)
{
item.BackColor = Color.LightCyan;
}
row++;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Scanlan Planning Tool Failed to Load", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
I tried using the format string of "#0.00%", however I get an error saying that there is no overload for ToString(). Any ideas on what I did wrong? Or on how to do this properly?
Thank you!
I'm having some trouble in my C# program.
After adding 9 items, the programs bugs, when im trying to add the 10th item, it only shows blank spaces.
private void btnConfirmar_Click(object sender, EventArgs e)
{
int NumeroUtente;
if (string.IsNullOrEmpty(txtNomeUtente.Text) || string.IsNullOrEmpty(txtTelefoneUtente.Text) || string.IsNullOrEmpty(txtEmailUtente.Text) || string.IsNullOrEmpty(cbbPulseira.Text))
{
MessageBox.Show("Não podem existir campos vazios!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
// Utentes na Fila de Atendimento
if (ListasFilas.FilaAtendimento.Count == 0)
MessageBox.Show("Erro: Não existem utentes na fila!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
else
// Utente repetido
if (txtNumeroUtente.Enabled == true && LV_Repetido(Convert.ToInt32(txtNumeroUtente.Text)) == true)
MessageBox.Show("Erro: Utente repetido!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
else
{
// Cria novo utente
if (NovoUtente == true)
{
// Nº Utente
NumeroUtente = Atribui_Num_Utente();
// Adiciona à ListaUtentes
ListasFilas.ListaUtentes.Add(new Utente(NumeroUtente, txtNomeUtente.Text, Convert.ToInt32(txtTelefoneUtente.Text), txtEmailUtente.Text));
//switch (cbbPulseira.Text)
//{
// case "Verde": ListasFilas.FilaAtVerde.Enqueue(NumeroUtente); break;
// case "Amarela": ListasFilas.FilaAtAmarelo.Enqueue(NumeroUtente); break;
// case "Vermelha": ListasFilas.FilaAtVermelho.Enqueue(NumeroUtente); break;
// case "Roxa": ListasFilas.FilaAtRoxo.Enqueue(NumeroUtente); break;
//}
// Atribui número
//NumeroUtente = Atribui_Num_Utente();
}
// Utente existente
else
{
NumeroUtente = Convert.ToInt32(txtNumeroUtente.Text);
}
// Bug encontrado
if(lblSenha.Text == "10")
MessageBox.Show("Bug: Quando chega à senha 10 não mostra os campos na listview!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
// Adiciona à listview
int cntItems = lvUtentes.Items.Count;
lvUtentes.Items.Add(lblSenha.Text); // Senha
lvUtentes.Items[cntItems].SubItems.Add(NumeroUtente.ToString()); // Nº
lvUtentes.Items[cntItems].SubItems.Add(txtNomeUtente.Text); // Nome
lvUtentes.Items[cntItems].SubItems.Add(cbbPulseira.Text); // Fila Cor
// Adiciona à Fila Cores
switch (cbbPulseira.Text)
{
case "Verde": ListasFilas.FilaAtVerde.Enqueue(NumeroUtente); break;
case "Amarela": ListasFilas.FilaAtAmarelo.Enqueue(NumeroUtente); break;
case "Vermelha": ListasFilas.FilaAtVermelho.Enqueue(NumeroUtente); break;
case "Roxa": ListasFilas.FilaAtRoxo.Enqueue(NumeroUtente); break;
}
// Próxima senha
lblSenha.Text = (Convert.ToInt32(lblSenha.Text) + 1).ToString();
ListasFilas.FilaAtendimento.Dequeue(); // Retira o próximo utente da fila
Im not seeing where is the problem, when i try to debug, watching it code by code it works, but when add's to the listview, i just got blank spaces.
Thank you.
EDIT: After some tests i figured out that it bugs when:
lblSenha.text passes from 9 to 10.
lblSenha.text passes from 99 to 100.
When lblsenha.text starts at 10 doesnt bug until 99.
In my application I store customers of a company. The user will be able to add customer number, name, address etc. These informations are stored in an xml file. And on the first tab of tabControl the user can type in the customer number in a textbox and then it autofills the surname and forename. And if the customer number is not available it appears a message box.
Well that sounds okay. But I got an issue with Visual Studio. I got this code:
private void txtKNrNew_Leave(object sender, EventArgs e)
{
XDocument xdoc = XDocument.Load(path + "\\save.xml");
int CustNos;
if (Int32.TryParse(txtKNrNew.Text, out CustNos))
{
var xmlNodeExist = "Buchhaltung/Customers/CustNo";
var existingCustNo = xdoc.XPathSelectElements(xmlNodeExist).FirstOrDefault(x => (int)x == CustNos);
if (existingCustNo == null)
{
MessageBox.Show("Diese Kundennummer ist nicht vorhanden!", "Kundennummer nicht vorhanden", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path + "\\save.xml");
var CustNoExist = String.Format("//Customers[CustNo/text() = {0}]/", CustNos);
var SurnameNode = xmlDoc.SelectNodes(CustNoExist + "Surname");
var ForenameNode = xmlDoc.SelectNodes(CustNoExist + "Forename");
string surname = SurnameNode[0].InnerText;
string forename = ForenameNode[0].InnerText;
if (CustNoExist != null)
{
txtSurnameNew.Text = surname;
txtForenameNew.Text = forename;
}
else
{
MessageBox.Show("aaaaaaaaaaa");
}
}
}
If I type in a customer number which does not exist it appears a messagebox to say that this customer number is not defined. But then Visual Studio interrupt the application and return an error:
Object reference not set to an instance of an object
If someone could give me a hint why this happen I'd be very pleased.
Like #adrianbanks said in the comments, you need to return, exit, stop processing, etc. after you find that the customer number does not exist.
To do that you return out of the method like so:
if (existingCustNo == null)
{
MessageBox.Show("Diese Kundennummer ist nicht vorhanden!", "Kundennummer nicht vorhanden", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
I have a DataGridView in a Windows Form, it has 2 columns, the last column is going to contain the name of a packet, the point is that this name never has to be duplicated.
I tried with this code using CellValidating event
string value = Convert.ToString(dgvTiendas.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
int cellIndex = e.RowIndex;
if(cellIndex == 1)
{
foreach (DataGridViewRow rw in dgvTiendas.Rows)
{
if (cellIndex == rw.Index)
{
return;
}
else
{
string valorRow = Convert.ToString(rw.Cells["ContenedorCodigoBarras"].Value);
if (value == valorRow)
{
MessageBox.Show("The container is already used");
dgvTiendas.Rows[e.RowIndex].ErrorText = "Contenedor ya utilizado";
e.Cancel = true;
}
else
{
e.Cancel = false;
}
}
}
}
When i run the application and i write a container's name, it is validated but it seems that validate the current cell because the "Error text" appears on the RowHeader.
Please help i have some weeks with this.
You are having this problem because you are setting the error text of the row with this code.
dgvTiendas.Rows[e.RowIndex].ErrorText = "Contenedor ya utilizado";
You need to set error text of the cell
dgvTiendas[e.ColumnIndex, e.RowIndex].ErrorText = "an error occured";