Editing HTML with a WYSIWYG Editor - c#

I have a datagridview with HTML strings. Using a CellDoubleClick event, I am displaying the html string in a WebBrowser control.
In Form1
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex != 0 && e.RowIndex != -1)
{
string s = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
this.f2 = new Form2(s);
f2.ShowDialog();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
In Form2
private IHTMLDocument2 doc;
string reply;
public Form2(string reply)
{
InitializeComponent();
this.reply = reply;
}
private void Form2_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText = reply; <--- string from DataGridView
IHTMLTxtRange range = doc.selection.createRange() as IHTMLTxtRange;
range.pasteHTML(webBrowser1.DocumentText);
range.collapse(false);
range.select();
doc = webBrowser1.Document.DomDocument as IHTMLDocument2;
doc.designMode = "On";
}
Using the above code, I can successfully display the HTML string as a plaintext, however I am unable to edit it. Alternatively, if I use this code:
private IHTMLDocument2 doc;
private void Form2_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText = reply; <--- string from DataGridView
doc = webBrowser1.Document.DomDocument as IHTMLDocument2;
doc.designMode = "On";
IHTMLTxtRange range = doc.selection.createRange() as IHTMLTxtRange;
range.pasteHTML(webBrowser1.DocumentText);
range.collapse(false);
range.select();
}
It will be a blank form, but I will be able to write to it.
I have a feeling it has to do with range.pasteHTML(webBrowser1.DocumentText); being in the Form2_Load method, but I'm unaware of any other method that will allow me to display the HTML string from the DataGridView upon opening Form2.
I want to allow users to be able to edit the HTML string as plaintext (after which it will be converted back to HTML and displayed in the datagridview).

Its possible! You can edit HTML using the default WebBrowser control,
Add a reference to the "Microsoft.mshtml.dll" file, available here.
Assuming your WebBrowser is named "browser", add this code in the Form.Load event
(browser.Document.DomDocument as mshtml.IHTMLDocument2).designMode = "On";
Call the following functions to format the selected text:
browser.document.ExecCommand("Bold", false, null);
browser.document.ExecCommand("Underline", false, null);
browser.document.ExecCommand("Italics", false, null);
browser.document.ExecCommand("StrikeThrough", false, null);
browser.document.ExecCommand("FontName", false, "Times New Roman");
browser.document.ExecCommand("FontName", false, "Arial");
browser.document.ExecCommand("FontName", false, "etc.");
browser.document.ExecCommand("FontSize", false, "1");
browser.document.ExecCommand("FontSize", false, "2");
browser.document.ExecCommand("FontSize", false, "3");
browser.document.ExecCommand("InsertUnorderedList", false, null);
browser.document.ExecCommand("InsertOrderedList", false, null);
browser.document.ExecCommand("Cut", false, null);
browser.document.ExecCommand("Copy", false, null);
browser.document.ExecCommand("Paste", false, null);
browser.document.ExecCommand("CreateLink", true, null);
The WebBrowser control does not allow editing, and is designed to view web pages only. Its actually the Internet Explorer/Trident rendering engine operating behind the scenes that parses the HTML and renders the final page complete with DOM/JS support. No popular browser supports editing of HTML pages, IMO, and neither does IE.

Related

Does WPF have a way of saving radio button content and then sent the save content through a event handler

