C# By Pressing button do in background - c#

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();
}

Related

I want to create dynamic textbox and ImageButton on Button Click Inside dynamic gridview cell

I have write code as following :
protected void Page_Load(object sender, EventArgs e)
{
Literal lt;
Label lb;
//Get ContentPlaceHolder
ContentPlaceHolder content = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
pnlStartDate = new Panel();
pnlStartDate.ID = "pnlStartDate";
// pnlStartDate.BorderWidth = 1;
pnlStartDate.Width = 100;
grvWorkOrder.Rows[rowIndex].Cells[13].Controls.Add(pnlStartDate);
lt = new Literal();
lt.Text = "<br />";
grvWorkOrder.Rows[rowIndex].Cells[13].Controls.Add(lt);
//Button To add TextBoxes
Button btnAddTxt = new Button();
btnAddTxt.ID = "btnAddTxt";
btnAddTxt.Text = "Add TextBox";
btnAddTxt.CausesValidation = false;
btnAddTxt.Click += new System.EventHandler(btnAddTextbox_Click);
grvWorkOrder.Rows[rowIndex].Cells[10].Controls.Add(btnAddTxt);
if (IsPostBack)
{
RecreateDateControls("txtStartDateDynamic", "TextBox", "img1StartDateDynamic", "ImageButton", "ceStartDateDynamic", "CalendarExtender");
}
rowIndex++;
}
}
}
}
protected void btnAddTextbox_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (btn.ID == "btnAddTxt")
{
Literal lt = new Literal();
lt.Text = "<br />";
int cntStartDate = FindOccurence("txtStartDateDynamic");
TextBox txt4 = new TextBox();
txt4.ID = "txtStartDateDynamic-" + Convert.ToString(cntStartDate + 1);
txt4.Width = 90;
pnlStartDate.Controls.Add(txt4);
int cntImgStartDate = FindOccurence("img1StartDateDynamic");
ImageButton img1StartDateDynamic = new ImageButton();
img1StartDateDynamic.ID = "img1StartDateDynamic-" + Convert.ToString(cntImgStartDate + 1);
img1StartDateDynamic.ImageUrl = "Images/calender.jpg";
img1StartDateDynamic.Width = 25;
img1StartDateDynamic.CausesValidation = false;
pnlStartDate.Controls.Add(img1StartDateDynamic);
int cntCeStartDate = FindOccurence("ceStartDateDynamic");
CalendarExtender ceStartDateDynamic = new CalendarExtender();
ceStartDateDynamic.ID = "ceStartDateDynamic-" + Convert.ToString(cntCeStartDate + 1);
ceStartDateDynamic.Enabled = true;
ceStartDateDynamic.TargetControlID = "txtStartDateDynamic-" + Convert.ToString(cntCeStartDate + 1);
ceStartDateDynamic.PopupButtonID = "img1StartDateDynamic-" + Convert.ToString(cntCeStartDate + 1);
ceStartDateDynamic.Format = "yyyy/MM/dd";
pnlStartDate.Controls.Add(ceStartDateDynamic);
pnlStartDate.Controls.Add(lt);
}
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateDateControls(string ctrlPrefix1, string ctrlType1, string ctrlPrefix2, string ctrlType2, string ctrlPrefix3, string ctrlType3)
{
string[] ctrls1 = Request.Form.ToString().Split('&');
string[] ctrls2 = Request.Form.ToString().Split('&');
string[] ctrls3 = Request.Form.ToString().Split('&');
int cnt1 = FindOccurence(ctrlPrefix1);
int cnt2 = FindOccurence(ctrlPrefix2);
int cnt3 = FindOccurence(ctrlPrefix3);
if (cnt1 > 0 && cnt2 > 0 && cnt3 > 0)
{
Literal lt;
for (int k = 1; k <= cnt1; k++)
{
for (int i = 0; i < ctrls1.Length ; i++)
{
if (ctrls1[i].Contains(ctrlPrefix1 + "-" + k.ToString()))
{
string ctrlName1 = ctrls1[i].Split('=')[0];
string ctrlValue1 = ctrls1[i].Split('=')[1];
if (ctrls1[i].Contains(ctrlPrefix2 + "-" + k.ToString()))
{
string ctrlName2 = ctrls1[i].Split('=')[0];
if (ctrls1[i].Contains(ctrlPrefix3 + "-" + k.ToString()))
{
string ctrlName3 = ctrls1[i].Split('=')[0];
if (ctrlType1 == "TextBox" && ctrlPrefix1 == "txtStartDateDynamic" && ctrlType2 == "ImageButton" && ctrlPrefix2 == "img1StartDateDynamic" && ctrlType3 == "CalendarExtender" && ctrlPrefix3 == "ceStartDateDynamic")
{
TextBox txt4 = new TextBox();
txt4.ID = ctrlName1;
txt4.Text = ctrlValue1;
txt4.Width = 90;
pnlStartDate.Controls.Add(txt4);
ImageButton img1StartDateDynamic = new ImageButton();
img1StartDateDynamic.ID = ctrlName2;
img1StartDateDynamic.ImageUrl = "Images/calender.jpg";
img1StartDateDynamic.Width = 25;
img1StartDateDynamic.CausesValidation = false;
pnlStartDate.Controls.Add(img1StartDateDynamic);
CalendarExtender ceStartDateDynamic = new CalendarExtender();
ceStartDateDynamic.ID = ctrlName3;
ceStartDateDynamic.Enabled = true;
ceStartDateDynamic.TargetControlID = ctrlName1;
ceStartDateDynamic.PopupButtonID = ctrlName2;
ceStartDateDynamic.Format = "yyyy/MM/dd";
pnlStartDate.Controls.Add(ceStartDateDynamic);
lt = new Literal();
lt.Text = "<br />";
pnlStartDate.Controls.Add(lt);
}
}
}
}
break;
}
}
}
}
But the problem is in RecreateDateControls() function ImageButton Counter cnt2 is zero therefore previous controls are not recreated what should i do for it.
go through the link..
create Dynamic Controls

