Combobox does not showing added items (with if condition) - c#

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

Related

c# equivalent to document.getElementById("ListBox"+i+"Item"+j).selected=true

I've created a dynamic webpage using strictly html, javascript, and MS Access. While it was functional, locally, there were complications deploying it. Since I have ported the data to MySQL and am trying to use Visual Studio's aspx.cs to do much of what the javascript did previously.
I have a screen that populates a dynamic set of rows based on a query result (two rows per record for aesthetics), one of the cells contains a drop down menu(html select/ asp:ListBox).
When I had everything only on javascript, I could create the cell, then create its contents, then set the selected value using:
document.getElementById("StatusDD" + rowCount).value = reader.GetValue(i);
From what I've gathered so far, the rough equivalent is:
ListItem li = StatusDD1.Items.FindByValue(reader.GetValue(i));
li.Selected = true;
However, I cannot simply hardcode StatusDD1 thru StatusDDx (for one, at the beginning my hardcoded set might be larger than the number of records returned, and two eventually the rows returned will be larger than the set of hardcoded values).
So what I did was I created the following function:
protected void setSelected(string selectId, string value)
{
/*Need to put something here to make the following work*/
selectId.Items.FindByValue(value).Selected = true;
}
The selectId being passed in is the name/id of the ListBox and the value is the value coming back from the query.
It's called like:
setSelected("StatusDD" + rowCount, (string)reader.GetValue(i));
If I could, for lack of better phrase, materialize the name created by "StatusDD"+rowCount, I could pass that name in as if I was passing in a ListBox, rather than a string.
Alternatively, if there was a way to select the ListBox from an array where I could do a conditional check WHERE/IF ListBox.Name = selectId, something like the following PseudoCode:
ListBox a = ListBox.NameMatches(selectId);
a.Items.FindByValue(value).Selected = true;
Currently ListBoxes are being created by defining the box in a string and then passing that string into an HtmlTableCell:
HtmlTable myTable = new HtmlTable();
HtmlTableRow newRow;
string cellId;
string cellContents;
int rowCount = 1;
string statusDisabled = "";
while (reader.Read()){
newRow = new HtmlTableRow();
myTable.Rows.Add( newRow );
...
...
cellContents = "<asp:ListBox name='StatusDD" + rowCount + "' id='StatusDD" + rowCount + "' style='width:100%; " + statusDisabled + "' value='" + reader.GetValue(i) + "' onchange='markNeedSave(" + (rowCount + 1) + ")'><asp:ListItem value='0'></asp:ListItem><asp:ListItem value='1'>New</asp:ListItem>....asp:ListBox>";
newRow.Cells.Add(new HtmlTableCell{InnerHtml = cellContents});
}
If it helps, here's how I had it working in javascript:
while (!rs.EOF) {
rowa = table.insertRow(rowCount);
rowa.id = "RECORD" + rowCount + "a";
cell = rowa.insertCell(i + 1);
cell.id = "RECORD" + rowCount + "_CELL" + (i + 1);
for (i = 0; i < 8; i++) {
cell.innerHTML = "<select name='StatusDD" + rowCount + "' id='StatusDD" + rowCount + "' style='width:100%' value='" + rs.fields(i).value + "' onchange='markNeedSave(" + (rowCount + 1) + ")'><option value='NONE'></option><option value='New'>New</option>...</select>";
if (readonly) {
document.getElementById("StatusDD" + rowCount).disabled = true;
}
document.getElementById("StatusDD" + rowCount).value = rs.fields(i).value;
}
...
}
OK, got the ListBox to work, but as I was researching, and when I finally got it to work, I discovered that what I wanted was the DropDownList, not the ListBox, but the same fixes needed to be done in order to get either to work.
I use the following function now:
protected void setSelected(string selectId, string value)
{
PlaceHolder TCS = Page.FindControl("TestingCS") as PlaceHolder;
DropDownList ddl = TCS.FindControl(selectId) as DropDownList;
if (ddl != null)
{
ddl.SelectedValue = value;
ListItem item = ddl.Items.FindByValue(value);
if(item != null)
{ item.Selected = true;}
}
}
Also, for my cell contents that just contain data using the following is fine:
cellContents = "<someString>";
newRow.Cells.Add(new HtmlTableCell{InnerHtml = cellContents});
but for my drop down (or list box) I need to use:
cell = new HtmlTableCell();
newRow.Cells.Add(cell);
DropList = new DropDownList();
DropList.ID = "StatusDD" + rowCount;
DropList.Items.Add(new ListItem("", "0"));
DropList.Items.Add(new ListItem("New", "1"));
...
cell.Controls.Add(DropList);
setSelected(DropList.ID, (string)(reader.GetValue(i)));
A smoother solution:
protected void setSelected(DropDownList ddl, string value)
{
ListItem item = ddl.Items.FindByValue(value);
if (item != null)
{ item.Selected = true; }
}
...
protected void accessRecord()
{
...
DropList = new DropDownList();
DropList.ID = "StatusDD" + rowCount;
DropList.Attributes["onChange"] = "javascript:markNeedSave(" + rowCount + ");";
DropList.Items.Add(new ListItem("", "0"));
DropList.Items.Add(new ListItem("New", "1"));
...
cell.Controls.Add(DropList);
setSelected(DropList,(string)reader.GetValue(i));
}
...
It sounds like the function you're looking for is FindControl. This can be used from the Page, or any parent control you might have created to hold your output.
An example implementation of your setSelected method might look like this:
protected void SetSelected(string selectId, string value)
{
var lb = Page.FindControl(selectId) as ListBox;
if (lb != null)
{
var item = lb.Items.FindByValue(value)
if(item != null)
item.Selected = true;
}
}

