Adding a picture to a checkbox list after binding - c#

Is there any way to populate a checkbox list through datasource/ databind and then actually add an image to each checkbox? i know how to do both separately but cant seem to figure out how to make them work together.
Essentially i will have a checkbox list of students for teachers to select from and i've been asked to put a picture of each student next to the checkbox.
The way i get images currently is i have a webform which intakes an ID in the url and then it grabs the blob off the database then converts the binary into a thumbnail image, saves that locally then redirects to it. then when i want to get an image on a different webform i just need to use Response.Redirect("imgs.aspx?ID=[Student Id]") and it will put in a small image of the student, is there any way to modify a checkbox list so that i can call on the imgs webform and display the image of the student next to their checkbox?
Code behind imgs.aspx:
protected void Page_Load(object sender, EventArgs e)
{
var stuId = Request.QueryString["ID"];
if (stuId.Length <= 0)
{
stuId = "100097645"; // If no ID number sent, display default 'image not available' thumbnail.
}
var con = new SqlConnection
{
ConnectionString =
removed for security reasons
};
con.Open();
var sqlCommand = new SqlCommand("Select BINARY_OBJECT FROM BLOBS WHERE OWNER_REF=" + stuId, con);
var reader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
reader.Read();
var byteArray = (byte[])reader["BINARY_OBJECT"];
var mstream = new System.IO.MemoryStream(byteArray, 0, byteArray.Length);
var dbImage = System.Drawing.Image.FromStream(new System.IO.MemoryStream(byteArray));
var thumbnailImage = dbImage.GetThumbnailImage(100, 100, null, new IntPtr());
thumbnailImage.Save(mstream, dbImage.RawFormat);
var thumbnailByteArray = new byte[mstream.Length];
mstream.Position = 0;
mstream.Read(thumbnailByteArray, 0, Convert.ToInt32(mstream.Length));
Response.Clear();
Response.BinaryWrite(thumbnailByteArray);
}
code i have so far to display the image:
private void StudentSelected()
{
string query = "Select distinct (Convert(varchar, PERSON_CODE) + '|' + FORENAME + ' ' + SURNAME) as StudentName, (Convert(varchar, PERSON_CODE) + '|' + FORENAME + '|' + SURNAME) as StudentValue From people where (FORENAME = '" + stuforename + "') and (SURNAME = '" + stusurname + "') and (Convert(varchar,PERSON_CODE) = '" + stuid + "')";
StudentCheckBoxData.Merge(GetData(query));
cbSelection.DataSource = StudentCheckBoxData;
cbSelection.DataTextField = "StudentName";
cbSelection.DataValueField = "StudentValue";
cbSelection.DataBind();
try
{
foreach (ListItem checkBox in cbSelection.Items)
{
checkBox.Text += string.Format("<img src = \"{0}\" /> ", GetImageUrl(checkBox.Text.Split('|')[0]));
}
}
catch
{
//Display Error Here
}
}
private string GetImageUrl(string id)
{
return string.Format("http://bceforms/Contact/imgs.aspx?ID=", id);
}
The problem at the moment is it shows the border but the image that appears is a Thumbnail not found image, when i've had this issue before it's been because image hasn't been databound however when i then use .databind(); on the checkbox List because it obviously the original datasource doesn't have the image, it just removes the image
Any help would be apprecieated

I do not think it is a good way in performance to save image data in sql, Instead you can save the image url in the sql and save the image file. And at the end of your code you have a problem:
private string GetImageUrl(string id)
{
return string.Format("http://bceforms/Contact/imgs.aspx?ID=", id);
}
You must change that to this:
private string GetImageUrl(string id)
{
return string.Format("http://bceforms/Contact/imgs.aspx?ID={0}", id);
}
After fixing this, Please let know the result.

Related

Trying to use File Upload in Listview? Update not working