I was wondering if it possible for WPF to save the radio button content and use the event handler to sent the content to text file. Do I need to do all that in the event handler or i can invoke some class?
public void method(){
string s = "Test1&Test2&Test3&Test4";
string[] s = Spliting.Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries);
List<RadioButton> radioButtonList = new List<RadioButton>();
radioButtonList.Add(radioButton);
radioButtonList.Add(radioButton1);
for (int i = 0; i < radioButtonList.Count; i++)
{
//some code that insert string into the radio button (done)
//when i use streamwriter inside here, it give me this in the text file
//System.Windows.Controls.RadioButton Content IsChecked:False <- this can be turn to true if i put variable.Checked = true
}
private void radioButton_Checked(object sender, RoutedEventArgs e)
{
if (radioButton.IsChecked == true)
{
StreamWriter streamwriters = new StreamWriter ("Sent.txt", false);
streamwriters.Close();
}
else if (radioButton1.IsChecked == true)
{
StreamWriter streamwriters = new StreamWriter("Sent.txt", false);
streamwriters.Close();
}
Or WPF have a method that can automatically save the content into variable. Am I missing something?
I wanted the radio button to check the radio button and sent the content into the text file.
If you just want to save the text displayed with the radio button to a file, then:
private void radioButton1_Checked(object sender, EventArgs e)
{
string radioButtonContent = ((RadioButton)sender).Text;
string savePath = #"C:\sent.txt"; // or wherever
File.WriteAllText(savePath, radioButtonContent);
}

File Download popup overwrites the alert popup

When the user clicks on the "Export to Excel" link, the standard "File download" dialog is presented to the user. See here for an example image.
But before exporting the excel file, I want to display an alert popup. But the Save dialog is obscuring the view of the alert popup.
How can I display the popup without it being obscured?
Here is my code...
dsResult = clsObj.getSearchResults_BL(detObj);
if (OrdDifference != null && OrdDifference.Any())
{
ScriptManager.RegisterClientScriptBlock(this.up, this.GetType(), "export", "alert('.....')", true);
set(dsResult, strName);
}
else
{
set(dsResult, strName);
}
private void set(DataSet ds, string strFileName)
{
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2007;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet sheet = workbook.Worksheets[0];
try
{
sheet.Name = strFileName;
sheet.ImportDataTable(ds.Tables[0], true, 1, 1, -1, -1);
...
workbook.SaveAs(strFileName, ExcelSaveType.SaveAsXLS, HttpContext.Current.Response, ExcelDownloadType.PromptDialog);
}
catch (Exception ex)
{
}
}
Your problem is here:
ScriptManager.RegisterClientScriptBlock(this.up, this.GetType(), "export", "alert('.....')", true);
set(dsResult, strName);
Because the set method in your program is writing to the Response Stream the call to ScriptManager.RegisterClientScriptBlock ends up doing nothing.
You need to do this on two steps:
if (OrdDifference != null && OrdDifference.Any())
{
//Just do this, nothing more.
ScriptManager.RegisterClientScriptBlock(this.up, this.GetType(), "export", "alertUser('Some Message Here')", true);
}
Now define the alertUser function in Javascript:
function alertUser(message)
{
alert(message);
window.location='AccepServiceOrder.aspx?o=Export';
}
Now on Page_Load check for the o parameter in the query string
protected void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString["o"]!=null)
{
dsResult = clsObj.getSearchResults_BL(detObj);
set(dsResult, strName);
}
}

open a fancybox on pageload

The situation is to open a fancy box on the page load,
Please find the below html, and the code behind I am using but with no success.
protected void Page_Load(object sender, EventArgs e)
{
if (SessionController.CurrentMember != null)
{
if (Request.IsAuthenticated)
{
int memberId = SessionController.CurrentMember.MemberID;
bool checkaccepted = CheckAcceptedTermsandConditions(memberId);
if (!checkaccepted)
{
string script = #"<script>$(document).ready(function() {
$(""#onlineCasinoTandC"").fancybox({
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'speedIn' : 600,
'speedOut' : 200,
'overlayShow' : false,
'overlayOpacity': 0.5,
'width' : 800,
'showCloseButton': true,
});
$(""#onlineCasinoTandC"").click();
});</script>";
ClientScript.RegisterStartupScript(this.GetType(), "fancybox", script);
onlineCasinoTandC.HRef = "/Common/EN/TermsandConditions.aspx";
}
}
}
}
Regards
Srividhya
delete the extra comma at the end of this line
'showCloseButton': true
And if u want to trigger, Click event, it should be
$('#foo').trigger('click');
Please find the below solution.
on page load
string script = #"<script type=""text/javascript"">$(document).ready(function() {$(""#termsandConditions"").fancybox({'transitionIn':'elastic','transitionOut':'elastic','speedIn':600,'speedOut':200,'overlayShow':false,'overlayOpacity': 0.5,'width':800,'href':""/Contents/Common/EN/TermandConditions.aspx""}).trigger('click');});</script>";
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsStartupScriptRegistered(cstype, script))
{
cs.RegisterStartupScript(cstype, "fancybox", script);
}
Regards
Vidya

input box in asp.net c#

