How to show address bar in WebBrowser control in a Windows Form?
I could be mistaken but I don't believe the WebBrowserControl includes the address bar, toolbar, etc. I believe you'll have to create your own address bar. You could use the Navigated or Navigating events to determine when the URL is changing and update the text box.
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
webBrowser1.Navigate(textBox1.Text);
}
}
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
if (textBox1.Text != e.Url.ToString())
{
textBox1.Text = e.Url.ToString();
}
}
Edit: My form has a TextBox named textBox1, a Button named button1 and a WebBrowserControl named webBrowser1
You could make a textbox and then fill it with the site property i think
Drag and drop a text box into your form.
Use the URL.ToString method to set the textbox .text value to that url string:
Dim strURL As String
strURL = ""
If Me.TextBox1.Text.Length = 0 Then
Me.TextBox1.Focus()
Me.TextBox1.BackColor = Color.Red
Else
If InStr(Me.TextBox1.Text, "http://") = 0 Then
strURL = "http://" & Me.TextBox1.Text.ToString()
Else
strURL = Me.TextBox1.Text.ToString()
End If
Me.WebBrowser1.Navigate(New System.Uri(strURL))
Me.TextBox1.Text = Me.WebBrowser1.Url.ToString()
End If
Here's C#:
string strURL = null;
strURL = "";
if (this.TextBox1.Text.Length == 0) {
this.TextBox1.Focus();
this.TextBox1.BackColor = Color.Red;
}
else {
if (Strings.InStr(this.TextBox1.Text, "http://") == 0) {
strURL = "http://" + this.TextBox1.Text.ToString();
}
else {
strURL = this.TextBox1.Text.ToString();
}
this.WebBrowser1.Navigate(new System.Uri(strURL));
this.TextBox1.Text = this.WebBrowser1.Url.ToString();
}
Related
How can I dynamically change the contents of what will be pasted in the TextBox.
Here is how I subscribe to the event:
DataObject.AddPastingHandler (uiTextBox, TextBoxPaste);
Here is how I define the event handler:
private void TextBoxPaste (object sender, DataObjectPastingEventArgs args)
{
string clipboard = args.DataObject.GetData (typeof (string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex (#"\D");
string result = nonNumeric.Replace (clipboard, String.Empty);
// I can't just do "args.DataObject.SetData (result)" here.
}
You cannot call args.DataObject.SetData("some data") since the DataObject is frozen. What you can do is replace the DataObject altogether:
private void TextBoxPaste(object sender, DataObjectPastingEventArgs e) {
string text = (String)e.DataObject.GetData(typeof(String));
DataObject d = new DataObject();
d.SetData(DataFormats.Text, text.Replace(Environment.NewLine, " "));
e.DataObject = d;
}
I can think of two ways, none of which are very attractive :) And both ways include canceling the paste command.
The first way would be to cancel the paste command and then calculate what the text would look like after the paste if result was pasted instead.
private void TextBoxPaste(object sender, DataObjectPastingEventArgs args)
{
string clipboard = args.DataObject.GetData(typeof(string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex(#"\D");
string result = nonNumeric.Replace(clipboard, String.Empty);
int start = uiTextBox.SelectionStart;
int length = uiTextBox.SelectionLength;
int caret = uiTextBox.CaretIndex;
string text = uiTextBox.Text.Substring(0, start);
text += uiTextBox.Text.Substring(start + length);
string newText = text.Substring(0, uiTextBox.CaretIndex) + result;
newText += text.Substring(caret);
uiTextBox.Text = newText;
uiTextBox.CaretIndex = caret + result.Length;
args.CancelCommand();
}
The other way would be to cancel the paste command, change the text in the Clipboard and then re-execute paste. This would also require you to differ between the real paste command and the manually invoked paste command. Something like this
bool m_modifiedPaste = false;
private void TextBoxPaste(object sender, DataObjectPastingEventArgs args)
{
if (m_modifiedPaste == false)
{
m_modifiedPaste = true;
string clipboard = args.DataObject.GetData(typeof(string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex(#"\D");
string result = nonNumeric.Replace(clipboard, String.Empty);
args.CancelCommand();
Clipboard.SetData(DataFormats.Text, result);
ApplicationCommands.Paste.Execute(result, uiTextBox);
}
else
{
m_modifiedPaste = false;
}
}
I use VB.net quite a bit, I've tested this C# bit, I used a converter because I'm lame :)
string oClipboard;
private void TextBox1_GotFocus(object sender, System.EventArgs e)
{
oClipboard = Clipboard.GetText();
Clipboard.SetText("foo");
}
private void TextBox1_LostFocus(object sender, System.EventArgs e)
{
Clipboard.SetText(oClipboard);
}
I set the clipboard to the new text when the control gets focus. It stores the old value. Later, when the control loses focus, the clipboard is set back to the old value.
Just some modifications of #Fredrik's code, since I've been trying out both of his methods.
First one is just a shortened version
private void TextBox_Pasting(object sender, DataObjectPastingEventArgs e)
{
string clipboard = e.DataObject.GetData(typeof(string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex (#"\D");
string result = nonNumeric.Replace(clipboard, string.Empty);
int caret = CaretIndex;
Text = Text.Substring(0, SelectionStart) + result +
Text.Substring(SelectionStart + SelectionLength);
CaretIndex = caret + result.Length;
e.CancelCommand();
}
and the other one is updated with keeping the clipboard content
private string oldClipboardContent { get; set; } = "";
private bool pasteModified { get; set; } = false;
private void TextBox_Pasting(object sender, DataObjectPastingEventArgs e)
{
if (pasteModified)
{
pasteModified = false;
}
else
{
pasteModified = true;
string text = (string)e.DataObject.GetData(typeof(string));
oldClipboardContent = text;
Regex nonNumeric = new System.Text.RegularExpressions.Regex (#"\D");
text = nonNumeric.Replace(text, string.Empty);
e.CancelCommand();
Clipboard.SetData(DataFormats.Text, text);
ApplicationCommands.Paste.Execute(text, this);
Clipboard.SetData(DataFormats.Text, OldClipboardContent);
oldClipboardContent = "";
}
}
I was using those inside my custom TextBox control, that is why I could access TextBox properties without writing the name first.
how can i update image in listview in gridview formate using folder path in asp.net in c#?
protected void UpdateButton_Click(object sender, EventArgs e)
{
TextBox ApplicantIdTextBox = (TextBox)RadListView8.FindControl("ApplicantIdTextBox");
FileUpload photoTextBox = (FileUpload)RadListView8.FindControl("photoTextBox");
string fileName1 = Path.GetExtension(ApplicantIdTextBox + photoTextBox.FileName);
string fileSavePath = Server.MapPath("ImageStorage/" + fileName1);
tblPersonalInfo pi = new tblPersonalInfo();
pi.photo = fileName1;
photoTextBox.SaveAs(fileSavePath);
dbcontext.AddTotblPersonalInfoes(pi);
dbcontext.SaveChanges();
}
But it show me error...What can i do?
Server Error in '/HrPayRoll' Application.
Object reference not set to an instance of an object.
I'd rewrite it something like this and then run it in debug mode and see what line the error is on. You were trying to use applicantIdTextBox as a string, although I would have thought that would give a different error:
protected void UpdateButton_Click(object sender, EventArgs e)
{
TextBox applicantIdTextBox = RadListView8.FindControl("ApplicantIdTextBox") as TextBox;
FileUpload photoTextBox = RadListView8.FindControl("photoTextBox") as FileUpload;
if ((applicantIdTextBox != null) && (photoTextBox != null))
{
string fileName = Path.GetExtension(applicantIdTextBox.Text + photoTextBox.FileName);
string fileSavePath = Server.MapPath("ImageStorage/" + fileName);
tblPersonalInfo personalInfo = new tblPersonalInfo();
personalInfo.photo = fileName;
photoTextBox.SaveAs(fileSavePath);
dbcontext.AddTotblPersonalInfoes(personalInfo);
dbcontext.SaveChanges();
}
}
I got a WebBrowser Control in a Windows Form and i want to use the middle mouse button click to add a new tab to my Browser. The only problem is that everytime i use the middle mouse button, the arrows to move the page appear.
So how can i disable this move/drag command only for the clicks on my links?
try this:
There are two different parts to this solution. The first is pretty easy - just set an event handler for the MouseDown event of your browser control:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.Document != null)
{
webBrowser1.Document.MouseDown += Document_MouseDown;
}
}
private void Document_MouseDown(object sender, HtmlElementEventArgs e)
{
if (e.MouseButtonsPressed == System.Windows.Forms.MouseButtons.Middle)
{
e.ReturnValue = false;
// Your custom code
}
}
but there were also some javascript-heavy websites on which this solution did not work. For those, I found another solution involving injecting javascript into the document which will prevent the middle-click:
HtmlElement head = browser.Document.GetElementsByTagName("head")[0];
HtmlElement mscript = browser.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)mscript.DomElement;
element.text = "function handleMouseEvent(e) { "
+ "var evt = (e==null ? event:e); "
+ "if ( e.which == 2 ) e.preventDefault(); "
+ "return true; } "
+ "document.onmousedown = handleMouseEvent; "
+ "document.onmouseup = handleMouseEvent; "
+ "document.onclick = handleMouseEvent; ";
head.AppendChild(mscript);
UPDATE
The JavaScript injection methodology can be improved by following the suggested way to do it using managed code only:
stackoverflow.com/a/6222430/1248295
This is an alternative example implementation of the javascript injection, wrote in VB.NET:
Private ReadOnly handleMouseEventJs As String =
"
function HandleMouseEvent(e) {
var evt = (e==null ? event:e);
if (e.which == 2) e.preventDefault();
return true;
}
document.onmousedown = HandleMouseEvent;
// These events below seems are not necessary to handle for this purpose.
// document.onmouseup = HandleMouseEvent;
// document.onclick = HandleMouseEvent;
"
Private Sub WebBrowser1_Navigated(sender As Object, e As WebBrowserNavigatedEventArgs) _
Handles WebBrowser1.Navigated
Dim wb As WebBrowser = DirectCast(sender, WebBrowser)
Dim doc As HtmlDocument = wb.Document
Dim head As HtmlElement = doc.GetElementsByTagName("head")(0)
Dim js As HtmlElement = doc.CreateElement("script")
js.SetAttribute("text", handleMouseEventJs)
head.AppendChild(js)
' This method call seems not necessary at all, it works fine without invocking it.
' doc.InvokeScript("HandleMouseEvent", Nothing)
End Sub
UPDATE 2
Inject this code instead:
document.body.onmousedown = function(e) { if (e.button === 1) return false; }
https://stackoverflow.com/a/30423534/1248295
The move icon displayed upon middle mouse click is under control of your mouse settings. But you can detect middle mouse click on your WebBrowser control.
Register DocumentCompleted event for your WebBrowser control and use the following code:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.MouseDown += Document_MouseDown;
}
void Document_MouseDown(object sender, HtmlElementEventArgs e)
{
if (e.MouseButtonsPressed == System.Windows.Forms.MouseButtons.Middle)
{
// code to add tab or do sth else
}
}
I have a bunch of different panels that are custom server controls, which inherits CompositeControl. The panels are rendered by using the CreateChildControls(). I have a page where I am displaying them based off of a users selection from a comboBox. When you change the selection it does a callback for a callback panel (DevExpress control), which is like an update panel. Based on the selection it adds the panel to the callback panel. But it seems that if you do this from a callback the server controls life cycle doesn't get started, so it never calls CreateChildControls() or OnPreRender(). Any ideas on how to make this work? EnsureChildControls() doesn't seem to helping.
Here is some example code of one of the panels
protected override void CreateChildControls()
{
base.CreateChildControls();
String strParentID = this.ClientInstanceName.Length > 0 ? this.ClientInstanceName : this.ClientID;
String strID = "";//Used as ID and ClientInstanceName.
String strKey = "";//Used in the ID and as the ControlInfo key.
if (!DesignMode)
{
//*******************************************************************
ASPxLabel lblUnit = new ASPxLabel();
lblUnit.Text = "Select Unit(s)";
callbackEdit.Controls.Add(lblUnit);
//*******************************************************************
strKey = "btnUnitSelector";
strID = strParentID + "_" + strKey;
btnUnitSelector = new ASPxButton()
{
ID = strID,
ClientInstanceName = strID,
CssFilePath = this.CssFilePath,
CssPostfix = this.CssPostfix,
SpriteCssFilePath = this.SpriteCssFilePath,
};
btnUnitSelector.Width = Unit.Pixel(180);
btnUnitSelector.AutoPostBack = false;
this.listControlInfo.Add(new ControlInfo(strKey, btnUnitSelector.ClientInstanceName, btnUnitSelector.ClientID));
callbackEdit.Controls.Add(btnUnitSelector);
//*******************************************************************
strKey = "unitPopup";
strID = strParentID + "_" + strKey;
unitPopup = new UnitPopup.UnitPopup();
unitPopup.ID = strID;
unitPopup.ClientInstanceName = strID;
unitPopup.btnOk_AutoPostBack = false;
unitPopup.ShowOnlyUnits = false;
unitPopup.DataSource = GlobalProperties.Company_UnitsAndAreas;
unitPopup.DataBind();
btnUnitSelector.ClientSideEvents.Click = "function (s, e) { " + unitPopup.ClientInstanceName + ".Show(); }";
unitPopup.ClientSideEvents.MemberSet = "function (s, e) { " + btnUnitSelector.ClientInstanceName + ".SetText(" + unitPopup.ClientInstanceName + ".selectedMemberName); }";
Controls.Add(unitPopup);
//*******************************************************************
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ClientScriptManager cs = this.Page.ClientScript;
//Register an embedded JavaScript file. The JavaScript file needs to have a build action of "Embedded Resource".
String resourceName = "QSR_ServerControls.Controls.DashboardControls.SalesChart.SalesChart.js";
cs.RegisterClientScriptResource(typeof(SalesChart), resourceName);
}
Here is some sample code of adding a panel
private void PopulatePanel(string panel)
{
tblDescCell.Controls.Add(new LiteralControl(GetPanels().Select("[PanelName] = '" + panel + "'")[0]["PanelDescription"].ToString()));
if (panel == "SalesChart")
tblTopLeftCell.Controls.Add(new SalesChart.SalesChart());
}
void callbackMain_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
{
PopulatePanel(e.Parameter);
}
During callback requests PreRender and Render methods are not executed (this is the main difference from PostBack request). But CreateChildControls should be executed. Please provide more information or code example.
Rather new to C# so please forgive me if i am missing something simple or am trying to just do this the wrong way.
I am creating another form to compliment my main form and it needs to pull some of the information from Main form on button click of Second form. The information on the Main for is stored in checkboxes and textboxes.
I have the textboxes working fine but cannot figure out how to pull the checkboxes tag data over along with the formatting. Main Form is working fine as is except I cannot figure out how to bring the checkbox data over as well.
This is the code i currently use to display the checkbox TAG data on my main form.
//Statements to write checkboxes to stringbuilder
string checkBoxesLine = "\u2022 LIGHTS ";
foreach (Control control in pnlCheckBoxes.Controls)
{
if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
if (checkBox.Checked && checkBox.Tag is string)
{
string checkBoxId = (string)checkBox.Tag;
checkBoxesLine += string.Format("{0}, ", checkBoxId);
}
}
}
This is the button i am using to open the new form and move the checkbox tag data and textbox.text data to the new form.
private void code_blue_link_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
trouble_shooting = tshooting_text.Text;
services_offered = services_offered_text.Text;
other_notes = other_notes_text.Text;
cust_modem = cust_modem_text.Text;
//Opens CODE BLUE form and pushes text to it.
code_blue_form CBForm = new code_blue_form();
CBForm.cust_name_cb = cust_name_text.Text;
CBForm.cust_cbr_cb = cust_callback_text.Text;
CBForm.cust_wtn_cb = cust_btn_text.Text;
CBForm.cust_notes_cb = cust_modem + "\r\n" + trouble_shooting + "\r\n" + services_offered + "\r\n" + other_notes;
CBForm.Show();
}
Here is my code for the Second form and how i am getting the information to populate textboxes on that form.
public partial class code_blue_form : Form
{
public string cust_name_cb;
public string cust_wtn_cb;
public string cust_cbr_cb;
public string cust_notes_cb;
public string cust_modem_cb;
public code_blue_form()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
cb_name_text.Text = cust_name_cb;
cb_wtn_text.Text = cust_wtn_cb;
cb_cbr_text.Text = cust_cbr_cb;
cb_notes_text.Text = cust_notes_cb;
}
}
}
Please forgive the long post! Any ideas/direction on this would be greatly appreciated. Thanks!
I am not going to answer straight away using ur code. I find code smell. If I were you I would do this (but then if you are adamant about going with the same design, then you can tweak my code accordingly, no big deal, the bottom line is you get the idea how to do):
void code_blue_link_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var checkBoxIds = GetCheckBoxIds();
cust_modem = cust_modem_text.Text;
trouble_shooting = tshooting_text.Text;
services_offered = services_offered_text.Text;
other_notes = other_notes_text.Text;
//take off underscore convetion and replace with camelCase convention.
CodeBlueForm cbForm = new CodeBlueForm(checkBoxIds, cust_name_text.Text,
cust_callback_text.Text,
cust_btn_text.Text,
cust_modem + "\r\n" +
trouble_shooting + "\r\n" +
services_offered + "\r\n" +
other_notes);
cbForm.Show();
}
private List<int> GetCheckBoxIds()//even better naming required like GetFruitIds()
{ //(whatever the id is of) or even better Tag
//checkBoxes with the Fruit object iself and not ids.
List<int> checkBoxIds = new List<int>(); //So you can call GetFruits();
foreach (Control control in pnlCheckBoxes.Controls)
{
if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
if (checkBox.Checked && checkBox.Tag is int) //tag them as ints.
checkBoxIds.Add((int)checkBox.Tag); //I hope ids are integers.
}
}
return checkBoxIds;
}
public partial class CodeBlueForm : Form
{
List<int> checkBoxIds = new List<int>():
string cust_cbr_cb; //should be private.
string cust_name_cb;
string cust_wtn_cb;
string cust_notes_cb;
string cust_modem_cb;
public CodeBlueForm(List<int> ids, string cust_name_cb, string cust_wtn_cb,
string cust_notes_cb, string cust_modem_cb)
{
InitializeComponent();
this.checkBoxIds = ids;
this.cust_name_cb = cust_name_cb;
this.cust_wtn_cb = cust_wtn_cb;
this.cust_notes_cb = cust_notes_cb;
this.cust_modem_cb = cust_modem_cb;
}
private void button1_Click(object sender, EventArgs e)
{
cb_name_text.Text = cust_name_cb;
cb_wtn_text.Text = cust_wtn_cb;
cb_cbr_text.Text = cust_cbr_cb;
cb_notes_text.Text = cust_notes_cb;
string checkBoxesLine = "\u2022 LIGHTS ";
// if you dont require a lot of string formatting, then just:
checkBoxesLine += string.Join(", ", checkBoxIds);
// or go with your classical:
//foreach (int id in checkBoxIds)
// checkBoxesLine += string.Format("{0}, ", checkBoxIds);
//and do what u want with checkboxline here.
}
}