Here is my ListView. I'm using the OnItemCommand to reference the code in code-behind. Here I'm trying to Update the database with the new FileUpload control.
<%--Listview--%>
<asp:ListView runat="server" ID="livLocation" class="container"
DataKeyNames="LocationID"
DataSourceID="sdsListViewLocation"
EmptyDataText="No data to display"
InsertItemPosition="FirstItem"
OnItemInserted="livLocation_ItemInserted"
OnItemUpdated="livLocation_ItemUpdated"
OnItemDeleted="livLocation_ItemDeleted"
OnItemCanceling="livLocation_ItemCanceling"
OnItemCommand="livLocation_ItemCommand">
</asp:ListView>
The Insert works perfectly fine. When an Update is executed a Null error is thrown for all FindControls. I believe for some reason the FindControls are not working for the Update. I have tried giving each control their own id's but that still didn't fix the problem. I have been referencing this post but nothing has helped so far: Upload images with fileupload within a Listview asp.net
protected void livLocation_ItemCommand(object sender, ListViewCommandEventArgs e)
{
//
if (e.CommandName == "Insert")
{
// Find controls on insert.
TextBox txtLocation = (TextBox)livLocation.InsertItem.FindControl("txtLocation");
TextBox txtImage = (TextBox)livLocation.InsertItem.FindControl("txtImage");
FileUpload fuiImage = (FileUpload)livLocation.InsertItem.FindControl("fuiImage");
// Get today's date
String strDate = DateTime.Now.ToString("MM-dd-yyyy-h-m-stt");
// If file is there to upload.
if (fuiImage.HasFile)
{
// Set path.
String strFileName = txtLocation.Text + "-" + strDate + ".jpg";
String strPath = Request.PhysicalApplicationPath + "Image\\Location\\" + strFileName;
// Save file.
fuiImage.SaveAs(strPath);
// Fill Image textbox
txtImage.Text = strFileName;
}
else
{
// Do nothing
}
}
else if (e.CommandName == "Update")
{
// Find controls on insert.
TextBox txtLocation = (TextBox)livLocation.InsertItem.FindControl("txtLocation");
TextBox txtImage = (TextBox)livLocation.InsertItem.FindControl("txtImage");
FileUpload fuiImage = (FileUpload)livLocation.InsertItem.FindControl("fuiImage");
// Get today's date
String strDate = DateTime.Now.ToString("MM-dd-yyyy-h-m-stt");
// If file is there to upload.
if (fuiImage.HasFile)
{
// Set path.
String strFileName = txtLocation.Text + "-" + strDate + ".jpg";
String strPath = Request.PhysicalApplicationPath + "Image\\Location\\" + strFileName;
// Save file.
fuiImage.SaveAs(strPath);
// Fill Image textbox
txtImage.Text = strFileName;
}
else
{
// Do nothing
}
}
else if (e.CommandName == "Delete")
{
// Delete file.
FileUpload fuiImage = (FileUpload)livLocation.InsertItem.FindControl("fuiImage");
String strPath = Request.PhysicalApplicationPath + "Image\\Location\\" + fuiImage.FileName;
System.IO.File.Delete("strPath");
}
else
{
// Do nothing
}
}
}
As discussed its always nice to use the sender object for better maintainability later. for your issue kindly visit the following link to get the edited item as your syntax is not correct: https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.listview.itemediting?view=netframework-4.8
it shows more details about item editing and how to fetch the edited item with the new edit index.
the
(TextBox)livLocation.InsertItem is incorrect it must be EditItem
so it will be (FileUpload)(sender as ListView).EditItem.FindControl.....

Combobox does not showing added items (with if condition)

I have a question regarding combobox. Add first I try to add some items to classTimeComboBox by looping the array and it works. But when I try to combine the foreach looping with if condition and the combobox display nothing inside it. Can someone fix this for me?
Here is my database screenshot
(All table in the database is in "Short Text" type.)
private void classTimeComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string ClassTime = classTimeComboBox.Text;
string ClassDate = classDateBox.Text;
string[] ClassName = { "CL01", "CL02", "CL03", "CL04", "CL05", "CL06", "CL07", "CL08", "CL09" };
if(classTimeComboBox.SelectedItem.ToString() == "08:00")
{
foreach (string x in ClassName)
{
cnnOleDB.Open();
checkAvailableClassRoom.CommandText = "Select * from Uploads where [ClassDate]='" + ClassDate + "' AND [ClassTime]='" + ClassTime + "' AND [ClassName]='" + x + "';";
checkAvailableClassRoom.Connection = cnnOleDB;
OleDbDataReader readDatabase = checkAvailableClassRoom.ExecuteReader();
if (readDatabase.Read() != true)
{
classNameComboBox.Items.Add(x);
}
else
{
}
cnnOleDB.Close();
}
}
}
The OleDbReader.Read() advances the reader to the next record and the method returns
true if there are more rows; otherwise, false.
So you should change the code, if you expect to have db more than one row, to this:
while (reader.Read())
{
var stringIdx = reader.GetOrdinal("<string Colum to display in combobox>");
classNameComboBox.Items.Add(reader.GetString(stringIdx));
}
If you only expect one row, or don't care about the number of rows you can change the while with the if you have with a small change:
if (readDatabase.Read() == true)
{
classNameComboBox.Items.Add(x);
}