I need to create a simple input box on my website in C#.
It should pop up, when i call it in the code like that
String input = InputBox("Name the file");
and then I need the use string the users enters later in the code
In a .net application, it is pretty easy to accomplish, but how can i make it work in a web application? I think it should be possible with ajax, but it seems pretty complicated for such a (seemingly) trivial thing.
Is there any kind of library or framework, that I can use for this right away?
thanks in advance
It sounds to me like the behavior you are looking for is to get a popup window with a text box for the user to enter a value and click ok. Is that right?
You're right in saying that it is more complicated with a web app. In a windows app, whenever you run the C# code, whatever happens, happens at that moment. It's pretty straightforward. However, in a web app, all of the C# runs before the page is even rendered in the browser. Therefore, C# in web forms can't really pop up a window.
In order to get a popup, you'll need to do that with JavaScript. The textbox inside the popup should be an <asp:Textbox> control. You can use the Ajax Control Toolkit if youre most comfortable with .NET controls. If youre comforatble with jQuery, you should check out jQuery UI.
I'm assuming you use webforms.
The most simple thing is to make a webform with one input box (<asp:textbox runat="server" id="inputfield" />). Add a button with an onclick event (<asp:button runat="server" id="button" onclick="OnClick" />. In the onclick eventhandler you do something with the value.
protected void OnClick(object sender, EventArgs args){
string input = inputfield.Text;
// do something
}
It should pop up, when i call it in the code like that
And when exactly is this? Keep in mind that there's a fundamental difference between the disconnected nature of web development vs. application development. All of your server-side C# code has already finished executing before the web page renders in the browser. So when are you going to call this code? Also, how are you going to pass the data back to the server? A form post? An AJAX call?
If you want it to "pop up" and to post back with AJAX, I recommend the jQuery UI Dialog as the actual pop-up. Then on its close event you can make the AJAX call to the server to post the data.
If you are looking for a simple solution for a POPUP that will get user input, I recomend checking out JQuery's dialog widget. In particular the modal form, here is a link to some more information: http://jqueryui.com/demos/dialog/#modal-form
ASP.NET has a TextBox control that does just this. All items with runat="server" are accessible through server-side code.
public class InputBox
{
public static DialogResult Show(string title, string promptText, ref string value)
{
return Show(title, promptText, ref value, null);
}
//Fuction
public static DialogResult Show(string title, string promptText, ref string value,
InputBoxValidation validation)
{
Form form = new Form();
Label label = new Label();
TextBox textBox = new TextBox();
Button buttonOk = new Button();
Button buttonCancel = new Button();
form.Text = title;
label.Text = promptText;
textBox.Text = value;
buttonOk.Text = "OK";
buttonCancel.Text = "Cancel";
buttonOk.DialogResult = DialogResult.OK;
buttonCancel.DialogResult = DialogResult.Cancel;
label.SetBounds(9, 20, 372, 13);
textBox.SetBounds(12, 36, 372, 20);
buttonOk.SetBounds(228, 72, 75, 23);
buttonCancel.SetBounds(309, 72, 75, 23);
label.AutoSize = true;
textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
form.ClientSize = new Size(396, 107);
form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });
form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
form.MinimizeBox = false;
form.MaximizeBox = false;
form.AcceptButton = buttonOk;
form.CancelButton = buttonCancel;
if (validation != null)
{
form.FormClosing += delegate(object sender, FormClosingEventArgs e)
{
if (form.DialogResult == DialogResult.OK)
{
string errorText = validation(textBox.Text);
if (e.Cancel = (errorText != ""))
{
MessageBox.Show(form, errorText, "Validation Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
textBox.Focus();
}
}
};
}
DialogResult dialogResult = form.ShowDialog();
value = textBox.Text;
return dialogResult;
}
}
public delegate string InputBoxValidation(string errorMessage);
private void button_updations_Click(object sender, EventArgs e)
{
InputBoxValidation validation = delegate(string val)
{
if (val == "")
return "Value cannot be empty.";
if (!(new Regex(#"^[a-zA-Z0-9_\-\.]+#[a-zA-Z0-9_\-\.]+\.[a-zA-Z]{2,}$")).IsMatch(val))
return "Email address is not valid.";
return "";
};
string value = "";
if (InputBox.Show("Enter your email address", "Email address:", ref value, validation) == DialogResult.OK)
{
if (value == "thazime7#gmail.com")
{
dataGridView1.Visible = true;
button_delete.Visible = true;
button1.Visible = true;
button_show.Visible = true;
label6.Visible = true;
label4.Visible = true;
label5.Visible = true;
textBox_uemail.Visible = true;
textBox_uname.Visible = true;
textBox_upassword.Visible = true;
textBox_delete.Visible = true;
button_deleteTable.Visible = true;
button_updatep.Visible = true;
textBox_updateall.Visible = true;
}
MessageBox.Show(value);
}
else
{
MessageBox.Show("You are not authenticated");
}
}

C# Web browser control is not updating correctly

I'm currently working on an app that technically interacts with an html page that uses dynamic content.
My problem is when I try to append data to the WBC the content isn't updating correctly.
namespace CheckList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
.... code removed ....
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != null)
{
HtmlDocument doc = webBrowser1.Document;
HtmlElement row = doc.CreateElement("tr");
HtmlElement cell1 = doc.CreateElement("td");
HtmlElement cell2 = doc.CreateElement("td");
cell1.InnerHtml = "[X] " + textBox1.Text;
cell2.SetAttribute("class", "solved_2");
cell2.InnerHtml = "Unsolved";
row.AppendChild(cell1);
row.AppendChild(cell2);
doc.GetElementsByTagName("table")[0].AppendChild(row);
//doc.Write(doc.GetElementsByTagName("HTML")[0].OuterHtml);
webBrowser1.Document.Body.InnerHtml = doc.Body.InnerHtml;
}
}
}
}
What currently happens is, I click "add" it should add the html to the page and update and the javascript and what not should still load.
What happens is it adds the content, but the javascript doesn't work after I attempt to reload the content. The CSS stays in tact though, and the javascript isn't working after that point.
JS Source:
var showalert = true;
var file = "file:///C:/Users/Removed/Documents/Visual Studio 2010/Projects/CheckList/CheckList/bin/Release/";
initiate_instance();
function initiate_instance() {
//insert
$.get(file + "saved.html", function(data) {
//$("table#items").append("<tr><th width='70%'>Issue</th><th width='30%' class='right'>Solved</th></tr>");
$("table#items").html($("table#items").html() + data);
});
//change [X] into a link
$("table#items tr td").each(function() {
$(this).html($(this).html().replace("[X]", "<a onclick='return remove(this)' href='#'>[X]</a>"));
});
//change the css
$("table#items tr:odd").attr("class", "odd");
$("table#items tr td:eq(0)").attr("width", "70%");
$("table#items tr td:eq(1)").attr("width", "30%");
$("td.solved, td.solved_2").click(function() {
if($(this).attr("class") == "solved") {
$(this).attr("class", "solved_2");
$(this).text("Unsolved");
} else {
$(this).attr("class", "solved");
$(this).text("Solved");
}
if(showalert == true) {
alert("Remember, for these changes to keep effect please save before closing the program.");
showalert = false;
}
});
}
//delete rows
function remove(obj) {
if(showalert == true) {
alert("Remember, for these changes to keep effect please save before closing the program.");
showalert = false;
}
$(obj).parent().parent().remove();
return false;
}
TL;DR: Have you tried setting "AllowNavigation" to true?
If you need to prevent navigation, but still need to update the page, a method I've found that works requires:
Initializing the WebBrowser control's DocumentText property with empty HTML to initialize the internal objects (i.e.: Document, DomDocument, Document.Body, etc)
Allowing navigation and the revoking upon page completion (if needed)
Code:
namespace CheckList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Initialize all the document objects
webBrowser1.DocumentText = #"<html></html>";
// Add the Document Completed event handler to turn off navigation
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Load default information via LoadHtml(string html);
LoadHtml(#"<html><head></head><body>Text!<script type='text/javascript' language='javascript'>alert('Aha!');</script></body></html>");
}
private void LoadHtml(string html)
{
webBrowser1.AllowNavigation = true;
// This will trigger a Document Completed event
webBrowser1.DocumentText = html;
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Prevent further navigation
webBrowser1.AllowNavigation = false;
// Clean-up the handler if no longer needed
}
private void button2_Click(object sender, EventArgs e)
{
// Do your document building
LoadHtml(doc.Body.Parent.OuterHtml);
}
}
}
I've found doing it this way:
Prevents users from navigating until allowed
Allows execution of JavaScript (immediately before OnDocumentCompleted fires)

Categories