How to find a specific word in WebBrowser control C# - c#

I use this code to find CDE in the HTML. How can I find my request data in tag page with different ids, for example if page id is 1 my result is CDE and when page id is 2 my result is IJK, How can I set id-value in my search?
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText = #"<html><head><title></title></head><body>"
+ "<page id=\"1\">"
+ #"ABCDEF</page>"
+ "<page id=\"2\">"
+ #"GHIJKLMN</page></body></html>";
webBrowser1.DocumentCompleted += HtmlEditorDocumentCompleted;
}
void HtmlEditorDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var document = (IHTMLDocument2)((WebBrowser)sender).Document.DomDocument;
if (document != null)
{
IHTMLBodyElement bodyElement = document.body as IHTMLBodyElement;
if (bodyElement != null)
{
IHTMLTxtRange trg = bodyElement.createTextRange();
if (trg != null)
{
trg.move("character", 2);
trg.moveEnd("character", 3);
trg.select();
trg.pasteHTML("<font color=#FF0000><strike>" + trg.text + "</strike></font>");
}
}
}
}

I have no idea, what do you need to do, you may have to rephrase the question...
But you might want to have a look at webBrowser1.Document.GetElementDyId() to get a specific element by "id"

Related

Filtering datagridview with multiple combobox

I am trying to make a simple product code search using a datagridview.
I am able to filter the database but not able to get all the functions I want
I currently have it set as
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
productsBindingSource.Filter = string.Format("Type = '{0}'",
comboBox1.SelectedItem.ToString());
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
productsBindingSource.Filter = string.Format("Type = '{0}' AND Fitting = '{1}'",
comboBox1.SelectedItem.ToString(),
comboBox2.SelectedItem.ToString());
}
This code works but after the selections are made and I change comboBox1 the data resets and doesn't keep the selection of comboBox2.
I understand in my current code that this would not happen but I cannot figure out how to get this to happen.
I would also like to add a text box in the future and have it narrow the filter even more.
You should approach this a bit more generically like so
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FilterProducts();
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
FilterProducts();
}
// Create a function to handle filters
private void FilterProducts()
{
string filter = "";
if (comboBox1.SelectedItem != null)
{
filter += string.Format("Type = '{0}'", comboBox1.SelectedItem.ToString());
}
if (comboBox2.SelectedItem != null)
{
if (filter.length > 0) filter += "AND "
filter += string.Format("Fitting = '{0}'", comboBox2.SelectedItem.ToString());
}
// Add another like above for your future textbox
// if (!string.IsNullOrEmpty(textBox1.Text))
// {
// if (filter.length > 0) filter += "AND "
// filter += string.Format("OtherColumn = '{0}'", textBox1.Text);
// }
productsBindingSource.Filter = filter;
}
The code could be further refactored for even better DRY standards but this should at least get you started.

How to remove href from gridview cells?

