webbrowser-control missing content on load - c#

I have a WebBrowser-Control that is displaying Markdown with MarkDig.
I'm loading the markdown content from my DB, and load it into the webbrowser-controller.
At the same time, I have a textbox next to it, with the same content as the webbrowser-controller, there is an event on the textbox with TextChanged, so when the content in the textbox is changed, it inserts the new text into the webbrowser-controller, and displays it as markdown.
My problem is, when the application loads and the webbrowser-controller is getting the content, it is not displayed in the webbrowser. But the content is displayed in the textbox. The content in the webbrowser is not displayed before I change something in the textbox.
Loaded as normal:
This is when I have added a space after the text "An h1 header" in the top
This is my TextChanged event, which loads the text in the textbox into the webbrowser. If I out comment this line, it works and loads fine.
private void textBox_KB_markdown_TextChanged(object sender, EventArgs e)
{
wbMarkDown.DocumentText = Markdig.Markdown.ToHtml(textBox_KB_markdown.Text);
}
And this is how I load the content from my DB, into the webbrowser-controller and the textbox.
private void GetKBContent()
{
OpenConection();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Knowlagebase WHERE id = 1", conn);
// cmd.Parameters.AddWithValue("#email", email_);
// cmd.Parameters.AddWithValue("#password", password_);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
string db_markdown = rdr["Markdown"].ToString();
string DecryptedKB_markdown = DecryptKBContent(db_markdown);
textBox_KB_markdown.Text = DecryptedKB_markdown;
string html_Markdown = Markdig.Markdown.ToHtml(DecryptedKB_markdown);
wbMarkDown.DocumentText = html_Markdown;
}
}
else
{
MessageBox.Show("Content was not found", "Information");
}
CloseConection();
}
So my question is, how can this be fixed, so the webbrowser-controller is displaying the content when loaded, and not having to edit first? What am I doing wrong?

I got this fixed by changing the TextChanged to KeyUp instead
private void textBox_KB_markdown_KeyUp(object sender, KeyEventArgs e)
{
wbMarkDown.DocumentText = Markdig.Markdown.ToHtml(textBox_KB_markdown.Text);
}

Related

Refresh datagridview from another user control

Using C# and Winform.
I read a couple of similar questions but couldn't find any great answers that could interlock with my code. So, bear with me and thank you in advance for helping me.
I have a single form that contains multiple User Controls. Inside the first user control, you can insert, update and delete records from the database. In the second User Control, there is a datagridview that is populated with all records.
The problem I have is that whenever I insert, update or delete a record inside the first user control. It won't refresh inside the datagridview when I swap to the second user control.
Beneath is the second user control that populates the datagridview
private void populate()
{
database.OpenConnection();
string query = "SELECT id, name, qoute, time, date from maintable";
SQLiteDataAdapter sda = new SQLiteDataAdapter(query, database.connection);
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(sda);
var ds = new DataSet();
sda.Fill(ds);
dtgNav.DataSource = ds.Tables[0];
databas.CloseConnection();
}
private void Navigation_Load(object sender, EventArgs e)
{
populate();
dtgNav.Columns[0].HeaderText = "ID";
}
public void Refresh()
{
this.Refresh();
}
Beneath is the code for adding a record to the datagridview in the first user control
private void btnAdd_Click(object sender, EventArgs e)
{
database.OpenConnection();
string query = "INSERT INTO maintable (`id`, `name`, `qoute`, `time`,`date`) VALUES (#Id, #Name, #Qoute, #Time, #Date)";
SQLiteCommand command = new SQLiteCommand(query, database.connection);
command.Parameters.AddWithValue("#Id", tbxID.Text);
command.Parameters.AddWithValue("#Name", tbxName.Text.Trim());
command.Parameters.AddWithValue("#Qoute", tbxQoute.Text.Trim());
command.Parameters.AddWithValue("#Time", tbxTime.Text.Trim());
command.Parameters.AddWithValue("#Date", dtpDate.Value.ToString("yyyy-MM-dd"));
command.ExecuteNonQuery();
MessageBox.Show("Added new event into the database.");
database.CloseConnection();
usercontrol2.Refresh();
}
I would appreciate it if we found a way to refresh the datagridview when the button is clicked without changing the original code all too much.
You have a public void Refresh method in the second usercontrol, try modifying this.Refresh();, to say populate();. this should call your private void populate method that you called when loading which should reload the grid. Let me know if this helps.

