How to add checkboxlist selected items to string array? - c#

public string[] selected()
{
string[] selecteditems = new string[chbindustry.Items.Count];
for (int i = 0; i < chbindustry.Items.Count-1; i++)
{
if (chbindustry.Items[i].Selected)
{
selecteditems[i] = chbindustry.Items[i].Text.ToString();
//string Va = string.Empty;
//Va = chbindustry.Items[i].Text.ToString();
// selecteditems[i] = Va;
}
}
return selecteditems;
}
In this code I want to add checkboxlist selected items to string array "selecteditems[i]" here using "selecteditems[i]" I need to bind in this code and show to only selected items
foreach (string s in subdirectoryEntries)
{
DirectoryInfo d = new DirectoryInfo(s);
for (int i = 1; i <= d.GetFiles().Length / 3; i++)
{
selected();
Page.ClientScript.RegisterArrayDeclaration("ImgPaths", "'" + "BusinessCards/" + s.Remove(0, s.LastIndexOf('\\') + 1) + "/" + i + ".jpg'");
Page.ClientScript.RegisterArrayDeclaration("refs", "'" + "DesignBCs.aspx?img=BusinessCards/" + s.Remove(0, s.LastIndexOf('\\') + 1) + "/" + i + "&Side=2'");
}
}

Did you mean this?
var selecteditems = chbindustry.Items.Cast<ListItem>().Where(i=>i.Selected).Select(i=>i.ToString()).ToArray();

Related

C# By Pressing button do in background