Adding a picture to a checkbox list after binding

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.

Method usage on ItemDataBound C# ASP.net

I have a method to use on ItemDataBound;
static void getPhoto() {
Fonksiyonlar vt=new Fonksiyonlar();
DataTable SeriFoto = vt.GetDataTable("select foto from seriFotograf where seriilanID=" + DataBinder.Eval(e.Item.DataItem, "ilan_id") + " and kapak=true" + " order by seriilanID desc");
if (SeriFoto.Rows.Count < 1)
{
DataRow nullPhotoRow;
nullPhotoRow = SeriFoto.NewRow();
nullPhotoRow["foto"] = "0.png";
SeriFoto.Rows.Add(nullPhotoRow);
}
Repeater rptReddedilenFoto = (Repeater)e.Item.FindControl("rptReddedilenFoto");
rptReddedilenFoto.DataSource = SeriFoto;
rptReddedilenFoto.DataBind();
}
But i get an error:
The name 'e' does not exist in the current context
These codes running normally but it doesn't in method.
The simplest, pass the DataGridItem to this method (or GridViewRow if it's a GridView):
static void getPhoto(DataGridItem item) {
DataRowView view = (DataRowView) item.DataItem;
Fonksiyonlar vt=new Fonksiyonlar();
DataTable SeriFoto = vt.GetDataTable("select foto from seriFotograf where seriilanID=" + view["ilan_id"] + " and kapak=true" + " order by seriilanID desc");
if (SeriFoto.Rows.Count < 1)
{
DataRow nullPhotoRow = SeriFoto.NewRow();
nullPhotoRow["foto"] = "0.png";
SeriFoto.Rows.Add(nullPhotoRow);
}
Repeater rptReddedilenFoto = (Repeater)item.FindControl("rptReddedilenFoto");
rptReddedilenFoto.DataSource = SeriFoto;
rptReddedilenFoto.DataBind();
}

Combobox.Text.Equals Not Testing Expected Value

I am currently modifying an existing application, I am removing the old UI elements and replacing them with standard WinForms components. So this code is functional as it appears.
My code is passing the conditional IF check when it should not be. The text for each of the comboboxes is <Any> by default, so they should skip past the encapsulated code.
(When filters are selected, they replace the default text to select the correct parts of SQL query to return results)
Now for the bizarre part!
The text property is coming up as System.Data.DataRowView for some of my combobox.text. Originally, this happened for all of them but now the first check appears as <Any> as intended. (Although I didn't change anything at all)
As you can see in this screenshot of my code during debug. The pinned value of cbRegGroup.Text is System.Data.DataRowView but when I enter the list of properties and scroll down to the text property it is shown as <Any>.
I have cleaned and rebuilt my project... and consulted with a college but neither of us can work out why text value is appearing like a .ToString()'ed object.
I am at a loss at what to do next. Any suggestions?
private void LoadPupilView()
{
try
{
this.Cursor = Cursors.WaitCursor;
dgMain.Rows.Clear();
//now populate list view
String filter = "[surname] LIKE '" + SearchString + "%'";
if (!cbYearGroup.Text.Equals("<Any>"))
{
String YearGroupCode = null;
try
{
YearGroupCode = cbYearGroup.SelectedValue.ToString();
}
catch { }
if (!String.IsNullOrEmpty(YearGroupCode))
filter = filter + " AND [yearGroup] LIKE '" + YearGroupCode + "'";
}
if (!cbRegGroup.Text.Equals("<Any>"))
{
String RegGroupCode = null;
try
{
RegGroupCode = cbRegGroup.SelectedValue.ToString();
}
catch { }
if (!String.IsNullOrEmpty(RegGroupCode))
filter = filter + " AND [registrationGroup] LIKE '" + RegGroupCode + "'";
}
if (!cbHouse.Text.Equals("<Any>"))
{
String HouseGroupCode = null;
try
{
HouseGroupCode = cbHouse.SelectedValue.ToString();
}
catch { }
if (!String.IsNullOrEmpty(HouseGroupCode))
filter = filter + " AND [houseGroup] LIKE '" + HouseGroupCode + "'";
}
DataRow[] dataRows = tblPupils.Select(filter);
foreach (DataRow datarow in dataRows)
{
dgMain.Rows.Add(new object[] {
datarow[0].ToString(),
datarow[1].ToString() + " " + datarow[2].ToString(),
datarow[5].ToString(),
datarow[4].ToString(),
datarow[6].ToString(),
datarow[3].ToString()
});
}
}
catch (Exception err)
{
MessageBox.Show("Error : " + err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
this.Cursor = Cursors.Default;
}
}
I'm very interested in knowing why this seems to be inconsistent... why is the first conditional check passed? When the rest aren't although they are the same.
You need to set the DisplayMember property of the ComboBox to the name of the column you want to display.

How i know when job occur on list view (SQL Server 2000)

I trying to write a job monitor on Listview, I get information from sysjob and sysjobhistory tables in msdb database. How I know when job occur on list view?
I don't understand about run_time column. I want to show last job on top line and show time
when job occur as shown in picture (i have 2 job Fern and Same)
Form sysjobhistory show number code that I don’t know it mean such as 70000,71000 …
but I want to show time as 11.00am, 10.00am... as shown in picture.
I want to show info continuously follow time schedule recurring for monitoring JOB.
public void GetJobsAndStatus()
{
string sqlJobQuery = "select j.job_id, j.name, j.enabled, jh.run_status, jh.message, jh.run_date, jh.step_name, jh.run_time from sysjobs j inner join sysjobhistory jh on j.job_id = jh.job_id";
// create SQL connection and set up SQL Command for query
using (SqlConnection _con = new SqlConnection("server=10.15.13.70;database=msdb;user id=sa;pwd="))
using (SqlCommand _cmd = new SqlCommand(sqlJobQuery, _con))
{
try
{
// open connection
_con.Open();
// create SQL Data Reader and grab data
using (SqlDataReader rdr = _cmd.ExecuteReader())
{
// as long as we get information from the reader
while (rdr.Read())
{
Guid jobID = rdr.GetGuid(0); // read Job_id
string jobName = rdr.GetString(1); // read Job name
byte jobEnabled = rdr.GetByte(2); // read Job enabled flag
int jobStatus = rdr.GetInt32(3); // read run_state from jobhistory
string jobMessage = rdr.GetString(4);
int jobRunDate = rdr.GetInt32(5);
string jobStepName = rdr.GetString(6);
int jobRunTime = rdr.GetInt32(7);
String[] lviData = new String[]
{
jobID.ToString(),
jobName.ToString(),
jobStepName.ToString(),
jobMessage.ToString(),
jobStatus.ToString(),
jobRunDate.ToString(),
jobRunTime.ToString(),
};
ListViewItem lvi = new ListViewItem(lviData);
listView1.Items.Add(lvi);
}
rdr.Close();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
// close connection again
_con.Close();
// return _jobs;
}
}
The result did not meet expectations such as the arrangement of the line.
Please suggestion how to do.(using MS Visual Studio 2008 (C#)) Thank you.
And Thank you for your past help.
I don't understand what your problem is, frankly......
Look at the first line in your last screen shot:
Run_Date = 20101122
The first four digits are the year (2010), the next two the month (11 = November), the last two the day (22).
If you look at the run time:
Run_Time = 112001
The first two digits are the hour (11), the next two the minutes (20), the last two the seconds (01).
So this job was last run on Nov 22, 2010, at 11:20:01.
Getting this info is a pretty simple case of a bit of string parsing and manipulation.
So what is causing you problems?? Where are you "blocked" and don't get to the next step??
Continuation of the previous.
I can do that on datagridview it good than use listview. I check for find job fail by use substring and check for last run date and last run time of the job.
public void DisplayList()
{
bool check = true; // true = use oldData
if ((oldData[0] != newData[0]) || ((oldData[0] == newData[0]) && (oldData[6] != newData[6])))
{
check = false; // false = use newData
}
if (!check)
{
string mgs = newData[3];
if (mgs.Substring(8, 1) == "f")
{
for (int j = 0; j < newData.Length; j++)
{
oldData[j] = newData[j];
}
for (int i = 0; i < IDList.Items.Count; i++)
{
if (oldData[0] == IDList.Items[i].ToString().ToLower())
{
dataGridView1.Rows.Add(oldData);
SmsRtb.Text = "The job name is : " + oldData[1] + '\n' + "message: " + oldData[3] + '\n' + "Date: " + oldData[5] + '\n' + "Time: " + oldData[6];
//SendSMS();
}
}
}
}
}
I have application on client for get job info form sql server via ODBC.
Is it possible if I use timer to get job info every 1s and show job info on listview. *i want everything is realtime *
how to do?
private void button1_Click_1(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
listView1.Items.Clear();
GetJobsAndStatus();
}

Categories