get the value from the dictionary

I am working with Round Robin (RR). I am building random Round-Robin value. I get the time for the RR randomly. In the first run it shows me the current values that i have in the list. but when it goes to run for the second time it just say the index is not presented in the dictionary key. I am trying to fix this problem I have add the time and the quantum tim that the algorithm reduce the value from the dictionary and return back to the dictionary it the value is > 0.
Dictionary<int, int> waytosave = new Dictionary<int, int>();
List<int> randomListxCoor = new List<int>();
List<int> randomListyCoor = new List<int>();
int xCoor;
int yCoor;
Random coor = new Random();
Random setTimeRandom = new Random();
int randomTimeSetting;
int NodeIndex = 0;
Graphics graphDraw;
Graphics drawLine;
int TimeToProcess = 0;
string NodeName = "";
int QuantumTime = 1;
int TotalRouterTime = 0;
int NextNodeToProcess = 0;
public Form1()
{
InitializeComponent();
this.graphDraw = this.panel1.CreateGraphics();
this.drawLine = this.panel1.CreateGraphics();
}
private void btnRun_Click(object sender, EventArgs e)
{
int nodesNumber = (int)this.numNodes.Value;
SolidBrush getNodesDrawn = new SolidBrush(Color.LightYellow);
for (int x = 1; x <= nodesNumber; x++)
{
xCoor = coor.Next(0, 700);
yCoor = coor.Next(0, 730);
if (!randomListxCoor.Contains(xCoor))
{
randomListxCoor.Add(xCoor);
}
if (!randomListyCoor.Contains(xCoor))
{
randomListyCoor.Add(yCoor);
}
randomTimeSetting = setTimeRandom.Next(1, 10);
//Draw the line from main Node to the other Nodes
Pen linePen = new Pen(Color.DarkMagenta, 2);
drawLine.DrawLine(linePen, 350, 360, xCoor, yCoor);
drawLine = this.panel1.CreateGraphics();
graphDraw.FillEllipse(getNodesDrawn, xCoor - 5, yCoor - 5, 15, 12);
//Add the values t the Dictionaries and the List.
waytosave.Add(x, randomTimeSetting);
}
}
private void btnRunTIme_Click(object sender, EventArgs e)
{
this.QuantumTime = (int)this.numQuanrum.Value;
this.ComputeTotalNodeTime();
this.timerRoundRobin.Enabled = true;
}
private void timerRoundRobin_Tick(object sender, EventArgs e)
{
this.NodeIndex = this.GetNextNodeToProcess();
if (this.NodeIndex >= 0)
{
this.waytosave[this.NodeIndex] -= this.QuantumTime;
here at this point it getting crashed. I tried to fixed the number of iteration but if i change the number of iterations it will not go through all the values in the dictionary.
if (this.waytosave[this.NodeIndex] < 0)
{
this.waytosave[this.NodeIndex] = 0;
}
this.NodeName = this.NodeIndex.ToString();
this.TimeToProcess = this.waytosave[this.NodeIndex];
this.txtOutput.Text += "\r\r\n" + " Time Remaining: "
+ this.TimeToProcess
+ "Router name: "
+ this.NodeName;
}
else
{
this.timerRoundRobin.Enabled = false;
this.txtOutput.Text += "\r\r\n" + " Ends x " + TotalRouterTime.ToString();
return;
}
}
private int GetNextNodeToProcess()
{
int NextNodeIndex = -1;
if (NextNodeToProcess >= this.waytosave.Count)
{ NextNodeToProcess = 0; }
for (int i = NextNodeToProcess; i < this.waytosave.Count; i++)
{
if (this.waytosave[i] > 0)
{
NextNodeIndex = i;
break;
}
}
NextNodeToProcess++;
return NextNodeIndex;
}
private void ComputeTotalNodeTime()
{
this.TotalRouterTime = 0;
foreach (KeyValuePair<int, int> item in this.waytosave)
{
this.TotalRouterTime += item.Value;
this.txtOutput.Text += "\r\r\n" + " Time Remaining: "
+ item.Value
+ "Router name: "
+ item.Key;
}
}
I am trying to fix this value from days but i have no success. the problem that in cannot read the first value from the dictionary. How can I solve this problem. Can you please give me some Hence.