Can someone explain me how can i do async tasks from this code?
Currently code does work and do the job but i have tried to make it async? So app will not get frozen while its executing but no success.
public WebpageLocalScanner()
{
InitializeComponent();
InitializeListView();
}
internal string GetType(string ip, int port)
{
try
{
if (port == 1234 || port == 4321)
{
string urlAddress = string.Format("http://{0}", ip);
string text = this.GetHttpData(ip, 80, urlAddress, 5120).ToUpper();
if (text.Contains("<HTML>"))
{
return "Webpage is here";
}
}
}
catch (Exception)
{
}
return string.Empty;
}
public void AddItem() {
listView1.Items.Clear();
int froms192 = Convert.ToInt32(tB1.Text);
int froms168 = Convert.ToInt32(tB2.Text);
int froms1a = Convert.ToInt32(tB3.Text);
int froms1b = Convert.ToInt32(tB4.Text);
int fromports = Convert.ToInt32(tBp1.Text);
int toports = Convert.ToInt32(tBp2.Text);
string FromIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
int FromPort = fromports;
int ToPort = toports;
int tos192 = Convert.ToInt32(tB5.Text);
int tos168 = Convert.ToInt32(tB6.Text);
int tos1a = Convert.ToInt32(tB7.Text);
int tos1b = Convert.ToInt32(tB8.Text);
string ToIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
if (froms1a < tos1a || froms1b < tos1b)
{
for (int i = froms1b; i <= tos1b; i++)
{
for (int u = froms1a; u <= tos1a; u++)
{
for (int p = fromports; p <= toports; p++)
{
string GenIP = froms192 + "." + froms168 + "." + u + "." + i;
string result = GetType(GenIP, p);
if (result != null) {
string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
var listViewItem = new ListViewItem(row);
listView1.Items.Add(listViewItem);
};
}
}
}
}
}
private void InitializeListView()
{
// Set the view to show details.
listView1.View = View.Details;
// Allow the user to edit item text.
listView1.LabelEdit = true;
// Allow the user to rearrange columns.
listView1.AllowColumnReorder = true;
// Display check boxes.
// listView1.CheckBoxes = true;
// Select the item and subitems when selection is made.
listView1.FullRowSelect = true;
// Display grid lines.
listView1.GridLines = true;
// Sort the items in the list in ascending order.
listView1.Sorting = SortOrder.Ascending;
// Attach Subitems to the ListView
listView1.Columns.Add("IP", 100, HorizontalAlignment.Left);
listView1.Columns.Add("PORT", 50, HorizontalAlignment.Left);
listView1.Columns.Add("SERVER", 100, HorizontalAlignment.Left);
listView1.Columns.Add("TYPE", 100, HorizontalAlignment.Left);
listView1.Columns.Add("COMMENT", 100, HorizontalAlignment.Left);
}
private void button1_Click(object sender, EventArgs e)
{
AddItem();
}
What im really struggle is understand how can i convert each function to return and can be used in background if its called.
Whatever i try its getting missing something.
Can you able to make it more clear for me?
What this does is simply scan local network to find current ip of webserver on other pc.
But 255 ips to do it takes a while and app just hungs and have to wait till its finished?
ANSWER CODE APPLIED:
public async void AddItem()
{
//listView1.Items.Clear();
int froms192 = Convert.ToInt32(tB1.Text);
int froms168 = Convert.ToInt32(tB2.Text);
int froms1a = Convert.ToInt32(tB3.Text);
int froms1b = Convert.ToInt32(tB4.Text);
int fromports = Convert.ToInt32(tBp1.Text);
int toports = Convert.ToInt32(tBp2.Text);
string FromIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
int FromPort = fromports;
int ToPort = toports;
int tos192 = Convert.ToInt32(tB5.Text);
int tos168 = Convert.ToInt32(tB6.Text);
int tos1a = Convert.ToInt32(tB7.Text);
int tos1b = Convert.ToInt32(tB8.Text);
string ToIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
if (froms1a < tos1a || froms1b < tos1b)
{
//var listViewItems = new List<ListViewItem>();
await Task.Run(() =>
{
for (int i = froms1b; i <= tos1b; i++)
{
List<string[]> rows = new List<string[]>();
for (int u = froms1a; u <= tos1a; u++)
{
for (int p = fromports; p <= toports; p++)
{
string GenIP = froms192 + "." + froms168 + "." + u + "." + i;
string result = GetProxyType(GenIP, p);
if (result != "")
{
string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
var listViewItem = new ListViewItem(row);
if (listView1.InvokeRequired)
{
listView1.Invoke(new MethodInvoker(delegate
{
listView1.Items.Add(listViewItem);
//row.Checked = true;
}));
}
else
{
listView1.Items.Add(listViewItem);
listViewItem.Checked = true;
}
//string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
//listViewItems.Add(row);
//listView1.Items.AddRange(rows.Select(a => new ListViewItem(a)).ToArray());
};
}
}
}
});
}
}
private async void button1_Click(object sender, EventArgs e)
{
AddItem();
}
You use the async keyword on any method that will need to run asynchronously. You use await on the code that you want to run in the background. Await yields control back to the UI until that code finishes. You only use async on methods that have an await, and you only use await on code that returns a Task. If you have code that you need to run in the background and it doesn't return a Task, you can wrap it in a Task.Run.
I think this will work, but I haven't tested it.
public WebpageLocalScanner()
{
InitializeComponent();
InitializeListView();
}
internal string GetType(string ip, int port)
{
try
{
if (port == 1234 || port == 4321)
{
string urlAddress = string.Format("http://{0}", ip);
string text = this.GetHttpData(ip, 80, urlAddress, 5120).ToUpper();
if (text.Contains("<HTML>"))
{
return "Webpage is here";
}
}
}
catch (Exception)
{
}
return string.Empty;
}
public async void AddItem() {
listView1.Items.Clear();
int froms192 = Convert.ToInt32(tB1.Text);
int froms168 = Convert.ToInt32(tB2.Text);
int froms1a = Convert.ToInt32(tB3.Text);
int froms1b = Convert.ToInt32(tB4.Text);
int fromports = Convert.ToInt32(tBp1.Text);
int toports = Convert.ToInt32(tBp2.Text);
string FromIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
int FromPort = fromports;
int ToPort = toports;
int tos192 = Convert.ToInt32(tB5.Text);
int tos168 = Convert.ToInt32(tB6.Text);
int tos1a = Convert.ToInt32(tB7.Text);
int tos1b = Convert.ToInt32(tB8.Text);
string ToIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
if (froms1a < tos1a || froms1b < tos1b)
{
var rows = new List<string[]>();
await Task.Run(() => {
for (int i = froms1b; i <= tos1b; i++)
{
for (int u = froms1a; u <= tos1a; u++)
{
for (int p = fromports; p <= toports; p++)
{
string GenIP = froms192 + "." + froms168 + "." + u + "." + i;
string result = GetType(GenIP, p);
if (result != null) {
string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
rows.add(row);
};
}
}
}
});
listView1.Items.AddRange(rows.Select(a => new ListViewItem(a)).ToArray());
}
}
private void InitializeListView()
{
// Set the view to show details.
listView1.View = View.Details;
// Allow the user to edit item text.
listView1.LabelEdit = true;
// Allow the user to rearrange columns.
listView1.AllowColumnReorder = true;
// Display check boxes.
// listView1.CheckBoxes = true;
// Select the item and subitems when selection is made.
listView1.FullRowSelect = true;
// Display grid lines.
listView1.GridLines = true;
// Sort the items in the list in ascending order.
listView1.Sorting = SortOrder.Ascending;
// Attach Subitems to the ListView
listView1.Columns.Add("IP", 100, HorizontalAlignment.Left);
listView1.Columns.Add("PORT", 50, HorizontalAlignment.Left);
listView1.Columns.Add("SERVER", 100, HorizontalAlignment.Left);
listView1.Columns.Add("TYPE", 100, HorizontalAlignment.Left);
listView1.Columns.Add("COMMENT", 100, HorizontalAlignment.Left);
}
private async void button1_Click(object sender, EventArgs e)
{
AddItem();
}

