GOOGLE ADS

domingo, 1 de mayo de 2022

2 mismo valor en gridview

hola, actualmente tengo un botón de búsqueda en mi formulario y quiero buscar entre 2 fechas y quiero tener un mensaje de alerta si tengo 2 mismos registros en otra columna, este es mi código por ahora

SqlConnection sqlCon = new SqlConnection(ConnectionString);
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
SqlDataAdapter sqlData = new SqlDataAdapter("DateFilter", sqlCon);
sqlData.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlData.SelectCommand.Parameters.AddWithValue("@Date", TxtFromDate.Text);
sqlData.SelectCommand.Parameters.AddWithValue("@Date2", TxtToDate.Text);
DataTable dtbl = new DataTable();
sqlData.Fill(dtbl);
sqlCon.Close();
Gridview1.DataSource = dtbl;
Gridview1.DataBind();
Gridview1.UseAccessibleHeader = true;
Gridview1.HeaderRow.TableSection = TableRowSection.TableHeader;


Solución del problema

Es realmente difícil descifrar tu pregunta. Parece que tiene un resultado de SQL existente DataGridViewy luego desea verificar a través de un botón si hay varias entradas con el mismo valor de "Fecha de creación".

(1) Debe usar objetos definidos para poder trabajar con elementos de objeto en lugar de DataTableíndices de fila/columna, lo cual es una molestia.

Por lo tanto, debe definir su objeto, mapear sus DataTablefilas como elementos de objetos en una colección (aquí: un simple List<>) y luego establecer esta colección en su DataGridView.DataSource, por ejemplo:

// define single object
public class FinishedGood {
public int ID { get; set; }
public DateTime CreatedDate { get; set; }
...
}
// define object collection
public class FinishedGoods: List<FinishedGood> { }
// execute your existing SQL query and fill the DataTable
...
// convert DataTable to FinishedGoods
FinishedGoods finishedGoods = new FinishedGoods();
foreach (DataRow row in dtbl.Rows) {
finishedGoods.Add(new FinishedGood() {
ID = Convert.ToInt32(row["ID"]),
CreatedDate = DateTime.Parse(row["CreatedDate"].ToString());,
...
});
}
// set the collection as datasource
gv.DataSource = finishedGoods;

(2) Ahora, puede verificar si hay DataSourceduplicados a través de Linq:

using System.Linq;
private HashSet<FinishedGood> CheckForDuplicateCreatedDates() {
HashSet<FinishedGood> result = new HashSet<FinishedGood>();
// collect all createdDates
HashSet<DateTime> createdDates = new HashSet<DateTime>();
foreach (FinishedGood finishedGood in gv.DataSource){
if (!createdDates.Contains(finishedGood.createdDate)) {
createdDates.Add(finishedGood.createdDate);
}
}
// loop through all createdDates
foreach (DateTime createdDate in createdDates) {
// check if there are more than 2 entries with the createdDate in your DataSource
if (gv.DataSource.Count(x => x.CreatedDate == createdDate) > 2) {
// add those entries to your duplicate result list
foreach (FinishedGood finishedGood in gv.DataSource.Where(x => x.CreatedDate == createdDate)) {
result.Add(finishedGood);
}
}
}
return result;
}

(3) Para mostrar la ventana emergente de alerta, puede usar MessageBox.Show().

(4) Para resaltar las filas correspondientes en DataGridview, puede usar el resultado de (2) para encontrar los índices de fila correspondientes y luego ajustar su DefaultCellStyle.

El clic del botón se vería así:

private void buttonCheck_Click(object sender, EventArgs e) {
// get duplicates
HashSet<FinishedGood> duplicates = CheckForDuplicateCreatedDates();
if (duplicates.Count() > 0) {
// show alert popup
MessageBox.Show("Duplicates found");
// highlight the corresponding rows
foreach (DataGridViewRow row in gv.Rows) {
if (duplicates.Contains((row.DataBoundItem as FinishedGood))) {
row.DefaultCellStyle.BackColor = Color.DarkRed;
row.DefaultCellStyle.ForeColor = Color.White;
}
}
}
}

No hay comentarios.:

Publicar un comentario

Flutter: error de rango al acceder a la respuesta JSON

Estoy accediendo a una respuesta JSON con la siguiente estructura. { "fullName": "FirstName LastName", "listings...