J’ai créé une table de données. Il a 3 colonnes Product_id , Product_name et Product_price
Datatable table= new DataTable("Product"); table.Columns.Add("Product_id", typeof(int)); table.Columns.Add("Product_name", typeof(ssortingng)); table.Columns.Add("Product_price", typeof(ssortingng)); table.Rows.Add(1, "abc", "100"); table.Rows.Add(2, "xyz", "200");
Maintenant, je veux rechercher par index et mettre à jour cette ligne.
dire par exemple
Je veux changer la valeur de la colonne Product_name en “cde” qui a la valeur de la colonne Product_id : 2.
Vous devez d’abord trouver une ligne avec id == 2, puis changer le nom pour:
foreach(DataRow dr in table.Rows) // search whole table { if(dr["Product_id"] == 2) // if id==2 { dr["Product_name"] = "cde"; //change the name //break; break or not depending on you } }
Vous pouvez également essayer ces solutions:
table.Rows[1]["Product_name"] = "cde" // not recommended as it selects 2nd row as I know that it has id 2
Ou:
DataRow dr = table.Select("Product_id=2").FirstOrDefault(); // finds all rows with id==2 and selects first or null if haven't found any if(dr != null) { dr["Product_name"] = "cde"; //changes the Product_name }
Vous pouvez trouver cette ligne avec
DataRow row = table.Select("Product_id=2").FirstOrDefault();
et le mettre à jour
row["Product_name"] = "cde";
Essayez la méthode SetField :
table.Rows[rowIndex].SetField(column, value); table.Rows[rowIndex].SetField(columnIndex, value); table.Rows[rowIndex].SetField(columnName, value);
Si votre dataset est trop volumineux, commencez par sélectionner les lignes requirejses par Select (). cela arrêtera de continuer la boucle.
DataRow[] selected = table.Select("Product_id = 2")
Ensuite, parcourez un sous-ensemble et mettez à jour
foreach (DataRow row in selected) { row["Product_price"] = ""; }
Vous pouvez parcourir le DataTable comme ci-dessous et définir la valeur
foreach(DataTable thisTable in dataSet.Tables) { foreach(DataRow row in thisTable.Rows) { row["Product_name"] = "cde"; } }
OU
thisTable.Rows[1]["Product_name"] = "cde";
J’espère que cela t’aides
Essayez ceci, je ne suis pas sûr à 100%
for( int i = 0 ;i< dt.Rows.Count; i++) { If(dt.Rows[i].Product_id == 2) { dt.Rows[i].Columns["Product_name"].ColumnName = "cde"; } }