Display Null Value or Zero-Valued Data from Textfile in C# ASP.Net

This code functions by reading textfile content, manipulate the data in it and display the output in a textbox.
using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
{
string filenameDate = FileUpload1.FileName.Substring(15, 2);
Dictionary<string, int> dMyobject = new Dictionary<string, int>();
while (!stRead.EndOfStream)
{
var readedLine = stRead.ReadLine();
if (!string.IsNullOrWhiteSpace(readedLine))
{
//int readedLineTime = Convert.ToInt32(readedLine.Substring(09, 02));
string sDate = readedLine.Substring(0, 11);
MatchCollection collection = Regex.Matches(readedLine, #"D;");
countedChars = collection.Count;
if (!dMyobject.Keys.Contains(sDate))
{
dMyobject.Add(sDate, collection.Count);
}
else
{
dMyobject[sDate] = dMyobject[sDate] + collection.Count;
}
}
textfileContent += readedLine + Environment.NewLine;
i++;
}
txtContent.Text = textfileContent;
lblLineCount.Text = i.ToString();
//Label1.Text = this.TextBox1.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length.ToString();
lblFileDate.Text = filenameDate;
foreach (var item in dMyobject)
{
textfileOutput += (item.Key + " " + item.Value) + Environment.NewLine;
// textfileOutput += (item.Value) + Environment.NewLine;
}
txtOutput.Text = textfileOutput;
}
each line in the textfile contains a date and series of pattern. this code read each lines separated by dates and count the total occurrence of a pattern, in this example, counting the pattern "D;" and summarize its total per Date (lines with same date should be summed-up). For example
running the code will give this current output
2016-12-01 - 7
2016-12-02 - 9
2016-12-03 - 5
2016-12-05 - 1
My Objective and desired output should include in the output the date with NULL VALUE. In my example, there was no 2016-12-04 record, **expected output should have displayed the date still and display 0 or blank such as:**
2016-12-01 - 7
2016-12-02 - 9
2016-12-03 - 5
2016-12-04 - 0
2016-12-05 - 1
This will do it.
using (StreamReader stRead = new StreamReader(#"c:\test.txt"))
{
string filenameDate = "test";
string textfileContent = string.Empty;
int i = 0;
string textfileOutput = string.Empty;
Dictionary<string, int> dMyobject = new Dictionary<string, int>();
while (!stRead.EndOfStream)
{
var readedLine = stRead.ReadLine();
if (!string.IsNullOrWhiteSpace(readedLine))
{
string sDate = readedLine.Substring(0, 11).Trim();
MatchCollection collection = Regex.Matches(readedLine, #"D;");
if (!dMyobject.Keys.Contains(sDate))
{
dMyobject.Add(sDate, collection.Count);
}
else
{
dMyobject[sDate] = dMyobject[sDate] + collection.Count;
}
}
textfileContent += readedLine + Environment.NewLine;
i++;
}
var date = DateTime.Parse(dMyobject.First().Key);
var beginOfMonth = new DateTime(date.Year, date.Month, 1);
var days = new Dictionary<string, int>();
for (var x = 0; x < DateTime.DaysInMonth(date.Year, date.Month); x++)
{
days.Add(beginOfMonth.AddDays(x).ToString("yyyy-MM-dd"), 0);
}
foreach (var item in days)
{
textfileOutput += (dMyobject.ContainsKey(item.Key) ? (item.Key + " " + dMyobject[item.Key]) : (item.Key + " 0")) + Environment.NewLine;
}
}
So the the last bit of code first creates the date ranges that are needed by picking a date from your Dictionary and iterating to the last day of that month. It then checks your matches and counts against the date ranges and if there is a match, use the updated count instead of 0.
In your upload file, there have 2016-12-04 line, you just edit you Regex for got all char and count the total score.
fix 1:Check whether the continuous time.
using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
{
string filenameDate = FileUpload1.FileName.Substring(15, 2);
SortedDictionary<string, int> dMyobject = new SortedDictionary<string, int>(); //this is a dictionary sorted by key
DateTime? startDatetime = null, endDatetime = null;//got mininum and maxinum dates, at late will be check the continuous time
while (!stRead.EndOfStream)
{
var readedLine = stRead.ReadLine();
if (!string.IsNullOrWhiteSpace(readedLine))
{
string sDate = readedLine.Substring(0, 11).Trim();
DateTime date;
if (DateTime.TryParse(sDate, out date))
{
if (startDatetime.HasValue == false)
startDatetime = date;
endDatetime = date;
//got start date and end date
//if date does not from big to small
//here need compare bwteen date and endDatetime
}
MatchCollection collection = Regex.Matches(readedLine, "(?<c>[A-Z]+);");
if (!dMyobject.Keys.Contains(sDate))
{
dMyobject.Add(sDate, GetTotal(collection));
}
else
{
dMyobject[sDate] = dMyobject[sDate] + GetTotal(collection);
}
}
textfileContent += readedLine + Environment.NewLine;
i++;
}
//here is check the continuous time
if (startDatetime.HasValue && endDatetime.HasValue)
{
for (var dt = startDatetime; dt.Value.CompareTo(endDatetime) <= 0; dt = dt.Value.AddDays(1))
{
string key = dt.Value.ToString("yyyy-MM-dd");
if (!dMyobject.Keys.Contains(key))
{
dMyobject[key] = 0;
}
}
}
txtContent.Text = textfileContent;
lblLineCount.Text = i.ToString();
//Label1.Text = this.TextBox1.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length.ToString();
lblFileDate.Text = filenameDate;
foreach (var item in dMyobject)
{
textfileOutput += (item.Key + " " + item.Value) + Environment.NewLine;
// textfileOutput += (item.Value) + Environment.NewLine;
}
txtOutput.Text = textfileOutput;
}
//this method is a new method, it got total score, and if you rule chanage you can set `D` +1, `A` +2 etc.
private int GetTotal(MatchCollection collection)
{
Dictionary<string, int> point = new Dictionary<string, int>();
point["D"] = 1;
point["A"] = 0;
int total = 0;
foreach (Match m in collection)
{
string str = m.Groups["c"].Value;
if (point.ContainsKey(str))
total += point[str];
}
return total;
}
Adding comments JohanP Answer, code is working fine expect date sub-string is wrong in original code and there are no issue with Dictionary 0 Value
JohanP's answer is a big help, but there are limitations because it also needs to write the first dates when it is null. So based from his answer, I have come up with this codes.
using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
{
Dictionary<string, int> dMyobject = new Dictionary<string, int>();
while (!stRead.EndOfStream)
{
var readedLine = stRead.ReadLine();
if (!string.IsNullOrWhiteSpace(readedLine))
{
//int readedLineTime = Convert.ToInt32(readedLine.Substring(11, 02));
string sDate = readedLine.Substring(11, 2);
MatchCollection collection = Regex.Matches(readedLine, #"D;");
countedChars = collection.Count;
if (!dMyobject.Keys.Contains(sDate))
{
dMyobject.Add(sDate, collection.Count);
}
else
{
dMyobject[sDate] = dMyobject[sDate] + collection.Count;
}
}
textfileContent += readedLine + Environment.NewLine;
i++;
}
txtContent.Text = textfileContent;
lblLineCount.Text = i.ToString();
var prevDate = string.Empty;
int tester = 01;
foreach (var item in dMyobject)
{
int testCorrectStart = Convert.ToInt32(item.Key) - tester;
if (testCorrectStart == 0)
{
if (!string.IsNullOrEmpty(prevDate))
{
var cur = Int32.Parse(item.Key); // convert current key into int
var prev = Int32.Parse(prevDate);
int dayDiff = cur - prev;
for (var x = 0; x < dayDiff - 1; x++) // run through day difference, add it to the last date that was added
{
textfileOutput += ((prev + (x + 1)).ToString() + " 0" + Environment.NewLine);
}
}
textfileOutput += (item.Key + " " + item.Value) + Environment.NewLine;
prevDate = item.Key;
tester++;
}
else
{
if (!string.IsNullOrEmpty(tester.ToString()))
{
var cur = Int32.Parse(item.Key); // convert current key into int
var prev = Int32.Parse(tester.ToString());
int dayDiff = cur - prev;
for (var x = 0; x < dayDiff ; x++) // run through day difference, add it to the last date that was added
{
textfileOutput += ("0" +(prev + x).ToString() + " 0" + Environment.NewLine);
}
}
textfileOutput += (item.Key + " " + item.Value) + Environment.NewLine;
prevDate = item.Key;
tester = Convert.ToInt32(prevDate) + 1;
}
}
txtOutput.Text = textfileOutput;
}
you can test its correcteness

Count Pattern / String Occurrence Per Group using C# in ASP.Net

This is the sample textfile
Line is categorized by date, per line date can be repeated like for example, December 1 and 2 have two entries. Expected Output should be counting the pattern "D;" for example per date
2016-12-01 - 7
2016-12-02 - 9
2016-12-03 - 5
This is what I currently have
using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
{
while (!stRead.EndOfStream)
{
var readedLine = stRead.ReadLine();
if (!string.IsNullOrWhiteSpace(readedLine))
{
for (int j = 01; j <= 31; j++)
{
int readedLineTime = Convert.ToInt32(readedLine.Substring(09, 02));
if (readedLineTime == j)
{
MatchCollection collection = Regex.Matches(readedLine, #"D;");
countedChars = collection.Count;
textfileOutput += readedLine.Substring(0, 11) + " - " + countedChars + Environment.NewLine;
}
}
}
textfileContent += readedLine + Environment.NewLine;
i++;
}
TextBox1.Text = textfileOutput;
TextBox2.Text = textfileContent;
Label1.Text = i.ToString();
//Label1.Text = this.TextBox1.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length.ToString();
// Label2.Text = filename;
}
and this is its current output that is being displayed in multiple line textbox
2016-12-01 - 4
2016-12-01 - 3
2016-12-02 - 4
2016-12-02 - 5
2016-12-03 - 5
Let me know if this works.
Dictionary<string, int> dMyobject = new Dictionary<string, int>();
while (!stRead.EndOfStream)
{
var readedLine = stRead.ReadLine();
if (!string.IsNullOrWhiteSpace(readedLine))
{
int readedLineTime = Convert.ToInt32(readedLine.Substring(09, 02));
string sDate = readedLine.Substring(0, 11);
MatchCollection collection = Regex.Matches(readedLine, #"D;");
countedChars = collection.Count;
if (!dMyobject.Keys.Contains(sDate))
{
dMyobject.Add(sDate, collection.Count);
}
else
{
dMyobject[sDate] = dMyobject[sDate] + collection.Count;
}
}
textfileContent += readedLine + Environment.NewLine;
i++;
}
You will need to push these values in some collection. So that you can check it.
Later, for using these values for printing or anything, use following
foreach (var item in dMyobject)
{
Console.WriteLine(item.Key + " " + item.Value);
}
string line = "";
Dictionary<string, int> list = new Dictionary<string, int>();
int count;
if (File.Exists(fileName) == true)
{
StreamReader objReader;
objReader = new StreamReader(fileName);
StreamWriter file = new StreamWriter(OutputfileName");
do
{
line = objReader.ReadLine();
string temp = line.Substring(0, 10);
if (!list.ContainsKey(temp))
{
MatchCollection collection = Regex.Matches(line, #"D;");
count = collection.Count;
list.Add(temp, count);
}
else
{
MatchCollection collection = Regex.Matches(line, #"D;");
count = collection.Count;
var val = list[temp];
list[temp] = count + val;
}
} while (objReader.Peek() != -1);
foreach (var j in list)
{
file.WriteLine(j.Key + " - " + j.Value+"\n");
}
file.Close();
}

How to get all rows in two foreach?

I don't know how to get the first rows of a first foreach run with the first rows of a second foreach.
The second rows of a first foreach run with the second rows of the second foreach.
Because I get all data into List<> and the foreach two list.
My code like:
for (int i = valuesFrom; i < valuesTo; i++)
{
values = name + " " + i;
lstAliasImage.Add(values);
}
for (int j = 0; j < lstImgAdded.Items.Count; j++)
{
string imgPath = lstImgAdded.Items[j].Text;
lstNameImage.Add(imgPath);
}
foreach (var alias in lstAliasImage)
{
foreach (var items in lstNameImage)
{
txtUser.Text = alisa;
Save(items + " " + txtUser.Text);
}
}
You can do that with a good old for cycle:
for (int i = 0; i < lstAliasImage.Count; i++) {
txtUser.Text = listAliasImage.ElementAt(i);
Save(lstNameImage.ElementAt(i) + " " + txtUser.Text);
}
Here I assumed that by alisa you meant alias. Also, I assumed that the element count is the same. If your type has an indexer defined, then you can use [i] instead of ElementAt(i).
Using a for loop will solve your problem;
for (int i = 0; i < lstAliasImage.Count; i++)
{
txtUser.Text = lstAliasImage[i];
Save(lstNameImage[i] + " " + txtUser.Text);
}
But it is better to solve this in a different way. As both Lists are related, you should create a struct, and store that in the list. At least to avoid errors if both lists are not the same length. Something like
public struct ImageStruct
{
public String alias;
public String name;
}
List<ImageStruct> images = new List<ImageStruct>();
for (int i = valuesFrom; i < valuesTo; i++)
{
images.Add(new ImageStruct()
{
alias="alias " + i,
name="name " + i
});
}
foreach (var item in images)
{
txtUser.Text = item.alias;
Save(item.name + " " + item.alias);
}
I hope you get the idea (I did not test the above code).

how to read the every position of search keyword from the array of files

This is my code now I can only find the last position of the word.
string[] textFiles = Directory.GetFiles(#"C:/PCRequestFiles");
foreach (string fileName in textFiles)
{
string[] lines = File.ReadAllLines(fileName);
for (int x = 0; x < lines.Length; x++)
{
int warnPos = lines[x].IndexOf(((TextBox)sm1.FindControl("Findtxt")).Text,
StringComparison.CurrentCultureIgnoreCase);
if (warnPos > 0)
{
((Label)sm1.FindControl("Findlbl")).Text = "The data is in the File " + fileName.Substring(29) + " at line " + ( x + 1) + " ";
dr = dt.NewRow();
dr["FileName"] = fileName.Substring(29);
dt.Rows.Add(dr);
gvFileGenStatus.DataSource = dt;
gvFileGenStatus.DataBind();
}
}
}
Thanks for all the help in advance ).
Changes;
if (warnPos > 0) has to be if (warnPos > -1) since this method returns 0 as valid index.
Findtxt label only displays the last index found. So we need to concatenate all the lines found.
string[] textFiles = Directory.GetFiles(#"C:/PCRequestFiles");
foreach (string fileName in textFiles)
{
string[] lines = File.ReadAllLines(fileName);
for (int x = 0; x < lines.Length; x++)
{
int warnPos = lines[x].IndexOf(((TextBox)sm1.FindControl("Findtxt")).Text, StringComparison.CurrentCultureIgnoreCase);
//Change to > -1
if (warnPos > -1)
{
//Add += to concatenate string
((Label)sm1.FindControl("Findlbl")).Text += "The data is in the File " + fileName.Substring(29) + " at line " + (x + 1) + " ";
dr = dt.NewRow();
dr["FileName"] = fileName.Substring(29);
dt.Rows.Add(dr);
gvFileGenStatus.DataSource = dt;
gvFileGenStatus.DataBind();
}
}
}

Categories

Resources