How to add checkboxlist selected items to string array?

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();

Runtime textbox creation creates issue

This code works fine for first two times,i.e ,when i click on "Add more solution" it creates a new row and controls respectively but when i click on "Add more solution" for the third time and "add step" button respective to that,,it creates problem.
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < TotalNumberAdded; i++)
{
AddControls((i + 1), plcSolution);
}
for (int i = 0; i < TotalNumberSolAdded; i++)
{
AddMoreControls((i + 1), plcAddMoreSolution, 1);
Button b = (Button)plcAddMoreSolution.FindControl("btn" + (i+1));
for (int j = 0; j < TotalNumberSolStepAdded; j++)
{
AddMoreStepControls((j + 1), plcAddMoreSolution);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
TotalNumberAdded++;
AddControls(TotalNumberAdded, plcSolution);
}
private void AddControls(int controlNumber, PlaceHolder plc)
{
TextBox txtBoxSolution = new TextBox();
Label lblSolution = new Label();
txtBoxSolution.ID = "txtBoxSolution" + controlNumber;
txtBoxSolution.TextMode = TextBoxMode.MultiLine;
txtBoxSolution.Width = 470;
txtBoxSolution.Height = 50;
lblSolution.ID = "lblSolution" + controlNumber;
lblSolution.Text = "Step " + (controlNumber + 1) + ": ";
lblSolution.Width = 200;
plc.Controls.Add(lblSolution);
plc.Controls.Add(txtBoxSolution);
}
protected int TotalNumberAdded
{
get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
set { ViewState["TotalNumberAdded"] = value; }
}
protected void btnAlternate_Click(object sender, EventArgs e)
{
lblSol.Text = "Solution 1";
string str = (string)ViewState["btnId"];
if (str != null)
{
btn = (Button)plcAddMoreSolution.FindControl(str);
btn.Visible = false;
}
btnAdd.Visible = false;
TotalNumberSolAdded++;
AddMoreControls(TotalNumberSolAdded, plcAddMoreSolution,1);
}
protected int TotalNumberSolAdded
{
get { return (int)(ViewState["TotalNumberSolAdded"] ?? 0); }
set { ViewState["TotalNumberSolAdded"] = value; }
}
private void AddMoreControls(int controlNumber, PlaceHolder plc,int n)
{
TextBox txtBoxMoreSolution = new TextBox();
Label lblMoreSolution = new Label();
btn = new Button();
btn.Text = "add step";
btn.ID = "btn" + controlNumber;
btn.Click += new EventHandler(btn_Click);
ViewState["btnId"] = btn.ID;
Label lbl = new Label();
lbl.Text = "soltuion" + (controlNumber + 1);
lbl.ID = "moreSolution" + (controlNumber + 1);
lbl.Font.Size = 20;
lbl.Font.Underline = true;
txtBoxMoreSolution.ID = "txtBoxMoreSolution" + controlNumber;
txtBoxMoreSolution.TextMode = TextBoxMode.MultiLine;
txtBoxMoreSolution.Width = 470;
txtBoxMoreSolution.Height = 50;
lblMoreSolution.ID = "lblMoreSolution" + controlNumber;
lblMoreSolution.Text = "Step " + n + ": ";
lblMoreSolution.Width = 200;
plc.Controls.Add(lbl);
plc.Controls.Add(lblMoreSolution);
plc.Controls.Add(txtBoxMoreSolution);
plc.Controls.Add(btn);
}
private void btn_Click(object sender, EventArgs e)
{
TotalNumberSolStepAdded++;
AddMoreStepControls(TotalNumberSolStepAdded, plcAddMoreSolution);
}
protected int TotalNumberSolStepAdded
{
get { return (int)(ViewState["TotalNumberSolStepAdded"] ?? 0); }
set { ViewState["TotalNumberSolStepAdded"] = value; }
}
private void AddMoreStepControls(int controlNumber, PlaceHolder plc)
{
TextBox txtBoxMoreStepSolution = new TextBox();
Label lblMoreStepSolution = new Label();
txtBoxMoreStepSolution.ID = "txtBoxMoreStepSolution" + controlNumber;
txtBoxMoreStepSolution.TextMode = TextBoxMode.MultiLine;
txtBoxMoreStepSolution.Width = 470;
txtBoxMoreStepSolution.Height = 50;
lblMoreStepSolution.ID = "lblMoreStepSolution" + controlNumber;
lblMoreStepSolution.Text = "Step " + (controlNumber +1) + ": ";
lblMoreStepSolution.Width = 200;
plc.Controls.Add(lblMoreStepSolution);
plc.Controls.Add(txtBoxMoreStepSolution);
}
this code will help you.. it works fine...
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < TotalNumberAdded; i++)
{
AddControls(i + 1);
}
for (int i = 0; i < TotalNumberSolAdded; i++)
{
AddMoreControls((i + 1), 1);
DataTable dt = (DataTable)ViewState["t"];
if (dt != null)
{
if ((TotalNumberSolAdded - dt.Rows.Count == 1) && (counter1 == dt.Rows.Count))
{
break;
}
if (i != 0)
{
for (int k = 0; k <= i; k++)
{
int a1 = int.Parse(dt.Rows[k][0].ToString());
b = a1 + b;
}
start = b - int.Parse(dt.Rows[i][0].ToString());
}
else
{
b = int.Parse(dt.Rows[i][0].ToString());
start = 0;
}
for (int j = start; j < b; j++)
{
counter++;
AddMoreStepControls((j + 1), counter);
}
b = 0;
counter = 0;
counter1++;
}
}
}
private void AddControls(int controlNumber)
{
TextBox txtBoxSolution = new TextBox();
Label lblSolution = new Label();
txtBoxSolution.ID = "txtBoxSolution" + controlNumber;
txtBoxSolution.TextMode = TextBoxMode.MultiLine;
txtBoxSolution.Width = 470;
txtBoxSolution.Height = 50;
lblSolution.ID = "lblSolution" + controlNumber;
lblSolution.Text = "Step " + (controlNumber + 1) + ": ";
lblSolution.Width = 200;
plcSolution.Controls.Add(lblSolution);
plcSolution.Controls.Add(txtBoxSolution);
}
protected int TotalNumberAdded
{
get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
set { ViewState["TotalNumberAdded"] = value; }
}
protected void btnAlternate_Click(object sender, EventArgs e)
{
Number = 0;
lblSol.Text = "Solution 1";
string str = (string)ViewState["btnId"];
if (str != null)
{
btn = (Button)plcAddMoreSolution.FindControl(str);
btn.Visible = false;
}
btnAdd.Visible = false;
TotalNumberSolAdded++;
AddMoreControls(TotalNumberSolAdded, 1);
}
protected int TotalNumberSolAdded
{
get { return (int)(ViewState["TotalNumberSolAdded"] ?? 0); }
set { ViewState["TotalNumberSolAdded"] = value; }
}
private void AddMoreControls(int controlNumber, int n)
{
TextBox txtBoxMoreSolution = new TextBox();
Label lblMoreSolution = new Label();
btn = new Button();
btn.Text = "add step";
btn.ID = "btn" + controlNumber;
btn.Click += new EventHandler(btn_Click);
ViewState["btnId"] = btn.ID;
Label lbl = new Label();
lbl.Text = "Soltuion" + (controlNumber + 1);
lbl.ID = "moreSolution" + (controlNumber + 1);
lbl.Font.Size = 20;
lbl.Font.Underline = true;
lbl.Font.Bold = true;
txtBoxMoreSolution.ID = "txtBoxMoreSolution" + controlNumber;
txtBoxMoreSolution.TextMode = TextBoxMode.MultiLine;
txtBoxMoreSolution.Width = 470;
txtBoxMoreSolution.Height = 50;
lblMoreSolution.ID = "lblMoreSolution" + controlNumber;
lblMoreSolution.Text = "Step " + n + ": ";
lblMoreSolution.Width = 200;
plcAddMoreSolution.Controls.Add(lbl);
plcAddMoreSolution.Controls.Add(lblMoreSolution);
plcAddMoreSolution.Controls.Add(txtBoxMoreSolution);
plcAddMoreSolution.Controls.Add(btn);
}
private void btn_Click(object sender, EventArgs e)
{
TotalNumberSolStepAdded++;
Number++;
string str = (string)ViewState["btnId"];
if (str != null)
{
string resultString = Regex.Match(str, #"\d+").Value;
a = int.Parse(resultString);
table = (DataTable)ViewState["t"];
if (table == null)
{
DataTable table1 = new DataTable();
table1.Columns.Add("count", typeof(int));
dr = table1.NewRow();
table1.Rows.Add(dr);
table1.Rows[a - 1]["count"] = Number;
table1.AcceptChanges();
ViewState["t"] = table1;
}
else
{
if (a != table.Rows.Count)
{
dr = table.NewRow();
table.Rows.Add(dr);
}
table.Rows[a - 1]["count"] = Number;
table.AcceptChanges();
ViewState["t"] = table;
}
}
AddMoreStepControls(TotalNumberSolStepAdded, Number);
}
protected int TotalNumberSolStepAdded
{
get { return (int)(ViewState["TotalNumberSolStepAdded"] ?? 0); }
set { ViewState["TotalNumberSolStepAdded"] = value; }
}
protected int Number
{
get { return (int)(ViewState["Number"] ?? 0); }
set { ViewState["Number"] = value; }
}
private void AddMoreStepControls(int controlNumber, int counter)
{
TextBox txtBoxMoreStepSolution = new TextBox();
Label lblMoreStepSolution = new Label();
txtBoxMoreStepSolution.ID = "txtBoxMoreStepSolution" + controlNumber;
txtBoxMoreStepSolution.TextMode = TextBoxMode.MultiLine;
txtBoxMoreStepSolution.Width = 470;
txtBoxMoreStepSolution.Height = 50;
lblMoreStepSolution.ID = "lblMoreStepSolution" + controlNumber;
lblMoreStepSolution.Text = "Step " + (counter + 1) + ": ";
lblMoreStepSolution.Width = 200;
plcAddMoreSolution.Controls.Add(lblMoreStepSolution);
plcAddMoreSolution.Controls.Add(txtBoxMoreStepSolution);
}

How can i make a task for each item in the listBox if i select more then one item?

First this is the listBox selected index changed event:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
label4.Text = listBox1.SelectedItem.ToString();
string startTag = "Url: ";
string endTag = " ---";
int startTagWidth = startTag.Length;
int endTagWidth = endTag.Length;
int index = 0;
index = label4.Text.IndexOf(startTag, index);
int start = index + startTagWidth;
index = label4.Text.IndexOf(endTag, start + 1);
string g = label4.Text.Substring(start, index - start);
label4.Text = g;
mainUrl = g;
}
}
Solved it by adding this method:
private string GetUrl(object obj)
{
string startTag = "Url: ";
string endTag = " ---";
int startTagWidth = startTag.Length;
int endTagWidth = endTag.Length;
int index = 0;
index = obj.ToString().IndexOf(startTag, index);
int start = index + startTagWidth;
index = obj.ToString().IndexOf(endTag, start + 1);
string g = obj.ToString().Substring(start, index - start);
mainUrl = g;
return mainUrl;
}
And using it in the DoWork event like this:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
object input = e.Argument;
string f = GetUrl(input);
this.Invoke(new MethodInvoker(delegate { label2.Text = "Website To Crawl: "; }));
this.Invoke(new MethodInvoker(delegate { label4.Text = f; }));
if (offlineOnline == true)
{
offlinecrawling(f, levelsToCrawl, e);
}
else
{
webCrawler(f, levelsToCrawl, e);
}
}

Categories

Resources