Increase the amount of data on listview when the data is successfully stored in sqlite in uwp

I have a listview whose data comes from a sqlite database. The database is created when the user selects the list on the previous page whose data comes from JSON.
Code:
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
if (connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
{
loading.IsIndeterminate = true;
try
{
string urlPath = "https://.../tryout_perid";
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("tid", ((App)(App.Current)).ID)
};
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
loading.IsIndeterminate = false;
RequestException();
}
string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonData = jsonObject["data"].GetArray();
foreach (JsonValue groupValue1 in jsonData)
{
JsonObject groupObject2 = groupValue1.GetObject();
string id = groupObject2["id"].GetString();
string title = groupObject2["judul"].GetString();
QuizHome quiz = new QuizHome();
quiz.ID = id;
((App)(App.Current)).ID = quiz.ID.ToString();
quiz.Title = title;
quizDataSource.Add(quiz);
if (quizDataSource.Count > 0)
{
string InsertQuiz = #"INSERT INTO DBName (ID,Judul) SELECT '" + id.ToString() + "','" + title.ToString() + "','" + "' WHERE not exists " +
"(select ID and Judul FROM DBName WHERE ID='" + id.ToString() + "' and Judul='" + title.ToString() + "')";
var quizName = objConn.Prepare(InsertQuiz);
quizName.Step();
}
JsonArray jsonDataSoal = groupObject2["list_soal"].GetArray();
foreach (JsonValue groupValueSoal in jsonDataSoal)
{
JsonObject groupObjectSoal = groupValueSoal.GetObject();
string qid = groupObjectSoal["qid"].GetString();
string pertanyaan = groupObjectSoal["question"].GetString();
QuizQuestion question = new QuizQuestion();
question.QID = qid;
question.Pertanyaan = pertanyaan;
questionDataSource.Add(question);
if (questionDataSource.Count > 0)
{
string InsertQuestion = #"INSERT INTO DBQuestion (QID,Pertanyaan) SELECT '" + qid.ToString() + "','" + pertanyaan.ToString() + "' WHERE not exists " +
"(select QID and Pertanyaan FROM DBQuestion WHERE OID='" + qid.ToString() + "' and Pertanyaan='" + pertanyaan.ToString() + "')";
var quizQuestion = objConn.Prepare(InsertQuestion);
quizQuestion.Step();
}
JsonArray jsonDataOption = groupObjectSoal["jawaban"].GetArray();
foreach (JsonValue groupValueOption in jsonDataOption)
{
JsonObject groupObjectOption = groupValueOption.GetObject();
string oid = groupObjectOption["oid"].GetString();
string option = groupObjectOption["q_option"].GetString();
string score = groupObjectOption["score"].GetString();
QuizOption pilihan = new QuizOption();
pilihan.OID = oid;
pilihan.Option = option;
optionDataSource.Add(pilihan);
if (optionDataSource.Count > 0)
{
string InsertOption = #"INSERT INTO DBOption (OID,Option) SELECT '" + oid.ToString() + "','" + option.ToString() + "','" + "' WHERE not exists " +
"(select OID and Option FROM DBOption WHERE OID='" + oid.ToString() + "' and Option='" + option.ToString() + "')";
var quizOption = objConn.Prepare(InsertOption);
quizOption.Step();
}
}
}
this.Loaded += ReadTryoutList_Loaded;
loading.IsIndeterminate = false;
}
}
private void ReadTryoutList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllDBName dbName = new ReadAllDBName();
DB_TryoutList = dbName.GetAllDBName();
ListTryout.ItemsSource = DB_TryoutList.OrderByDescending(i => i.ID).ToList();//Binding DB data to LISTBOX and Latest contact ID can Display first.
if (DB_TryoutList.Count == 0)
{
statuskosongStack.Visibility = Visibility.Visible;
ListTryout.Visibility = Visibility.Collapsed;
}
else
{
statuskosongStack.Visibility = Visibility.Collapsed;
ListTryout.Visibility = Visibility.Visible;
}
}
I am having problems, that is when the user selects the list on the previous page and the data is successfully stored in the database, but the amount of data on listview is not increased. If I click the back button and enter on this page again, then the data on listview increases. How do I get listview to increase in the number of data when the data is successfully saved?
This issue is caused by the asynchronous method in your code. After you click the item, you navigate to the TryoutLibrary1 page. On this page, you save the data to the database meanwhile you get the data source from the database on the Page.Loaded event. But when you get the data, the clicked item has not been insert into the database, so it will not display on the page until you reload the data(reenter the page again).
So you should reconsider your logic again in the ItemClick event, you should make sure the data have saved into the database then you get and set the data as the ListView.ItemsSource. As a example, when you click the item, you can create a object and put it into a local ObservableCollection object, then set the ObservableCollection as the ListView itemsSource to make it display on the UI, on other side, you save the item to the database.

