This code(below) suppose to add information to ToolTips which are taken from database(and the class Codons does it(it is the part that actually works)). I tried to do it in FOR loop, but it is warning me about this line:
toolTip1.SetToolTip(Convert.ToString(letter),"Name: "+fullname+" ("+cdn.GetCodon1()+")"
+"\n Begin: "+cdn.GetStart()+", End: "+cdn.GetEnd()+"");
I have 20 buttons which are named in a-z letters, except 6 specific letters(see the IF inside the FOR)
Here is the CODE:
private void UpdateToolTipButton()
{
string fullname;
Codons cdn;
char letter='a';
//get info about every amino acid from database
OleDbConnection dataConnection = new OleDbConnection();
dataConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
dataConnection.Open();
for(int i=1;i<=26;i++,letter++)
{
if((letter!='b')&&(letter!='e' )&& (letter!='j') && (letter!='o')&& (letter!='u') && (letter!='z'))
{
OleDbCommand datacommand = new OleDbCommand();
datacommand.Connection = dataConnection;
datacommand.CommandText = "SELECT tblCodons.codonsFullName"
+" FROM tblCodons"
+" WHERE tblCodons.codonsCodon1="+letter;
OleDbDataReader dataReader = datacommand.ExecuteReader();
dataReader.Read();
fullname = dataReader.GetString(0);
cdn = new Codons(fullname);
toolTip1.SetToolTip(Convert.ToString(letter),"Name: "+fullname+" ("+cdn.GetCodon1()+")"
+"\n Begin: "+cdn.GetStart()+", End: "+cdn.GetEnd()+"");
}
}
}
SetToolTip is looking for a control as the first argument. You are supplying Convert.ToString(letter).
The first argument needs to be the button you want to have the tooltip:
toolTip1.SetToolTip(button1, "Name: " + fullname);
I'm guessing you were trying to set the title of the ToolTip, in which case, that's not part of the SetToolTip method. You would have to set the property yourself:
toolTip1.ToolTipTitle = Convert.ToString(letter);
If your buttons are those letters, then you would reference them by their name as the control key:
if (this.Controls.ContainsKey(Convert.ToString(letter))) {
toolTip1.SetToolTip(this.Controls[Convert.ToString(letter)], "Name: " + fullname + " etc(";
}
You shouldn't open a new reader for every item, you were also missing single quotes around an item in the where clause, but the where clause isn't necessary anyway \(^_^)_/
anyway, this is my Solution.
private char _letter;
private string _fullName;
public char Letter{
get{
return _letter;
}
set{
_letter = value;
}
}
public string FullName{
get{
return _fullName;
}
set{
_fullName = value;
}
}
Private Void UpdateToolTipButton(){
string fullname;
codons cdn;
char letter;
OleDbConnection iConnect = new OleDbConnection();
iConnect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=#"C:\Projects_2012\Project_Noam\Access\myProject.accdb";
OleDbCommand iCommand = new OldDbCommand("Select * from tblCodons",iConnect);
List<YourClassName> iList = new List<YourClassName>();
OleDbDataReader iRead = null;
iRead = iCommand.ExecuteReader();
while(iRead.Read()){
YourClassName iClass = new YourClassName();
iClass.Letter = Convert.ToChar(iRead["codonsCodon1"]);
iClass.FullName = Convert.ToString(iRead["codonsFullName"]);
iList.Add(iClass);
}
iConnect.Close();
iRead.Close();
foreach(var VarName in iList)
{
toolTip1.SetToolTip(button1, "Name: " + var.FullName);
toolTip1.ToolTipTitle = var.Letter;
}
}
If I got it right, your Form has multiple buttons, with their Text properties set to letters a-z. the problem is that SetToolip needs the control (button) as its first parameter in order to set its tooltip, but you are passing button's text value instead.
Your loop should be arranged into something like this, so that you can iterate through actual buttons:
foreach (var button in GetButtons())
{
if (ShouldSetTooltip(button))
{
// ...
tooltip.SetTooltip(button, text);
}
}
To get all buttons placed in your form (or on a panel), you can use something like:
private IEnumerable<Button> GetButtons()
{
// this is where you decide which buttons to return
foreach (var c in this.Controls) // or panel1.Controls
if (c is Button)
yield return (Button)c;
}
And then you will probably need to add your check to skip certain button names:
private bool ShouldSetTooltip(Control c)
{
string[] lettersToSkip = new string[] { "b","e","o","u","j","z" };
return lettersToSkip.Contains(c.Text) == false;
}
[Edit]
If you want to get the control by its Name property (note: this is not the same as the Text property), you can use you loop and write it like this:
for (int i = 1; i <= 26; i++, letter++)
{
...
var button = this.Controls[letter.ToString()];
var txt = "Name: "+fullname+" ("+cdn.GetCodon1()+")"
+"\n Begin: "+cdn.GetStart()+", End: "+cdn.GetEnd()+"";
toolTip1.SetToolTip(button, txt);
}
Related
I have a listbox with a list of items that get loaded when you navigate to a certain page. Then I have an on click that passes parameters to an AddProducts method. That method is what loops through all selected items and inserts values from the fields filled in as well as takes the values from the listItems and adds them as parameters to a stored procedure.
The problem I'm running into is that when looping through the listItems
if(selectedItem.Selected) is returning false, but in my method where I load the listbox I initialize a SelectedValue so I'm not sure why it's giving me the error message I have for no selected items. I was able to get it to work yesterday before I moved LoadListBoxCategories outside of LoadAddData but unsure as to why that would have any effect to if(listItem.Selected).
I'm relatively new to asp.net so any help/ explanation as to why my code isn't working is extremely appreciated. I've spent the last three days trying to figure this out and haven't found a solution that works.
Code:
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session[IS_LOGGED_IN] == null)
{
Response.Redirect("/utilities/companydata/login.aspx", true);
return;
}
gvTextInputs.RowEditing += new GridViewEditEventHandler(gvTextInputs_RowEditing);
if (!IsPostBack)
{
string pageId = Request.QueryString["pageid"];
string productId = Request.QueryString["productid"];
/* Add Mode */
if (!string.IsNullOrEmpty(pageId))
{
SetMode(MODE_ADD, "");
LoadAddData(pageId);
LoadListBoxCategories(pageId);
}
else if (!string.IsNullOrEmpty(productId))
{
string imageServer;
if (LoadProductData(productId, out imageServer))
{
InitImageGridview();
InitTextGridview();
InitStaticGridview();
SetMode(MODE_EDIT, imageServer);
SetImageServer(imageServer);
}
else
{
//TO DO - Return Error
}
}
}
else
{
InitImageGridview();
InitTextGridview();
InitStaticGridview();
}
}
Load ListBox:
private void LoadListBoxCategories(string pageId)
{
listBoxCategories.Visible = true;
//This gets query is so I can store the CompanyId and the CombinedValue data from pageId
string select = "SELECT companyName, cl.GbsCompanyId, cl.companyId, wpt.productTypeId, productName, (CAST(wp.pageId as varchar(200)) +'|'+ CAST(wp.productTypeId as varchar(200)) + '|' ) AS CombinedValue FROM CompanyList cl, WtpPages wp, WtpProductTypes wpt WHERE cl.companyId=wp.companyId AND wpt.productTypeId=wp.productTypeId AND wp.pageId=#pageId";
SqlDataSource connectionId = new SqlDataSource(DB_CONNECT, select);
connectionId.SelectParameters.Add("pageId", pageId);
DataView dView = (DataView)connectionId.Select(DataSourceSelectArguments.Empty);
if (dView.Table.Rows.Count == 1)
{
string companyId = dView.Table.Rows[0]["companyId"].ToString();
string curCategoryProductTypeId = dView.Table.Rows[0]["CombinedValue"].ToString();
// EXEC MCAdmin_GetAllCategoriesByCompanyId #companyId
// Lists All Categories #companyId has Active
string selectLoadData = "EXEC MCAdmin_GetAllCategoriesByCompanyId #companyId";
SqlDataSource conn = new SqlDataSource(DB_CONNECT, selectLoadData);
conn.SelectParameters.Add("companyId", companyId);
lstCategoriesBox.Items.Clear();
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
// Pre-selects the value of the productTypeId you are trying to add a product for
// to send later run against a foreach insert in AddProduct()
lstCategoriesBox.SelectedValue = curCategoryProductTypeId;
testOutcomeCategory.InnerText = curCategoryProductTypeId;
lstCategoriesBox.DataSource = conn;
lstCategoriesBox.DataBind();
}
}
AddProduct:
private string AddProduct(string companyId, out string errMsg)
{
foreach (ListItem selectedItem in lstCategoriesBox.Items)
{
if (selectedItem.Selected)
{
// assign current productTypeId & pageId from selected Categories new CombinedValue column
string[] splitColumnValue = selectedItem.Value.Split('|');
string selectedPageId = splitColumnValue[0].ToString();
string selectedProductTypeId = splitColumnValue[1].ToString();
SqlDataSource connnection = new SqlDataSource(DB_CONNECT, "");
connnection.InsertCommand = "EXEC MCAdmin_AddProductFromClassic #pageId, #productTypeId, #productCode, #imgDirectory, #numSides, #sortOrder, #isActive, #template, #template2, #template3, #EditorJson, #MockupTemplateBase, #MockupTemplateTreatment, #BorderDefault ";
connnection.InsertParameters.Add("pageId", selectedPageId);
connnection.InsertParameters.Add("productTypeId", selectedProductTypeId);
connnection.InsertParameters.Add("productCode", txtProductCode.Text);
connnection.InsertParameters.Add("numSides", ddlNumSides.SelectedValue);
connnection.InsertParameters.Add("sortOrder", txtSortOrder.Text);
connnection.InsertParameters.Add("isActive", ddlActive.SelectedValue);
connnection.InsertParameters.Add("template", txtTemplate1.Text);
connnection.InsertParameters.Add("template2", txtTemplate2.Text);
connnection.InsertParameters.Add("template3", txtTemplate3.Text);
connnection.InsertParameters.Add("EditorJson", txtJson.Text);
connnection.InsertParameters.Add("MockupTemplateBase", txtMockupTemplateBase.Text);
connnection.InsertParameters.Add("MockupTemplateTreatment", txtMockupTemplateTreatment.Text);
connnection.InsertParameters.Add("BorderDefault", txtBorderDefault.Text);
/* Special Product Code for Upload Artwork Business Card */
if (txtProductCode.Text.ToUpper() == "BPFAH1-001-100")
{
connnection.InsertParameters.Add("imgDirectory", "/images/business-cards/general/");
}
else
{
connnection.InsertParameters.Add("imgDirectory", ddlImgDir.SelectedValue);
}
int result = connnection.Insert();
if (result > 0)
{
SqlDataSource connect = new SqlDataSource(DB_CONNECT, "");
connect.SelectCommand = "SELECT TOP 1 wtpProductId FROM WtpProducts ";
connect.SelectCommand = "WHERE productTypeId=#productTypeId AND pageId=#pageId DESC ";
connect.SelectParameters.Add("pageId", selectedPageId); //
connect.SelectParameters.Add("productTypeId", selectedProductTypeId); //
DataView dView = (DataView)connect.Select(DataSourceSelectArguments.Empty);
if (dView.Table.Rows.Count == 1)
{
string wtpProductId = dView.Table.Rows[0]["wtpProductId"].ToString();
errMsg = "";
return wtpProductId;
}
else
{
errMsg = "ERROR: Could not get productId of newly created Product.";
return "0";
}
}
else
{
errMsg = "ERROR: Could not add WtpProduct record to DB";
return "0";
}
}
else
{
errMsg = "ERROR: You must select a Category";
return "0";
}
}
errMsg = "ERROR: Did not make it into the foreach loop";
return "0";
}
OnClick method:
protected void OnClick_btnAddProduct(object sender, EventArgs e)
{
string pageId = Request.QueryString["pageid"];
testOutcomeCategory.InnerText = lstCategoriesBox.SelectedValue; // This proves that I have something selected!!!
string select = "SELECT companyName, cl.GbsCompanyId, cl.companyId, wpt.productTypeId, productName, baseImgDirectory, templateDirectory, wp.imageServer FROM CompanyList cl, WtpPages wp, WtpProductTypes wpt WHERE cl.companyId=wp.companyId AND wpt.productTypeId=wp.productTypeId AND wp.pageId=#pageId";
SqlDataSource conn = new SqlDataSource(DB_CONNECT, select);
conn.SelectParameters.Add("pageId", pageId);
DataView dView = (DataView)conn.Select(DataSourceSelectArguments.Empty);
if(dView.Table.Rows.Count == 1)
{
string companyId = dView.Table.Rows[0]["companyId"].ToString();
if (!string.IsNullOrEmpty(pageId))
{
string errMsg;
string productId = AddProduct(companyId, out errMsg);
if(productId != "0")
{
Response.Redirect("/utilities/companydata/add-edit-wtp-product.aspx?productid=" + productId, true);
SetStatusMsg("Success", false);
}
else
{
SetStatusMsg(errMsg, true);
}
}
}
}
The list box instance is recreated on the server-side during the postback (as well as entire page). You do not set the selected items in the Page_Load event handler - if (!IsPostBack) goes to else branch. This is why you don't see them.
Ok,
lstCategoriesBox.Items.Clear();
Ok, above goes nuclear - blows out the list, blows out the selection.
Ok, that's fine
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
Ok, above adds a new item. Should be ok, but one should setup the lb BEFORE adding any data - including that "--select--" row.
It just makes sense to "setup" the lb and THEN start adding data, right?
However, But, if above works - ok, then lets keep going, but I would setup the lb before adding any rows of data. Say like this:
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
Now, the next line:
lstCategoriesBox.SelectedValue = curCategoryProductTypeId;
Ouch! - we just cleared the lb, and now we trying to set it to a value? You can't do that - the lb just been cleared, right? You would need to load up the lb first, and THEN you can set it to the selected value, right?
I might be missing something here, but that lb needs to be loaded up with valid data BEFORE you attempt to set the selected value?
To test first, change following
Outcome Category.InnerText = list CategoriesBox.SelectedValue;
to
Category.InnerText = Request.Form["CategoriesBox-ClientID"]
If the data is coming in correctly, the list view cleared or reloaded when between reload and click events the page.
UPDATE: I just figured it out! So stupid but when I check if(selectedItem.Selected) since I'm looping through the ListBox items it starts at the first index of the ListBox and since the first isn't selected then that if goes to the else block. Remove the else and it works fine
I have a table and one of the column is YesNo which is of type varchar(3). I have two radio buttons in my PDF file which is in an array:
pg1rb (radio group field)
--> c1 (radio button one (yes))
--> c2 (radio button two (no))
I set textboxes like this in my code:
formFieldMap["topmostSubform[0].Page1[0].f1_01_0_[0]"] = reader.GetValue(0).ToString();
How can I select YES or NO radio button based on the row value?
Can I do something like this:
formFieldMap["pg1rb"] = reader.GetBoolean(10); //10 is the 9th column which is Yes/No value
Or do I get the value and based on it select the radio button, something like this:
if (reader.GetValue(10).ToString() == "Yes") {
formFieldMap["pg1rb"][c1] = "1";
else {
formFieldMap["pg1rb"][c2] = "1";
}
My SQL table:
I am trying to follow this site: Website example
My function that actually does the conversion:
public void writeData(string k, string c)
{
Conn = new SqlConnection(cString);
Conn.Open();
//MessageBox.Show(k);
//MessageBox.Show(c);
var pdfPath = Path.Combine(Server.MapPath("~/PDFTemplates/forme.pdf"));
// Get the form fields for this PDF and fill them in!
var formFieldMap = PDFHelper.GetFormFieldNames(pdfPath);
//if more than multiple entries, verify by name and the last four ssn
sqlCode = "SELECT * FROM [DSPCONTENT01].[dbo].[TablePDFTest] WHERE [name] = '" + k + "' AND [ssn3] = " + c + "";
//sqlCode = "SELECT * FROM [DSPCONTENT01].[dbo].[TablePDFTest] WHERE [name] = #name2 AND [ssn3] = #ssnnum";
//MessageBox.Show("" + sqlCode.ToString());
using (SqlCommand command = new SqlCommand(sqlCode, Conn))
{
command.CommandType = CommandType.Text;
//command.Parameters.AddWithValue("name2", k);
//command.Parameters.AddWithValue("ssnnum", c);
using (reader = command.ExecuteReader())
{
if (reader.HasRows)
{
if (reader.Read())
{
//MessageBox.Show(reader.GetValue(0).ToString());
/*formFieldMap["topmostSubform[0].Page1[0].f1_01_0_[0]"] = reader.GetValue(0).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_02_0_[0]"] = reader.GetValue(1).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_04_0_[0]"] = reader.GetValue(2).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_05_0_[0]"] = reader.GetValue(3).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_07_0_[0]"] = reader.GetValue(4).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField1[0]"] = reader.GetValue(5).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[0]"] = reader.GetValue(6).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[1]"] = reader.GetValue(7).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[2]"] = reader.GetValue(8).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[3]"] = reader.GetValue(9).ToString();*/
if (reader.GetValue(10).ToString() == "Yes")
{
//MessageBox.Show("YES");
}
else if (reader.GetValue(10).ToString() == "No")
{
//MessageBox.Show("NO");
}
}
}
}
}
// Requester's name and address (hard-coded)
formFieldMap["topmostSubform[0].Page1[0].f1_06_0_[0]"] = "Medical Group\n12 Westchester Ave\nPurchase, NY 10121";
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
PDFHelper.ReturnPDF(pdfContents, "Completed-W9.pdf");
}
The PDFHelper class:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.IO;
using iTextSharp.text.pdf;
public class PDFHelper
{
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields)
fields.Add(entry.Key.ToString(), string.Empty);
reader.Close();
return fields;
}
public static byte[] GeneratePDF(string pdfPath, Dictionary<string, string> formFieldMap)
{
var output = new MemoryStream();
var reader = new PdfReader(pdfPath);
var stamper = new PdfStamper(reader, output);
var formFields = stamper.AcroFields;
foreach (var fieldName in formFieldMap.Keys)
formFields.SetField(fieldName, formFieldMap[fieldName]);
stamper.FormFlattening = false;
stamper.Close();
reader.Close();
return output.ToArray();
}
// See http://stackoverflow.com/questions/4491156/get-the-export-value-of-a-checkbox-using-itextsharp/
public static string GetExportValue(AcroFields.Item item)
{
var valueDict = item.GetValue(0);
var appearanceDict = valueDict.GetAsDict(PdfName.AP);
if (appearanceDict != null)
{
var normalAppearances = appearanceDict.GetAsDict(PdfName.N);
// /D is for the "down" appearances.
// if there are normal appearances, one key will be "Off", and the other
// will be the export value... there should only be two.
if (normalAppearances != null)
{
foreach (var curKey in normalAppearances.Keys)
if (!PdfName.OFF.Equals(curKey))
return curKey.ToString().Substring(1); // string will have a leading '/' character, so remove it!
}
}
// if that doesn't work, there might be an /AS key, whose value is a name with
// the export value, again with a leading '/', so remove it!
var curVal = valueDict.GetAsName(PdfName.AS);
if (curVal != null)
return curVal.ToString().Substring(1);
else
return string.Empty;
}
public static void ReturnPDF(byte[] contents)
{
ReturnPDF(contents, null);
}
public static void ReturnPDF(byte[] contents, string attachmentFilename)
{
var response = HttpContext.Current.Response;
if (!string.IsNullOrEmpty(attachmentFilename))
response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
response.ContentType = "application/pdf";
response.BinaryWrite(contents);
response.End();
}
}
Your question was confusing because it used a reader object that didn't refer to iTextSharp's PdfReader class and it used a formFieldMap object of which the type was unknown (it doesn't seem related to iTextSharp). Your edit was very welcome to understand the question.
The field names you mention look as if they are fields in an XFA form, but the article you refer to talks about filling out AcroForm documents, so let's assume that your form was indeed born as an XFA form, but later on converted to an AcroForm.
In this case, nobody will be able to tell you which values to pick to set the radio buttons without seeing the PDF. Please download chapter 6 of my book and read section 6.3.5, more specifically where it says Inspecting the form and its fields. On page 183, you can read that the possible values for a group of radio buttons is either "Off"–no radio button is selected— or a code that is defined in the form itself.
For instance: in the example from the book, the possible values for the category group were spec, toro, anim, etc...
This means that you can set a radio box in that group like this:
formFields.SetField("category", "spec");
or:
formFields..SetField("category", "toro");
or:
formFields.SetField("category", "anim");
and so on.
So, if you want to set a radio button in a radiogroup named pg1rb, you first need to know which are the possible values. You assume that the possible values are "Yes" and "No" in which case you could use:
formFields.SetField("pg1rb", "Yes");
or
formFields.SetField("pg1rb", "No");
But the possible values could also be "1" and "0", "On" and "Off", "true" and "false",... The possible values were chosen by the person who created the form.
You can get these values programmatically by using the code from page 182:
StringBuilder sb = new StringBuilder();
sb.Append("Possible values for pg1rb:");
sb.Append(Environment.NewLine);
states = form.GetAppearanceStates("pg1rb");
for (int i = 0; i < states.Length - 1; i++) {
sb.Append(states[i]);
sb.Append(", ");
}
sb.Append(states[states.Length - 1]);
Inspect what was written to the sb object and you have the values you are looking for.
I'm trying to change several button images according to what state I get in the database.
If I get any state "0" I should change the button image to a "busy" image, since the default image is a "free" one.
So my question is: How can i change a button through a variable name?
I have this code for now(i know its wrong):
private void checkSuites()
{
SqlCeCommand checkSuite = new SqlCeCommand("SELECT * FROM RentSessionLog WHERE State='0'", mainConnection);
SqlCeDataReader readSuite = checkSuite.ExecuteReader();
int suiteIndex;
string suitePath = "suite" + suiteIndex;
while (readSuite.Read())
{
suiteIndex = Convert.ToInt32(readSuite["SuiteNum"]);
suitePath.Image = NewSoftware.Properties.Resources.busySuiteImg;
}
}
It's as simple as:
while (readSuite.Read())
{
suiteIndex = Convert.ToInt32(readSuite["SuiteNum"]);
switch(suiteIndex)
{
case 0:
{
suitePath.Image = NewSoftware.Properties.Resources.busySuiteImg;
break;
}
default:
{
suitePath.Image = NewSoftware.Properties.Resources.freeSuiteImg;
}
}
}
Edit:
The reason I used a switch is in case you have other-states appearing in the future. You have "Busy" and "Free", but there could be "Reserved" as well and you may want to have further conditions that would just get obfuscated in a simple if else if sequence.
I believe you need to use this.Controls.Find(suitePath, true) to turn your string into a control. I am presuming that "suite" + suiteIndex is the .Name of each of your buttons.
string suitePath = "suite" + suiteIndex;
Button suiteButton = this.Controls.Find(suitePath, true);
suiteButton.Image = ...
See more details about Controls.Find
Alternatively for quicker access, you may want to keep a Dictionary<int, Control> with each of your buttons in it.
I DID IT! Using a dictionary as Thymine said:
public void checkSuites()
{
Dictionary<int, Control> btnList = new Dictionary<int, Control>();
btnList.Add(1, suite1);
btnList.Add(2, suite2);
btnList.Add(3, suite3);
btnList.Add(4, suite4);
btnList.Add(5, suite5);
SqlCeCommand checkSuite = new SqlCeCommand("SELECT * FROM RentSessionLog WHERE State='0'", mainConnection);
SqlCeDataReader readSuite = checkSuite.ExecuteReader();
while (readSuite.Read())
{
int suiteIndex = Convert.ToInt32(readSuite["SuiteNum"]);
string suitePath = "suite" + suiteIndex;
foreach (Button key in btnList.Values)
{
if (key.Name == suitePath)
{
key.Image = NewSoftware.Properties.Resources.busySuiteImg;
}
}
}
}
Thank you all who helped :D
I have a routine that populates a combobox from a database; the first time the combo is populated, it all works perfectly, but if I try to do it again, the combobox is completely blank. I narrowed it down to this line:
cboThis.DataSource = cboThis.Items;
This seems to clear the Items collection for the combobox...but only if the combo was already populated.
Any ideas what could be going on here?
There IS an event handler for one of the combo's SelectedIndexChanged event, but this doesn't seem to get called by anything but the first and last lines of code.
Here's the complete routine:
public void ComboFromDB(ComboBox cboThis, string strTable, string strField)
{
cboThis.SelectedIndex = -1;
cboThis.DataSource = null;
cboThis.Items.Clear();
string strQuery = #"SELECT ID, " + strField + " FROM " + strTable;
using (SqlConnection sqcConnection = new SqlConnection(strConnection))
{
sqcConnection.Open();
SqlCommand sqcCommand = new SqlCommand(strQuery, sqcConnection);
SqlDataReader dr = sqcCommand.ExecuteReader();
while (dr.Read())
{
cboThis.Items.Add(new ComboItem((int)dr[0], dr[1].ToString())); //this all works fine
}
}
cboThis.DataSource = cboThis.Items; //This line clears cboThis.Items...
cboThis.ValueMember = "ID";
cboThis.DisplayMember = "Display";
cboThis.SelectedIndex = -1;
}
Cheers
try to create a structure like this
struct tmpItems
{
//member variables
private Int32 _ID;
private String _Display;
//properties
public Int32 ID
{
get {return _ID;}
}
public String Display
{
get {return _Display;}
}
public tmpItems(Int32 pID , String pDisplay)
{
_ID = pID;
_Display = pDisplay;
}
}
now assign
ArrayList dataItems = new ArrayList();
dataItems.Add(new tmpItems((int)dr[0], dr[1].ToString()));
then finally set
cbothis.DataSource = dataItems;
cboThis.ValueMember = "ID";
cboThis.DisplayMember = "Display";
Ensure that ComboBox SelectedIndexChange event handles the Initialization of data..
because while setting datasource , the items will be added one by one.. each time generating SelectedIndexChangeEvent .. but will find difficult in accessing SelectedValue property at this stage
In the end I binned using Items and just shoved it through a Dictionary.
public void Button1_Click(object sender, EventArgs e)
{
String a = DropDownList1.SelectedItem.Value;
String b = DropDownList3.SelectedItem.Value.PadLeft(3, '0');
String c = TextBox1.Text.PadLeft(5, '0').ToString();
String d = TextBox2.Text.ToString();
String digit = a + b + c + d;
try
{
OdbcConnection casetype = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
casetype.Open();
//************to get case type
string casetypequery = "select casename from casetype where skey=?";
//************to get case type
OdbcCommand casetypecmd = new OdbcCommand(casetypequery, casetype);
String casetypefromdropdown = DropDownList3.SelectedItem.ToString();
casetypecmd.Parameters.AddWithValue("?", casetypefromdropdown);
using (OdbcDataReader casetypeMyReader = casetypecmd.ExecuteReader())
{
while (casetypeMyReader.Read())
{
String casename = casetypeMyReader["casename"].ToString();
}
}
}
catch (Exception ewa)
{
Response.Write(ewa);
}
I am not able to access
String casename = casetypeMyReader["casename"].ToString();
which is inside while loop in my above code.
How can i access
'casename'
outside while loop?i want to use it to put the content in HtmlEditor(ajax)
If you want to access the variable outside the loop you need to declare it outside:
string casename = "some default value";
while (casetypeMyReader.Read())
{
casename = casetypeMyReader["casename"].ToString();
}
// You can access casename here and it's value will either be the default one
// if the reader returned no rows or the last row being read.
You could declare an Array or List of strings outside the loop, and save the casename values in that.
List<string> caseNames = new List<string>();
while (casetypeMyReader.Read())
{
caseNames.Add(casetypeMyReader["casename"].ToString());
}
Now they're all in the array and you can access it wherever.
If there are duplicates, and you need unique values, you can do caseNames.Distinct().ToList() afterwards.