I have a button click that will generate the text from gridview cells. But I want to remove the href tag when it get the text. How can I do it? Trying to do .atrributes.remove("href) but can't get it to save to a arraylist
protected void Button_Example_Click(object sender, EventArgs e)
{
foreach (GridViewRow s in GridView_Staff.Rows)
{
CheckBox CheckBox_Staff = (s.FindControl("CheckBox_Staff") as CheckBox);
if (CheckBox_Staff.Checked == true)
{
s.Cells[2].Attributes.Remove("href");
Response.Write("<script>alert('" + s.Cells[2].Text + "');</script>");
}
}
}
s.Cells[2].Text contains:
Example A
It's been a while since I was last using webforms and GridView, but to my eye it looks as though you are calling .Attributes.Remove() on the Cell object itself (.Cells[2]). But I would have thought that the anchor tag was inside the cell?
Would it not be more like this (excuse the pseudo-code):
var Anchor = s.Cells[2].FindControl("TheAnchor") as AnchorTag;
Anchor.Attributes.Remove("href");
Response.Write("<script>alert('" + Anchor.Text + "');</script>");
Or something similar?
You could use a regular expression to remove the href attribute like this:
protected void Button_Example_Click(object sender, EventArgs e)
{
foreach (GridViewRow s in GridView_Staff.Rows)
{
CheckBox CheckBox_Staff = (s.FindControl("CheckBox_Staff") as CheckBox);
if (CheckBox_Staff.Checked == true)
{
string text = s.Cells[2].Text;
string pattern = #"(?<=<[^<>]+)\s+(?:href)\s*=\s*([""']).*?\1";
text = System.Text.RegularExpressions.Regex.Replace(text, pattern, "", RegexOptions.IgnoreCase);
s.Cells[2].Text = text;
Response.Write("<script>alert('" + s.Cells[2].Text + "');</script>");
}
}
}

HttpCookie gets messsed up in hebrew

Let me explain my project first of all.
Its a form with some information that I add in to textboxs and a signature field.
When you click on the signature it redirects you to another page where you sign and then goes back to the form and puts the signature in an image.
Point is when I go to the signature page I put the Form information in to a cookie so I can put them back on when I return from the signature page.
The problem is when it gets to the other page the cookie gets messed up content wise. If I try to write some simple hebrew on the page there is no problem.
This is the code that saves the cookie.
protected void ReCapture(object sender, EventArgs e)
{
string s = "";
foreach (Control c in form1.Controls)
{
if (c.GetType() == typeof(TextBox))
{
s += ((TextBox)c).Text + ":" + ((TextBox)c).ID + ",";
}
if (c.GetType() == typeof(Image))
{
s += ((Image)c).ImageUrl + ":" + ((Image)c).ID + ",";
}
}
Response.Cookies.Remove("Controls");
HttpCookie hc = new HttpCookie("Controls",s.Remove(s.Length - 2));
hc.Expires.AddHours(2);
hc.Path = "/";
Response.Cookies.Add(hc);
Response.Redirect("SignaturePage.aspx?id=" + ((Control)sender).ID);
}
This is the signature page code(practically nothing)
protected void Save(object sender, EventArgs e)
{
Session["TheSignature"] = Request.Form["TheData"];
Response.Redirect("Test.aspx");
}
Why is this happening?

Event handler not working perfectly with C#

I am dynamically creating buttons which each selection of a dropdownlist.
With the following code I am adding an event handler to each button.
button.Click += new System.EventHandler(button_Click);
PlaceHolder1.Controls.Add(button);
private void button_Click(object sender, EventArgs e)
{
//Do something...
Response.Write("hello");
}
But unfortunately it does not fire that event and gives me an error as following
button_Click 'Index.button_Click(object, System.EventArgs)' is a 'method', which is not valid in the given context
How do I handle this?
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, typeof(Page), "Close", "javascript:OpenPopUp1();", true);
if (Session["filter"] == DropDownList1.SelectedValue)
{
}
else
{
if (Session["filter"] == "")
{
Session["filter"] = DropDownList1.SelectedValue + ":";
}
else
{
Session["filter"] = DropDownList1.SelectedValue + ":" + Session["filter"];
}
}
string asd = Session["filter"].ToString();
string[] split = asd.Split(':');
DropDownList1.Items.RemoveAt(DropDownList1.SelectedIndex);
for (int i = 0; i < split.Count(); i++)
{
string filter = split[i].ToString();
Button button = new Button();
button.Text = split[i].ToString();
button.ID = split[i].ToString();
button.Attributes.Add("onclick", "remove(" + split[i].ToString() + ")");
button.Click += new System.EventHandler(button_Click);
PlaceHolder1.Controls.Add(button);
}
}
The above shows the whole code of dropdownselected index.
button.Click += new System.EventHandler(button_Click);
PlaceHolder1.Controls.Add(button);
} // <-- end your current method with a curly brace
// Now start a new method
private void button_Click(object sender, EventArgs e)
{
//do something...
Response.Write("hello");
}
It's hard to say what you're going after, as there are a number of issues going on here. Since your dynamically generated buttons are being created in the SelectedIndexChanged event handler of your dropdown, they are not going to exist, nor are their event bindings, on the next postback. This means they can show up on the page, but clicking them won't do anything.
Secondly, since you are storing the SelectedValue to Session, and then using that value to set the Button IDs, you are going to be creating buttons with duplicate IDs if the user ever comes back to the page. (I noticed you are removing the list item once selected, but it would come back if the user refreshed the page, while the session object would remain populated.)
Last oddity, I wasn't able to find where your particular exception is handling, nor able to reproduce it. Which version of .NET are you programming against? Are you invoking the button click event anywhere from code-behind?
Now, that all said, I'm providing the following fix (or at least improvement):
protected void Page_Init(object sender, EventArgs e)
{
CreateButtons();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, typeof(Page), "Close", "javascript:OpenPopUp1();", true);
if (Session["filter"] == DropDownList1.SelectedValue)
{
}
else
{
if (Session["filter"] == "")
{
Session["filter"] = DropDownList1.SelectedValue + ":";
}
else
{
Session["filter"] = DropDownList1.SelectedValue + ":" + Session["filter"];
}
}
DropDownList1.Items.RemoveAt(DropDownList1.SelectedIndex);
CreateButtons();
}
private void CreateButtons()
{
PlaceHolder1.Controls.Clear();
if (Session["filter"] != null)
{
string asd = Session["filter"].ToString();
string[] split = asd.Split(':');
for (int i = 0; i < split.Count(); i++)
{
string filter = split[i].ToString();
Button button = new Button();
button.Text = split[i].ToString();
button.ID = split[i].ToString();
button.Attributes.Add("onclick", "remove(" + split[i].ToString() + ")");
button.Click += new System.EventHandler(button_Click);
PlaceHolder1.Controls.Add(button);
}
}
}
private void button_Click(object sender, EventArgs e)
{
//do something...
Response.Write("hello");
}

Adding data dynamically to a asp literal control inside a grid view

I'm trying to add data to a literal which place inside a gridview. Currently code look like this
protected void GvListingRowDataBound(object sender, GridViewRowEventArgs e)
{
var query = DisplayAllData();
Literal info = (Literal)e.Row.FindControl("ltritemInfo");
if(query != null)
{
foreach (var listing in query)
{
var list = DisplayListById(listing.id);
info.Text = "<h3>" + list.title + "</h3>";
info.Text += "<h4>" + list.description + "</h4>";
}
}
}
This will generate an error
Object reference not set to an instance of an object.
If anyone has an idea about this it will be great help
Thanks
Ensure you're only operating on the data rows, and not the header, footer, separator, pager, etc. The enum for this is DataControlRowtype. This is why your info object/reference is null, as it operates on the header first.
Check that the e.Row.RowType is of type DataRow.
For safety, also check that your info is not null.
protected void GvListingRowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var query = DisplayAllData();
Literal info = (Literal)e.Row.FindControl("ltritemInfo");
if(query != null && info !=null)
{
foreach (var listing in query)
{
var list = DisplayListById(listing.id);
info.Text = string.Format("<h3>{0}</h3><h4>{1}</h4>",
list.title, list.description);
}
}
}
}

Categories