How to convert value in a hiddenfield to an integer in an asp.net c# web forms application?

I have a hiddenfield titled hdn_ven_id that is populated with the primary key value (integer) when a row in a grid is selected.
protected void rg_vendors_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridDataItem item in rg_vendors.SelectedItems)
{
hdn_ven_id.Value = item["venId"].Text;
}
}
Then I use the value from hdn_ven_id to populate #venIdFk in a SqlCommand.
protected void newDocUpldBtn_Click(object sender, EventArgs e)
{ ...
new_doc_cmd.Parameters.AddWithValue("#venIdFk", hdn_ven_id.Value);
...}
I get the following error:
Conversion failed when converting the nvarchar value '81,' to data type int.
81 is the correct primary key value, so I know that the correct value is being captured by the hidden field.
I have reviewed several threads like this one (Convert HiddenField to Integer) on how to convert the value of the hiddenfield from an nvarchar to an integer. However, I can't get the value of the hidden field to go into the database. If I add
int venidfk = int.Parse(hdn_ven_id.Value);
to newDocUpldBtn_Click I get the error "Input string was not in a correct format".
How can I convert the hiddenfield value to an integer?
Here is all of newDocUpldBtn_Click:
protected void newDocUpldBtn_Click(object sender, EventArgs e)
{
int venidfk = int.Parse(hdn_ven_id.Value);
//Save the file to the server and set the full path
int i = 0;
FileUpload fu = docFU;
string filename = fu.FileName;
string fnnnoext = System.IO.Path.GetFileNameWithoutExtension(fu.FileName);
string fnnextonly = System.IO.Path.GetExtension(fu.FileName);
if (fu.HasFile)
{
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))
{
i++;
filename = (fnnnoext + "(" + i.ToString() + ")" + fnnextonly);
}
fu.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);
hdn_doc_path.Value = (Server.MapPath("~/Data/") + filename);
hdn_doc_path_no_ext.Value = (fnnnoext + "(" + i.ToString() + ")" + fnnextonly);
SqlConnection drap_cnxn = new SqlConnection("Data Source=WDBSVCPRD01\\SVCDB;Initial Catalog=drap;Integrated Security=True");
{
SqlCommand new_doc_cmd = new SqlCommand("Insert Into docs(docTitle, docType, docContractType, docOrg, docDept, docDesc, PriorContCd, LegCompContId, docUpldDt, docPath, docStat, venIdFk) Values(LTRIM(RTRIM(#docTitle)), LTRIM(RTRIM(#docType)), LTRIM(RTRIM(#docContractType)), LTRIM(RTRIM(#docOrg)), LTRIM(RTRIM(#docDept)), LTRIM(RTRIM(#docDesc)), LTRIM(RTRIM(#PriorContCd)), LTRIM(RTRIM(#LegCompContId)), LTRIM(RTRIM(#docUpldDt)), LTRIM(RTRIM(#docPath)), LTRIM(RTRIM(#docStat)), LTRIM(RTRIM(#venIdFk)))", drap_cnxn);
new_doc_cmd.Parameters.AddWithValue("#docTitle", docTitleTextBox.Text);
new_doc_cmd.Parameters.AddWithValue("#docType", docTypeDdl.SelectedValue);
new_doc_cmd.Parameters.AddWithValue("#docContractType", docContractTypeDdl.SelectedValue);
new_doc_cmd.Parameters.AddWithValue("#docOrg", docOrgDdl.SelectedValue);
new_doc_cmd.Parameters.AddWithValue("#docDept", docDeptDdl.SelectedValue);
new_doc_cmd.Parameters.AddWithValue("#docDesc", docDescTextBox.Text);
new_doc_cmd.Parameters.AddWithValue("#PriorContCd", priorContCdTextBox.Text);
new_doc_cmd.Parameters.AddWithValue("#LegCompContId", legCompContIdTextBox.Text);
new_doc_cmd.Parameters.AddWithValue("#docUpldDt", DateTime.Now.ToString());
new_doc_cmd.Parameters.AddWithValue("#docPath", hdn_doc_path.Value);
new_doc_cmd.Parameters.AddWithValue("#docStat", "4");
new_doc_cmd.Parameters.AddWithValue("#venIdFk", venidfk);
drap_cnxn.Open();
new_doc_cmd.ExecuteNonQuery();
drap_cnxn.Close();
if (IsPostBack)
{
ven_doc_det_upld_status_lbl.Text = "Your document was successfully uploaded.";
docTitleTextBox.Text = "";
docTypeDdl.Text = "";
docContractTypeDdl.SelectedValue = "";
docOrgDdl.Text = "";
docDeptDdl.Text = "";
docDescTextBox.Text = "";
priorContCdTextBox.Text = "";
legCompContIdTextBox.Text = "";
hdn_doc_path.Value = "";
rg_vendors.DataBind();
fv_ven_docs.DataBind();
}
else
{
ven_doc_upld_fail_lbl.Text = "Your document failed to upload. Please contact Compliance for assistance.";
}
}
}
}
It looks like your hidden field includes a comma. Either figure out where that's coming from and remove it, or use
new_doc_cmd.Parameters.AddWithValue("#venIdFk", hdn_ven_id.Value.Replace(",",""));