i am getting an error at oledbdatareader saying no given value for one or more required parameters in ASP.NET

I have a webpage called blogwebsite and in that I have a textbox and search button. I am passing the value of textbox on button click to another webform called blogseacrh through session. I also have a database bound through these webforms. In this blogsearch webpage I have taken the session variable in a textbox. Using this textbox value I am writing a oledbcommand select query. I am fetching data from the database using this textbox value and want to display it on the blogsearch webpage. For this to happen I am using oledbdatareader to read the data and then write the fetched data in the textbox. But when I am running the webpage when I click on search button it gives me the error at the oledbdatareader line saying that no given value given for one or more required parameters.
I really can't understand what I am doing wrong. Can someone please give me a solution?
This is the button click event which is working perfectly
protected void btn_srch_Click(object sender, EventArgs e)
{
Session["name"] = txt_bnm.Text;
Response.Redirect("blogseacrh.aspx");
}
This is the code that needs to be executed on another webpage on button click event
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null)
{
con.Open();
txt2_bnm.Text = Session["name"].ToString();
cmd = new OleDbCommand("select user from tbl_blogs where book_name='" + txt2_bnm.text + "',con); `
OleDbDataReader d = cmd.ExecuteReader();
while (d.Read())
{
user = d["user"].ToString();
Response.Write(user);
}
cmd = new OleDbCommand("select blogs from tbl_blogs where book_name='" + txt2_bnm.Text + "' ", con);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
blogs = dr["blogs"].ToString();
Response.Redirect(blogs);
}
con.Close();
}
I have also checked all the field names and table name and they are all correct as well.
Can someone please solve this error. i have an assignment to complete please.

textchanged event trigger after given seconds

My requirement is that, there is a textbox and a datagrid , when i enter text in textbox by scanning, if the value is present in database it should be added to datagrid and textbox value should go empty.
i have kept this functionality in textbox textchanged event.
VALUE:
16789
35688
1678934
097544
if i scan'1678934', the value corresponding to '16789' is added in the grid and only 34 remains in textbox. how do i overcome this. should i place some timer so that once the scanning is complete the value may get added to the grid? how do i do it! or is there anyother event?
I used the following code
private void txtValue_TextChanged(object sender, EventArgs e)
{
if (txtValue.Text != "")
{
dataGridView1.Columns.Clear();
strValue = "SELECT NAME FROM EMPDETAIL WHERE ID = #input";
MySqlCommand cmdValue = new MySqlCommand(strValue, connection);
connection.Open();
cmdValue.Parameters.AddWithValue("#input", input);
MySqlDataAdapter adapterValue = new MySqlDataAdapter(cmdValue);
DataTable dtValue = new DataTable();
adapterValue.Fill(dtValue);
dataGridView1.DataSource = dtValue;
connection.Close();
}
}
EDIT:
Below Is the code to achieve the above functionality (as per #Daniel's Answer)
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (txtValue.Text != "")
{
if (e.KeyCode == Keys.Enter)
{
dataGridView1.Columns.Clear();
strValue = "SELECT NAME FROM EMPDETAIL WHERE ID = #input";
MySqlCommand cmdValue = new MySqlCommand(strValue, connection);
connection.Open();
cmdValue.Parameters.AddWithValue("#input", input);
MySqlDataAdapter adapterValue = new MySqlDataAdapter(cmdValue);
DataTable dtValue = new DataTable();
adapterValue.Fill(dtValue);
dataGridView1.DataSource = dtValue;
connection.Close();
}
}
}
The problem is of course that if product "123" exists, it'll be found when scanning product "1234". You can work around this using a timer like you suggested, but you really don't want that.
Barcode scanners (usually, and configurably) add a character after scanning, for example a newline character (\n).
Instead of looking up the record in the TextChanged event, add a default button to the form (which will be clicked by this newline interpreted as Enter key press), or use the KeyPress event to find out when the termination character is entered.

