Exporting random rows to excel file based on int value - c#

So I have my report printing out exactly what I want (almost). Now I just have to get one feature finished. I have a number that is generated and placed into a variable called percentage.
percentage equals the the rounded number of all the licenses in the database that allAttendeeLicenseNos pulls in multiplied by the number that is entered in by the user multiplied .01 to make it a percentage.
So my goal is to see all the attendees, and say okay this person only wants a percentage of them, but it doesn't matter which ones so I am going to grab random rows until the percentage number is there.
Again, please be patient as I am very new to C# and am learning.
var percentage = Math.Round(allAttendeeLicenseNos.Count() * Percentage * 0.01);
var allAttendeeData = _mii.LicenseeRecords.Where(r => allAttendeeLicenseNos.Contains(r.LicenseNumber)).Where(i => i.LicenseStatus.Equals(chosenLicenseStatus)).ToList();
var retval = _mapper.Map<List<DLILicense>, List<RandomAuditViewModel>>(allAttendeeData);
using (var exs = new ExcelPackage())
{
var worksheet = exs.Workbook.Worksheets.Add("RandomAuditReport");
var row = 1;
var col = 1;
var properties = typeof(RandomAuditViewModel).GetProperties();
foreach (var field in properties)
{
worksheet.Cells[row, col].Style.Font.Bold = true;
var displayName = field.GetCustomAttribute<DisplayAttribute>() != null ?
field.GetCustomAttribute<DisplayAttribute>().GetName() :
field.Name;
worksheet.SetValue(row, col, displayName);
col++;
}
col = 1;
row++;
retval.ForEach(i =>
{
var periodOrdinal = _ce.Events
.Where(e => e.Attendees.Select(a => a.LicenseNumber).Contains(i.LicenseNumber))
.Select(e => e.Course.CertificationPeriod)
.OrderBy(p => p.StartDate)
.ToList()
.IndexOf(thePeriod) + 1;
i.MetRequirements = determineIfCeMet(i.LicenseNumber, i.LicenseTypeCode, i.DateOfOriginalLicensure, periodOrdinal, thePeriod.Id, thePeriod.EndDate, thePeriod.Board);
foreach (var field in properties)
{
if (field.GetCustomAttribute<DataTypeAttribute>().DataType.Equals(DataType.Date))
{
var value = ((DateTime)field.GetValue(i));
worksheet.Cells[row, col].Style.Numberformat.Format = "MM/dd/yyyy";
worksheet.Cells[row, col].Formula = "=DATE(" + value.Year + "," + value.Month + "," + value.Day + ")";
}
else worksheet.SetValue(row, col, field.GetValue(i));
col++;
}
col = 1;
row++;
});
return exs.GetAsByteArray();

Something like below?
retval.ForEach(i =>
{
if(retval.IndexOf(i) == percentage)
break;
var periodOrdinal = _ce.Events
.Where(e => e.Attendees.Select(a => a.LicenseNumber).Contains(i.LicenseNumber))
.Select(e => e.Course.CertificationPeriod)
.OrderBy(p => p.StartDate)
.ToList()
.IndexOf(thePeriod) + 1;
i.MetRequirements = determineIfCeMet(i.LicenseNumber, i.LicenseTypeCode, i.DateOfOriginalLicensure, periodOrdinal, thePeriod.Id, thePeriod.EndDate, thePeriod.Board);
foreach (var field in properties)
{
if (field.GetCustomAttribute<DataTypeAttribute>().DataType.Equals(DataType.Date))
{
var value = ((DateTime)field.GetValue(i));
worksheet.Cells[row, col].Style.Numberformat.Format = "MM/dd/yyyy";
worksheet.Cells[row, col].Formula = "=DATE(" + value.Year + "," + value.Month + "," + value.Day + ")";
}
else worksheet.SetValue(row, col, field.GetValue(i));
col++;
}
col = 1;
row++;
})
Where you're using this
if(retval.IndexOf(i) == percentage)
break;
to determine if you've hit the percentage, then breaking out of the ForEach.

Related

How to print only the specified rows from the grid view

Welcome
I have a sales screen with an invoice that is displayed in the grid view with the report of Extra Robert
I just want when I select some rows using the select box only the selected rows are printed on one page I tried this code but it prints each row in a separate report
I just want to print the selected rows on one page. Thank you
for (int i = 0; i <= DgvSale.Rows.Count - 1; i++)
{
if (Convert.ToBoolean(DgvSale.Rows[i].Cells[8].Value) == true)
{
tblRpt1 = db.readData("SELECT [Order_ID] as 'رقم الفاتورة',talb_ID as 'طلب',[Cust_Name] as 'اسم العميل',Products.Pro_Name as 'المنتج',Products.Group_ID as 'قسم',Products_Group.Group_Name as 'اسم القسم',[Sales_Detalis].[Qty] as 'الكمية',[Price] as 'السعر',[User_Name] as 'الكاشير',[Date] as 'التاريخ',[Unit] as 'الوحدة',[Sales_Detalis].Tax_Value as 'الضريبة',Price_Tax as 'السعر بعد الضريبة',[typetalab] as 'نوع الطلب',[priceservic] as 'خدمة',[shiftname] as 'شيفت',notes as 'ملاحظات',shiftnum as 'شيفت رقم',Print_Group.Print_Name,Print_Group.Name_Group FROM [dbo].[Sales_Detalis] , Products,Products_Group,Print_Group where Products.Pro_ID = Sales_Detalis.Pro_ID and Products.Pro_ID= " + row1.Cells[0].Value + " and Order_ID = " + id + " and Products.Group_ID = Products_Group.Group_ID and Print_Group.Name_Group=Products.Group_ID ORDER BY Order_ID ASC", "");
}
}
if (Properties.Settings.Default.SalePrintKind == "8CM")
{
devOrderSales2 rpt = new devOrderSales2() { DataSource = tblRpt1, DataMember = "OrderSales2" };
rpt.DataSource = tblRpt1;
rpt.Parameters["ID1"].Value = id;
rpt.PrinterName = Properties.Settings.Default.PrinterNameSteker;
rpt.xrTableCell8.Visible=true;
if (Properties.Settings.Default.saleprintauto == "0")
{
rpt.Print();
}
else if (Properties.Settings.Default.saleprintauto == "1")
{
rpt.ShowPreviewDialog();
}
}
I suggest to create the WHERE condition dynamically with the selected records:
string sql = #"SELECT [Order_ID] as 'رقم الفاتورة',talb_ID as 'طلب',[Cust_Name] as 'اسم العميل',Products.Pro_Name as 'المنتج',Products.Group_ID as 'قسم',Products_Group.Group_Name as 'اسم القسم',[Sales_Detalis].[Qty] as 'الكمية',[Price] as 'السعر',[User_Name] as 'الكاشير',[Date] as 'التاريخ',[Unit] as 'الوحدة',[Sales_Detalis].Tax_Value as 'الضريبة',Price_Tax as 'السعر بعد الضريبة',[typetalab] as 'نوع الطلب',[priceservic] as 'خدمة',[shiftname] as 'شيفت',notes as 'ملاحظات',shiftnum as 'شيفت رقم',Print_Group.Print_Name,Print_Group.Name_Group
FROM
[dbo].[Sales_Detalis]
INNER JOIN Products
ON Products.Pro_ID = Sales_Detalis.Pro_ID
INNER JOIN Products_Group
ON Products.Group_ID = Products_Group.Group_ID
INNER JOIN Print_Group
ON Print_Group.Name_Group=Products.Group_ID
WHERE
Products.Pro_ID IN ({0}) AND Order_ID = {1}
ORDER BY Order_ID ASC";
var productIds = new List<int>();
for (int i = 0; i <= DgvSale.Rows.Count - 1; i++) {
if (Convert.ToBoolean(DgvSale.Rows[i].Cells[8].Value) == true) {
productIds.Add(Convert.ToInt32(DgvSale.Rows[i].Cells[0].Value));
}
}
if (Properties.Settings.Default.SalePrintKind == "8CM" && productIds.Count > 0) {
string commandText = String.Format(sql, String.Join(", ", productIds), id);
tblRpt1 = db.readData(commandText, "");
var rpt = new devOrderSales2 {
DataSource = tblRpt1,
DataMember = "OrderSales2",
PrinterName = Properties.Settings.Default.PrinterNameSteker
};
rpt.xrTableCell8.Visible = true;
rpt.Parameters["ID1"].Value = id;
if (Properties.Settings.Default.saleprintauto == "0") {
rpt.Print();
} else if (Properties.Settings.Default.saleprintauto == "1") {
rpt.ShowPreviewDialog();
}
}
Also, you should use the modern JOIN syntax instead of the outdated join conditions in the WHERE clause.
Note that I have set up a SQL string with {0} and {1} as placeholders later being replaced with the String.Format method. I assumed the product ids to be of type int. The resulting WHERE conditions looks something like this:
WHERE
Products.Pro_ID IN (12, 30, 55, 68) AND Order_ID = 17
The C# verbatim strings introduced with #" allow you to include line breaks within the string and to make the SQL text more readable.
row1 always points to the same row. Get the row dynamically with DgvSale.Rows[i] instead, within the loop.
One way is to first collect all the relevant IDs from the rows, and only do 1 db query, eg:
var toprint_ids = new List<long>();
for (int i = 0; i <= DgvSale.Rows.Count - 1; i++)
{
if (Convert.ToBoolean(DgvSale.Rows[i].Cells[8].Value) == true)
{
var itm_id = Convert.ToInt64(row1.Cells[0].Value);
ids.Add(itm_id);
}
}
if (toprint_ids.Count == 0)
return;
tblRpt1 = db.readData("SELECT [Order_ID] as 'رقم الفاتورة',talb_ID as 'طلب',[Cust_Name] as 'اسم العميل',Products.Pro_Name as 'المنتج',Products.Group_ID as 'قسم',Products_Group.Group_Name as 'اسم القسم',[Sales_Detalis].[Qty] as 'الكمية',[Price] as 'السعر',[User_Name] as 'الكاشير',[Date] as 'التاريخ',[Unit] as 'الوحدة',[Sales_Detalis].Tax_Value as 'الضريبة',Price_Tax as 'السعر بعد الضريبة',[typetalab] as 'نوع الطلب',[priceservic] as 'خدمة',[shiftname] as 'شيفت',notes as 'ملاحظات',shiftnum as 'شيفت رقم',Print_Group.Print_Name,Print_Group.Name_Group FROM [dbo].[Sales_Detalis] , Products,Products_Group,Print_Group where Products.Pro_ID = Sales_Detalis.Pro_ID and Products.Pro_ID in (" + string.Join(",", toprint_ids) + ") and Order_ID = " + id + " and Products.Group_ID = Products_Group.Group_ID and Print_Group.Name_Group=Products.Group_ID ORDER BY Order_ID ASC", "");
if (Properties.Settings.Default.SalePrintKind == "8CM")
{
devOrderSales2 rpt = new devOrderSales2() { DataSource = tblRpt1, DataMember = "OrderSales2" };
rpt.DataSource = tblRpt1;
rpt.Parameters["ID1"].Value = id;
rpt.PrinterName = Properties.Settings.Default.PrinterNameSteker;
rpt.xrTableCell8.Visible=true;
if (Properties.Settings.Default.saleprintauto == "0")
{
rpt.Print();
}
else if (Properties.Settings.Default.saleprintauto == "1")
{
rpt.ShowPreviewDialog();
}
}
Please notice the change in the query as well: in (" + string.Join(",", toprint_ids) + ")
Also if you have non-numeric IDs for your rows (eg Guids), then you need to change the list to a List<string> and also change your query to like in ('" + string.Join("','", toprint_ids) + "')

Search DataGridView for duplicates

I have this code to find duplicate values in DataGridView and mark them with different colors.
var rows = dataGridView1.Rows.OfType<DataGridViewRow>().Reverse().Skip(1);
var dupRos = rows.GroupBy(r => r.Cells["Date"].Value.ToString()).Where(g =>
g.Count() > 1).SelectMany(r => r.ToList());
foreach (var r in dupRos)
{
r.DefaultCellStyle.BackColor = Color.Pink;
}
foreach (var r in rows.Except(dupRos))
{
r.DefaultCellStyle.BackColor = Color.Cyan;
}
The code works fine.
I have changed the code so it will write in the second column the word Unique or Duplicate and a counter number for the duplicate cells.
int counter = 1;
var rows = dataGridView1.Rows.OfType<DataGridViewRow>().Reverse().Skip(1);
//ignore the last empty line
var dupRos = rows.GroupBy(r => r.Cells["Date"].Value.ToString()).Where(g =>
g.Count() > 1).SelectMany(r => r.ToList());
foreach (var r in dupRos)
{
r.DefaultCellStyle.BackColor = Color.Pink;
r.Cells["Time"].Value = "Dup" + counter;
counter++;
}
foreach (var r in rows.Except(dupRos))
{
r.DefaultCellStyle.BackColor = Color.Cyan;
r.Cells["Time"].Value = "Unick";
}
My problem is that the counter continues to count for all the duplicate groups and not reset itself every time its start with a different group of duplicate values.
How can I fix it?
Please try this one. If it works you can replace string type for lastDupRowDate with actual date type.
int counter = 1;
var rows = dataGridView1.Rows.OfType<DataGridViewRow>().Reverse().Skip(1);
//ignore the last empty line
var dupRos = rows.GroupBy(r => r.Cells["Date"].Value.ToString()).Where(g =>
g.Count() > 1).SelectMany(r => r.ToList());
string lastDupRowDate = null;
foreach (var r in dupRos)
{
r.DefaultCellStyle.BackColor = Color.Pink;
counter = lastDupRowDate == r.Cells["Date"].Value.ToString() ? count + 1 : 1;
lastDupRowDate = r.Cells["Date"].Value.ToString();
r.Cells["Time"].Value = "Dup" + counter;
}
foreach (var r in rows.Except(dupRos))
{
r.DefaultCellStyle.BackColor = Color.Cyan;
r.Cells["Time"].Value = "Unick";
}

Excel takes only that no of rows which has data in c#...my code works for some excel sheet not for all

Excel sheets made by different different clients...that code works when i make but not when user make..is anything problem with excel sheet so , i can tell user make like that way..or i can do anything with my code.
private void MeterUpdateByExcelSheet(HttpPostedFileBase file)
{
List<string> errorMessages = new List<string>();
int siteId = Helpers.SiteHelpers.Functions.GetSiteIdOfLoginUser().Value;
var stream = file.InputStream;
using (var package = new ExcelPackage(stream))
{
//getting number of sheets
var sheets = package.Workbook.Worksheets;
int totalProcessedMeters = 0;
if (sheets.Count > 0)
{
var sheet = sheets.FirstOrDefault();
//getting number of rows
var rows = sheet.Dimension.End.Row;
for (int row = 2; row <= rows; row++)
{
//get data for a row from excel
var meterNo = Convert.ToString(sheet.Cells[row, 1].Value);
int? sanctionLoadMains = (int)Convert.ToDecimal(sheet.Cells[row, 2].Value);
int? sanctionLoadDG = (int)Convert.ToDecimal(sheet.Cells[row, 3].Value);
int? unitArea = (int)Convert.ToDecimal(sheet.Cells[row, 4].Value);
int? creditLimit = (int)Convert.ToDecimal(sheet.Cells[row, 5].Value);
int? sMSWarning = (int)Convert.ToDecimal(sheet.Cells[row, 6].Value);
int? sMSWarning1 = (int)Convert.ToDecimal(sheet.Cells[row, 7].Value);
string date = sheet.Cells[row, 8].Value.ToString();
DateTime billingDate;
if (string.IsNullOrEmpty(date))
{
errorMessages.Add("Date is not given for MeterNo " + meterNo + " at row " + row);
continue;
}
if (!DateTime.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out billingDate))
{
errorMessages.Add("Date format is not correct for MeterNo. " + meterNo + " at row " + row);
continue;
}
if (!string.IsNullOrEmpty(meterNo))
{
meterNo = meterNo.PadLeft(9, '0');
var oldMeter = _meterRepository.GetBySiteIdAndMeterNo(siteId, meterNo);
var newMeter = _meterRepository.GetBySiteIdAndMeterNo(siteId, meterNo);
int wattUnit = 1000;//loads should be multiple of 1000(watt)
int smsWarningUnit = 100;//sms warnings should be multiple of 100
if (newMeter == null)
{
errorMessages.Add("MeterNo. " + meterNo + " does not exist.");
continue;
}
if (sanctionLoadMains.HasValue && sanctionLoadMains >= 500)
{
newMeter.LoadSenctionMain = sanctionLoadMains.Value;
}
if (sanctionLoadDG.HasValue && sanctionLoadDG >= 500)
{
newMeter.LoadSenctionDG = sanctionLoadDG.Value;
}
if (unitArea.HasValue)
{
newMeter.UnitArea = unitArea.Value;
}
if (creditLimit.HasValue)
{
newMeter.CreditLimit = creditLimit.Value;
}
if (sMSWarning.HasValue && sMSWarning >= 100)
{
newMeter.SMSWarningAmount = sMSWarning.Value;
}
if (sMSWarning1.HasValue && sMSWarning1 >= 100)
{
newMeter.SMSWarning1Amount = sMSWarning1.Value;
}
if (billingDate != null)
{
newMeter.BillingDate = billingDate.ToIndiaDateTime();
}
_meterRepository.AddOrUpdate(newMeter);
var meterNotes = Helpers.MeterHelpers.Functions.GetMeterNote(oldMeter, newMeter);
Helpers.MeterHelpers.Functions.AddMeterNotes(meterNo, meterNotes);
totalProcessedMeters++;
}
}
TempData["SuccessMessage"] = totalProcessedMeters + " Meter(s) have been updated successfully";
}

EPPLUS: Length of a DataValidation list cannot exceed 255 characters

This question is answered on a basic level on another post: here However for my case I am not able to hard code the validation values into the sheet I am pulling them from a database based on the content of the cell and will need to do a separate validation for 4 columns on every row. Is there a way this can be achieved? Thank you in advance.
// Data Validations //
// Product Validation //
for (int i = 2; i < rowCount; i++)
{
var val = ws.DataValidations.AddListValidation(ws.Cells[i, 5].Address);
val.ShowErrorMessage = true;
val.ErrorTitle = "Entry was invalid.";
val.Error = "Please choose options from the drop down only.";
var ticketEntity = ticketQueryable.Where(o => o.TTSTicketNumber == ws.Cells[i, 3].Value.ToString()).Single<CustCurrentTicketEntity>();
var prodIds = prodExtQueryable.Where(p => p.ZoneId == ticketEntity.ZoneId && p.TicketTypeId == ticketEntity.TicketTypeId);
if (ticketEntity != null)
{
var prodIdsList = new List<int>();
foreach (var prodId in prodIds)
{
prodIdsList.Add(prodId.ProductId);
}
var ProductList = ProductCache.Instance.AllProducts.Where(p => prodIdsList.Contains(p.ProductId)).Select(p => new SelectListItem() { Value = p.ProductId.ToString(), Text = p.Name });
foreach (var Result in ProductList)
{
var product = Result.Text;
val.Formula.Values.Add(product);
}
}
}
So yes as Ernie said What I did was add a second sheet "ProductValidations" and set it to Hidden (unhide it to check that it is working). I then Load my data from the DataTable and then add some basic EPPLUS formatting. I then iterate over the Rows and Insert values into the "ProductValidations" sheet for each cell. Next I convert my column number to the correct Excel Column letter name (A, AC, BCE etc) I then create a string to pass back as an Excel formula targeting the correct range of cells in the "ProductValidations" sheet. Also to anyone having an issue downloading the Excel file from the server this guid method works just fine for me.
public ActionResult DownloadExcel(EntityReportModel erModel, string filename)
{
var dataResponse = iEntityViewService.LoadEntityView(new EntityViewInput
{
SecurityContext = SessionCache.Instance.SecurityContext,
EntityViewName = "Ticket",
Parameters = new Dictionary<string, object> {
{"MinTicketDateTime", "04/26/16"}
}
});
var table = dataResponse.DataSet.Tables[0];
filename = "TICKETS-" + DateTime.Now.ToString("yyyy-MM-dd--hh-mm-ss") + ".xlsx";
using (ExcelPackage pack = new ExcelPackage())
{
ExcelWorksheet ws = pack.Workbook.Worksheets.Add(filename);
//Add second sheet to put Validations into
ExcelWorksheet productVal = pack.Workbook.Worksheets.Add("ProductValidations");
// Hide Validation Sheet
productVal.Hidden = OfficeOpenXml.eWorkSheetHidden.Hidden;
// Load the data from the datatable
ws.Cells["A1"].LoadFromDataTable(table, true);
ws.Cells[ws.Dimension.Address].AutoFitColumns();
int columnCount = table.Columns.Count;
int rowCount = table.Rows.Count;
// Format Worksheet//
ws.Row(1).Style.Font.Bold = true;
List<string> deleteColumns = new List<string>() {
"CurrentTicketId",
};
List<string> dateColumns = new List<string>() {
"TicketDateTime",
"Updated",
"InvoiceDate"
};
ExcelRange r;
// Format Dates
for (int i = 1; i <= columnCount; i++)
{
// if cell header value matches a date column
if (dateColumns.Contains(ws.Cells[1, i].Value.ToString()))
{
r = ws.Cells[2, i, rowCount + 1, i];
r.AutoFitColumns();
r.Style.Numberformat.Format = #"mm/dd/yyyy hh:mm";
}
}
// Delete Columns
for (int i = 1; i <= columnCount; i++)
{
// if cell header value matches a delete column
if ((ws.Cells[1, i].Value != null) && deleteColumns.Contains(ws.Cells[1, i].Value.ToString()))
{
ws.DeleteColumn(i);
}
}
int col = 0;
int Prow = 0;
int valRow = 1;
// Data Validations //
// Iterate over the Rows and insert Validations
for (int i = 2; i-2 < rowCount; i++)
{
Prow = 0;
col++;
valRow++;
// Add Validations At this row in column 7 //
var ProdVal = ws.DataValidations.AddListValidation(ws.Cells[valRow, 7].Address);
ProdVal.ShowErrorMessage = true;
ProdVal.ErrorTitle = "Entry was invalid.";
ProdVal.Error = "Please choose options from the drop down only.";
var ticketEntity = ticketQueryable.Where(o => o.TTSTicketNumber == ws.Cells[i, 3].Value.ToString()).Single<CustCurrentTicketEntity>();
// Product Validation //
var prodIds = prodExtQueryable.Where(p => p.ZoneId == ticketEntity.ZoneId && p.TicketTypeId == ticketEntity.TicketTypeId);
if (ticketEntity != null)
{
var prodIdsList = new List<int>();
foreach (var prodId in prodIds)
{
prodIdsList.Add(prodId.ProductId);
}
var ProductList = ProductCache.Instance.AllProducts.Where(p => prodIdsList.Contains(p.ProductId)).Select(p => new SelectListItem() { Value = p.ProductId.ToString(), Text = p.Name });
//For Each Item in the list move the row forward and add that value to the Validation Sheet
foreach (var Result in ProductList)
{
Prow++;
var product = Result.Text;
productVal.Cells[Prow, col].Value = product;
}
// convert column name from a number to the Excel Letters i.e A, AC, BCE//
int dividend = col;
string columnName = String.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}
// Pass back to sheeet as an Excel Formula to get around the 255 Char limit for Validations//
string productValidationExcelFormula = "ProductValidations!" + columnName + "1:" + columnName + Prow;
ProdVal.Formula.ExcelFormula = productValidationExcelFormula;
}
}
// Save File //
var fileStream = new MemoryStream(pack.GetAsByteArray());
string handle = Guid.NewGuid().ToString();
fileStream.Position = 0;
TempData[handle] = fileStream.ToArray();
// Note we are returning a filename as well as the handle
return new JsonResult()
{
Data = new { FileGuid = handle, FileName = filename }
};
}
}
[HttpGet]
public virtual ActionResult Download(string fileGuid, string fileName)
{
if (TempData[fileGuid] != null)
{
byte[] data = TempData[fileGuid] as byte[];
return File(data, "application/vnd.ms-excel", fileName);
}
else
{
//Log err
return new EmptyResult();
}
}

Search for a string in a DataGridView

I'm loading a CSV into a DataGridView by the following code
string rowValue;
string[] cellValue;
if(File.Exists(textBoxFilePath.Text.ToString().Trim()))
{
StreamReader streamReader = new StreamReader(textBoxFilePath.Text.ToString().Trim());
rowValue = streamReader.ReadLine();
cellValue = rowValue.Split(',');
for (int i = 0; i <= 4 - 1; i++)
{
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.Name = cellValue[i];
column.HeaderText = cellValue[i];
dataGridView1.Columns.Add(column);
}
// Reading content
while (streamReader.Peek() != -1)
{
rowValue = streamReader.ReadLine();
cellValue = rowValue.Split(',');
DateTime dt = new DateTime();
dt = DateTime.Now;
String month = dt.Month.ToString();
String day = dt.Day.ToString();
if (dt.Month < 10)
{
month = "0" + dt.Month;
}
if (dt.Day < 10)
{
day = "0" + dt.Day;
}
String stringDate = dt.Year.ToString() + "/" + month + "/" + day;
Console.WriteLine(dt.ToShortDateString());
Console.WriteLine(stringDate);
if (cellValue[2].CompareTo(stringDate) == 0)
{
dataGridView1.Rows.Add(cellValue);
}
}
streamReader.Close();
dataGridView1.Sort(this.dataGridView1.Columns["User-Name"], ListSortDirection.Ascending);
}
else
{
MessageBox.Show("No File is Selected");
}
I want to search for a User-Name. Which is column 2.
You can access arbitrary cell's value in DataGridView following the pattern:
dataGridView.Rows[rowIndex].Cells[columnIndex].Value
Are you looking for particular value of User-Name column? If so, you can handle it like this:
string searchedText = "some name";
var matchedRows = this.dataGridView1.Rows
.Cast<DataGridViewRow>()
.Select(r => r.Cells["User-Name"].Value)
.Where(v => v != null && v.ToString() == searchedText)
.ToList();
The matchedRows list will contain all rows that matched your search string. Note that you'll need to include using System.Linq; namespace for .Cast and .Where methods.

Categories