Load picture from SQL database asp.net C#

I have avatars stored in a database. I have used the the data type image for the avatars. I want to load the avatar of a user into an image control, but i cant get it to work. I have tried this code without any luck:
public void GetUserAvatar()
{
string username = Convert.ToString(Session["username"]);
var image = from u in dc.Users
where u.username == username
select u.image;
imgAvatar.Controls.Add(image);
}
I think i might have to save the images to a folder and then save the file path in the database instead. This seems to be easier and smoother. Any ideas?
I ended up saving the image to a folder and then saving the path to the database. My code for image uploading now looks like this:
public void addImage()
{
if (fuAvatar.PostedFile.ContentType.ToLower().StartsWith
("image") && fuAvatar.HasFile)
{
string saveLocation = Server.MapPath("savedAvatars/");
string fileExtension = System.IO.Path.GetExtension(fuAvatar.FileName);
string fileName = Convert.ToString(Session["userid"]);
string savePath = saveLocation + fileName + fileExtension;
fuAvatar.SaveAs(savePath);
string imageDBPath = fileName + fileExtension;
LinqClass1DataContext dc = new LinqClass1DataContext();
int userid = Convert.ToInt32(Session["userid"]);
var tblUser = (from u in dc.Users
where u.userid == userid
select u).First();
tblUser.imagePath = #"\savedAvatars\"+imageDBPath;
dc.SubmitChanges();
lblResult.Text = "Avatar lastet opp!";
}
else lblResult.Text = "Avatar ikke lastet opp!";
}
And to load the picture:
public void GetUserAvatar()
{
int userid = Convert.ToInt32(Session["userid"]);
var varPath = dc.Users.Single(u => (u.userid == userid)).imagePath;
string imagePath = Convert.ToString(varPath);
imgAvatar.ImageUrl = imagePath;
}
you should add a generic handler file (.ashx) and write in it something like that:
string sql = "select image from table1";
SqlCommand command = new SqlCommand(sql, con);
SqlDataReader dReader = command.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["Source"]);
dReader.Close();
then in your page do something like this:
img.ImageUrl = "Handler.ashx;
http://www.dotnetcurry.com/ShowArticle.aspx?ID=129 read this article, first I've found. Basically you need to create a handler which responds with the raw image.
Please find the answer in below link.
Get images from database using Handler
You will have to create a handler which will load the image and u can pass the source to image
tag.

Categories