How to display employeephoto from database on listbox item click - c#

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)

Related

webbrowser-control missing content on load

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

How to transfer data of selected value in comboBox from one form to another

I have winform that shows the info of a company with a comboBox that shows the delegates of that company now If I select one of those delegates and clicked edit button for the selected delegate another form should appear with the info of that selected delegate to allow me modify the info; the common key between company and delegate tables is id so how to do this ???
this is my codes for the form of edit company
delIdVar = Convert.ToInt32(compDelcombox.SelectedValue);
DelEditFrm delEditFrm = new DelEditFrm(delIdVar);
delEditFrm.Show();
and this is the codes for the constructor of delegate edit form
public DelEditFrm(int delIdVar)
{
InitializeComponent();
int delId = delIdVar;
}
and finally these codes for loading the columns data into textBoxes in my delegate edit form load event
private void DelEditFrm_Load(object sender, EventArgs e)
{
try
{
cn.Open();
cmd = new SqlCommand("select delName,delAdd,delPhone1,delPhone2 from delegate where delId= ' delId '", cn);
dr = cmd.ExecuteReader();
dr.Read();
delEditNametxt.Text = dr["delName"].ToString();
delEditAddtxt.Text = dr["delAdd"].ToString();
delEditPhone1txt.Text = dr["delPhone1"].ToString();
delEditPhone2txt.Text = dr["delPhone2"].ToString();
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
dr.Close();
cn.Close();
}
}
when I attempt to edit the selected delegate it gives me an exception "Convertion failed when converting the varchar value 'delId' to data type int " but the dilId column in my table is of int type
The basic idea is to:
Map the delegate to the id. (this can be stored or queried, if it's really a db)
When a delegate is selected, trigger a lookup of that id and populate the fields of a dialog box. (again, lookup or query)
Record changes when that dialog is closed. (a Modify on that item)

corrupt database & listbox problems

im working in WinForms C#.
for some reason when I want to populate my listBox it stops and says my database is corrupt.
I have added a repair line and the codes run afterwards, but nothing happends. My listbox is not populated.
Here is the code im using.:
public void button1_Click(object sender, EventArgs e)
{
SqlCeConnection cn = new SqlCeConnection(#"Data Source = Database1.mdf");
cn.Open();
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM tblprojects ORDER BY Projekt_liste ASC", cn);
try
{
SqlCeDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
ListBox project_list = Application.OpenForms["Form1"].Controls["tabControl1"].Controls["tabPage1"].Controls["Project_list"] as ListBox;
project_list.Items.Add(dr["Projekt_liste"].ToString());
}
cn.Close();
cn.Dispose();
}
catch (Exception ex)
{
}
}
public void button2_Click(object sender, EventArgs e)
{
SqlCeConnection cn = new SqlCeConnection();
SqlCeEngine engine = new SqlCeEngine("Data Source = Database1.mdf");
if (false == engine.Verify())
{
MessageBox.Show("Database is corrupted.");
engine.Repair(null, RepairOption.RecoverAllPossibleRows);
}
}
For example if you want to load the items
1. make sure you have a ListBox on the winform
2. name the ListBox
3. Create a ListItem
4 Add the ListItem to the ListBox
while(dr.Read())
{
ListViewItem obj=new ListViewItem(Convert.ToString(dr[0]),Convert.ToString(dr[1]);
//in object of ListViewItem give display member at first and give value member at second position
listView1.Items.Add(obj); // add object to the listbox
}
Here are a few links that you can use as well to show different ways on how to populate a ListBox
one is Windows and the other will be if you are using or plan to use ASP.NET
Populate a ListBox when using SQLDataReader
asp.net SqlDataReader example: how to use Read() method to populate ListBox
Populate ASP.NET ListBox using SqlDataReader
From Microsoft Site
The Repair method does not guarantee complete data recovery for every
database. Some forms of data corruptions cannot be repaired
completely, regardless of the Repair option that is selected by the
application.
This could be one of the case where your file is corrupted.
Also please try To have repair call straight above the call to populate Data in List.
This may help.

Transfer data to another table and make previous GridView empty

I have GridView. When I click a button, it sends data to another table and makes the previous GridView empty.
I have the following code for the button click, but it does not make the previous GridView empty.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string userApply = "insert into Company (CompanyName) select (JobTitle) from Jobs where JobTitle=JobTitle";
SqlCommand insertApply = new SqlCommand(userApply, conn);
try
{
insertApply.ExecuteNonQuery();
conn.Close();
Response.Redirect("ApplyJob.aspx");
}
catch (Exception er)
{
Response.Write(er.ToString());
}
finally
{
}
}
}
}
Are you clearing the previous gridview anywhere?
Maybe try this before your redirect:
grvPrevious.DataSource = null;
grvPrevious.DataBind();
it looks like you have your GridView in ApplyJob.aspx, since you are redirecting to that page in your try block and there you see the gridview holding some values. You may pass a query string along with ApplyJob.aspx and then in your form load of ApplyJob.aspx check for that query string. If you find the value then clear the Gridview. Something on the following line..
In your try block do :
Response.Redirect("ApplyJob.aspx?ClearGridView=YES");
In your Form_Load event of the ApplyJob.aspx check for the query string
if(Request.QueryString["ClearGridView"] != null && Request.QueryString["ClearGridView"] =="YES")
{
yourGridView.DataSource = null;
youGridView.DataBind();
}

ADO.NET: Data not being displayed properly in repeater

I am facing a peculiar issue in my ADO.NET code. This is the table data that I am accessing from a repeater from the frontend.
1 get car cleaned 2012-02-14 08:32:25.643 NULL
2 submit tax documents 2012-02-14 08:33:04.610 NULL
3 photo copy all documents 2012-02-14 08:33:04.610 NULL
Data in the first row is not being displayed at all.
If I delete the rows 2 and 3, no data is being displayed in the repeater. I think the issue is with my ADO.NET code. Also, if I truncate the table completely, the page is loading forever as opposed to displaying the "No Data Found" message in the label.
protected void Page_Load(object sender, EventArgs e)
{
txtNewTask.Focus();
if (!IsPostBack)
{
GetTaskList();
}
}
protected void GetTaskList()
{
conn = new SqlConnection(cstr);
getTasksCmd = new SqlCommand("select Name, CreationDate, CompletionDate from tasks", conn);
try
{
using (conn)
{
conn.Open();
using (reader = getTasksCmd.ExecuteReader())
{
while (!reader.Read())
{
lblDbMsg.Text = "No Data Found!";
}
rptTaskList.DataSource = reader;
rptTaskList.DataBind();
}
}
}
catch (Exception)
{
throw;
}
}
Take out the while loop from your code:
using (reader = getTasksCmd.ExecuteReader())
{
rptTaskList.DataSource = reader;
rptTaskList.DataBind();
}
Because you are calling SqlDataReader.Read() once, you are moving past the first record. Therefore, if you want to be able to retrieve all of the rows of data including the first, don't call Read() at all.
SqlDataReader.Read() Method MSDN Reference

Categories

Resources