How to store values before postback

I have two dropdownlists, ddlstates and ddlcitys.
The ddlstates has a list of Brazilian states that when clicked, loads the ddlcitys with the cities of that state. Until then, everything works correctly, but when clicking the save button which makes verification of completed fields or not, the ddlcitys back to the first option. How to store the information ddlcitys before the postback?
In code behind, have code that loads the ddlcitys:
protected void ddlstates_TextChanged(object sender, EventArgs e)
{
if (ddlstates.Text != "")
{
List<ListItem> cidades = new List<ListItem>();
SqlConnection conn = new SqlConnection(mytools.stringconection);
SqlDataReader dr = null;
conn.Open();
SqlCommand cmd = new SqlCommand("select ciddesc from cidades where cidestsigla = '" + ddlstates.SelectedValue.ToString() + "' order by 1 asc");
cmd.Connection = conn;
dr = cmd.ExecuteReader();
ddlcitys.Items.Clear();
while (dr.Read())
{
cidades.Add(new ListItem(dr[0].ToString()));
}
dr.Close();
conn.Close();
ddlcitys.DataTextField = "Text";
ddlcitys.DataValueField = "Value";
ddlcitys.DataSource = cidades;
ddlcitys.DataBind();
}
}
Asked long time ago, anyway may the answer help anyone.
On your page load event before bind any of your dropdownlists, make sure that not post back, then on your dropdown select change events , your dropdown values will not re bind so values will not changed.
hint : make sure that your aspx page enable view state (by default enabled) read more.
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
//this will called when your page loaded at first time, so bind your drop down values here.
} else {
//this will called on select change, don't bind your dropdown again, then values will be same (asp.net web forms viewstates will handle read more about viewstate).
}
}

How to display employeephoto from database on listbox item click

I have a listbox that retrieves employeedata, and when I click on employee, I get his firstname, lastname and his photo.
I did everything until displaying the image from database. I have this code below. When I click on employeename in listbox, I want to load and display his photo alongside with his name too.
(SQL column EmployeePhoto is "image" type, where I successfully inserted employee images as binary.
Crawled this subject in stack but did not find a useful solution that I could understand. Need your kind help, thanks.
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) //select listbox item
{
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT EmployeeFirstName,EmployeeLastName,EmployeePhoto FROM Employees WHERE EmployeeID = #myvalue", cnn);
cmd.Parameters.AddWithValue("#myvalue", (ListBox1.SelectedValue));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
TextBox1.Text = dr.GetString(0);
TextBox2.Text = dr.GetString(1);
//want to display EmployeePhoto in ID:Image1 that was saved as binary
}
}
cnn.Close();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
I would save the image to the file System (using File.WriteAllBytes()). And then show the file from the file system in the image box.
You need image handler (ASHX) in order to display binary data to browser.
Image Handling In ASP.NET
For example,
using System;
using System.Web;
public class ImageHandler : IHttpHandler, IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
// Query image data from database based on query string value.
context.Response.BinaryWrite(YourImageByte);
}
public bool IsReusable {
get { return false; }
}
}
// Usage
Image1.ImageUrl ="ImageHandler.ashx?id=5"
You should use ListView control and not ListBox.
ListViewiItem has an ImageIndex property,that enables you to specify the index of the image to render from the it (It supports binding as well)

Categories

Resources