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.
Related
To better explain my problem with my personal website project, I would start off with the database that I have created. The table is called guitarItems.
This table is where i get data for displaying images and guitar details in the webpage. In order to do this, I created a method named "GetGuitarItems" to execute and read the sql statements.
public static ArrayList GetGuitarItems(string itemCategory)
{
ArrayList list = new ArrayList();
string query = string.Format("SELECT * FROM guitarItems WHERE brand LIKE '{0}'", itemCategory);
try
{
conn1.Open();
command1.CommandText = query;
SqlDataReader reader = command1.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32(0);
string type = reader.GetString(1);
string brand = reader.GetString(2);
string model = reader.GetString(3);
double price = reader.GetDouble(4);
string itemimage1 = reader.GetString(5);
string itemimage2 = reader.GetString(6);
string description = reader.GetString(7);
string necktype = reader.GetString(8);
string body = reader.GetString(9);
string fretboard = reader.GetString(10);
string fret = reader.GetString(11);
string bridge = reader.GetString(12);
string neckpickup = reader.GetString(13);
string bridgepickup = reader.GetString(14);
string hardwarecolor = reader.GetString(15);
GuitarItems gItems = new GuitarItems(id, type, brand, model, price, itemimage1, itemimage2, description, necktype, body,
fretboard, fret, bridge, neckpickup, bridgepickup, hardwarecolor);
list.Add(gItems);
}
}
finally
{
conn1.Close();
}
return list;
}
Next part is this code where you display the data that you have retrieved from the database.
public partial class Pages_GuitarItems1 : System.Web.UI.Page
{
private string brandType = "Ibanez";
private int x = 0;
protected void Page_Load(object sender, EventArgs e)
{
FillPage();
}
private void FillPage()
{
ArrayList itemList = new ArrayList();
ArrayList itemListPage = new ArrayList();
if (!IsPostBack)
{
itemList = ConnectionClassGuitarItems.GetGuitarItems("%");
}
else
{
itemList = ConnectionClassGuitarItems.GetGuitarItems(brandType);
}
StringBuilder sb = new StringBuilder();
foreach (GuitarItems gList in itemList)
{
itemListPage.Add("GuitarItemsIbanezDetails" + (x + 1) + ".aspx");
sb.Append(
string.Format(
#"
<div class='one-two'>
<a href='{3}' runat='server'><img runat='server' src='{0}'/></a>
<div class='content'>
<div id='label'>{1} {2}</div>
</div>
</div>", gList.ItemImage1, gList.Brand, gList.Model, itemListPage[x]));
x++;
}
lblOutput.Text = sb.ToString();
}
}
Now the problem is its displaying every guitar items in the database. As shown from the code above, what I'm trying to display is only the guitar items with brand "Ibanez" in it. I have my suspicions with the foreach code but atleast for now, the GetGuitarItemsMethod is designed to get only the Ibanez guitar items and the data will be passed on to the ArrayList itemList variable for displaying. And I have also checked the sql statement and it seems correct. Hope you guys can help me on this one.
Change from
if (!IsPostBack)
{
itemList = ConnectionClassGuitarItems.GetGuitarItems("%");
}
else
{
itemList = ConnectionClassGuitarItems.GetGuitarItems(brandType);
}
to
itemList = ConnectionClassGuitarItems.GetGuitarItems(brandType);
Need help to get the 1st row record and return record as string in the << >> after while() loop.
There are a lot of columns in one row, I'm having a problem to declare it as string st? like usually string st = new string() please help to correct it
Thanks
public string Get_aodIdeal(string SubmittedBy)
{
String errMsg = "";
Guid? rguid = null;
int isOnContract = 0;
int isFreeMM = 0;
string _FileName;
DateTime InstallDateTime = DateTime.Now;
string FileDate = ToYYYYMMDD(DateTime.Now);
errMsg = "Unknown Error.";
SqlConnection conn = null; SqlCommand cmd = null;
string st = null;
conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["iDeal"].ConnectionString);
cmd = new SqlCommand();
string SQL = "select TOP 1 * from table1 Order by SubmittedOn desc";
SqlDataAdapter sqd = new SqlDataAdapter(SQL, conn);
cmd.CommandTimeout = 1200;
conn.Open();
SqlDataReader sqr;
//sqd.SelectCommand.Parameters.Add("#Submitted", SqlDbType.Int).Value = PostID;
sqr = sqd.SelectCommand.ExecuteReader();
while (sqr.Read())
st = new string{
rguid = cmd.Parameters["#rguid"].Value as Guid?,
ridno = int.Parse(sqr["ridno"].ToString()),
SubmittedOn= DateTime.Parse(sqr["SubmittedOn"].ToString()),
SubmittingHost = sqr["SubmittingHost"].ToString(),
ServiceAgreementNo = sqr["ServiceAgreementNo"].ToString(),
DocumentID = sqr["DocumentID"].ToString(),
Source = sqr["Source"].ToString(),
FileName = sqr["FileName"].ToString(),
FileType = sqr["FileType"].ToString(),
FileDate = DateTime.Parse(sqr["FileDate"].ToString()),
InstallTime = DateTime.Parse(sqr["InstallTime"].ToString()),
CalenderCode = cmd.Parameters["CalenderCode"].Value as Guid,
isFreeMM = bool.Parse(sqr["isFreeMM"].ToString()),
isOnContract = bool.Parse(sqr["isOnContract"].ToString()),
isProcessed = bool.Parse(sqr["isProcessed"].ToString()),
ProcessedByFullName = sqr["ProcessedByFullName"].ToString(),
isDelete = bool.Parse(sqr["isDelete"].ToString()),
version = int.Parse(sqr["Version"].ToString()),
LastUpdatedBy = DateTime.Parse(sqr["LastUpdatedBy"].ToString()),
LastUpdatedOn = DateTime.Parse(sqr["LastUpdatedOn"].ToString()),
shopGuid = sqr["shopGuid"].ToString(),
MacID = sqr["MacID"].ToString(),
MSISDN = sqr["MSISDN"].ToString()
}
You can use a StringBuilder for this purpose as like the following:
StringBuilder strBuilder= new StringBuilder();
while (sqr.Read())
{
strBuilder.AppendFormat("PostID : {0}{1}",sqr["PostID"].ToString(),Environment.NewLine);
strBuilder.AppendFormat("dateposted : {0}{1}",sqr["dateposted"].ToString(),Environment.NewLine);
// And so on Build your string
}
Finally the strBuilder.ToString() will give you the required string. But More smarter way is Create a Class with necessary properties and an Overrided .ToString method for display the output.
Let AodIdeal be a class with an overrided ToString() method. And Let me defined it like the following :
public class AodIdeal
{
public int PostID { get; set; }
public string dateposted { get; set; }
public string Source { get; set; }
// Rest of properties here
public override string ToString()
{
StringBuilder ObjectStringBuilder = new StringBuilder();
ObjectStringBuilder.AppendFormat("PostID : {0}{1}", PostID, Environment.NewLine);
ObjectStringBuilder.AppendFormat("dateposted : {0}{1}",dateposted, Environment.NewLine);
ObjectStringBuilder.AppendFormat("Source : {0}{1}", Source, Environment.NewLine);
// and so on
return ObjectStringBuilder.ToString();
}
}
Then you can create an object of the class(let it be objAodIdeal), and make use of its properties instead for the local variables. And finally objAodIdeal.ToString() will give you the required output.
Example usage
AodIdeal objAodIdeal= new AodIdeal();
while (sqr.Read())
{
objAodIdeal.PostID = int.Parse(sqr["PostID"].ToString());
objAodIdeal.dateposted= sqr["dateposted"].ToString();
// assign rest of properties
}
string requiredString= objAodIdeal.ToString();
private void getRRvalue(string DELRRNO)
{
try {
DBSFCDataContext SFC = new DBSFCDataContext();
var query = (from i in SFC.POP10500s where i.POPRCTNM == DELRRNO select new { PONO = i.PONUMBER, DATEREC = i.DATERECD, VENDID = i.VENDORID, ITEMCODE = i.ITEMNMBR, QTYBAGS = i.QTYBAGS, QTYSHIP = i.QTYSHPPD, DEPT = i.TRXLOCTN });
foreach (var r in query)
{
string[] row = {
DELRRNO,
r.PONO,
Convert.ToDateTime(r.DATEREC).ToString(),
r.VENDID,
r.ITEMCODE,
r.QTYBAGS.ToString(),
r.QTYSHIP.ToString(),
r.DEPT
};
//glbVariables.getRRNO = ;
//glbVariables.getPONO = ;
//glbVariables.getRRdateRec = ;
//glbVariables.getVendID = ;
//glbVariables.getItemNO = ;
//glbVariables.getQtyBags = ;
//glbVariables.getQtyShipped = ;
//glbVariables.getLocnCode = ;
}
SFC.Connection.Close();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message.ToString()); }
}
I'm new to C#.NET and I was just thinking if I could use a dynamic array like for this code above do I need to declare a global array like this --> "public static string[] row;" so I can use this array string in another form by calling it with the data that I have stored from this function, could this happen in c#?
I need help here please anyone that is good at arrays in c#...
To get you desired results, you will have to do little more work. I explain your solution using List.
First create a class for your one query result:
public class OneRowData
{
public string DELRRNO;
public string PONO;
public string DATEREC;
public string VENDID;
public string ITEMCODE;
public string QTYBAGS;
public string QTYSHIP;
public string DEPT;
}
In your given code, create a List of OneRowData type and make it public static to access it from outside the class as well:
public static List<OneRowData> QueryResults = new List<OneRowData>();
Now in your foreach loop, create an object of OneRowData, assing values to it and add it to the List:
foreach (var r in query)
{
OneRowData Obj = new OneRowData();
//assing values to them
Obj.DATEREC = Convert.ToDateTime(r.DATEREC).ToString();
Obj.DELRRNO = DELRRNO;
Obj.DEPT = r.DEPT;
Obj.ITEMCODE = r.ITEMCODE;
Obj.PONO = r.PONO;
Obj.QTYBAGS = r.QTYBAGS.ToString();
Obj.QTYSHIP = r.QTYSHIP.ToString();
Obj.VENDID = r.VENDID;
//then add the object to your list
QueryResults.Add(Obj);
}
Now you can simply call your List any where and fetch your data like this:
foreach (OneRowData Row in QueryResults)
{
//Row.DATEREC
//Row.DELRRNO
//call them like this and use as you need
}
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);
}
I need to read the values from a variable which is of type object for e..g.., i have a variable called result as:
object result= h[key];
h[key] is a hash table which returns 5 values to result variable. How do I read the 1st value to my local variable of type string in C# script in SSIS package?
I can see only GetType, Equals, ToString() options for result variable.
Any help please?
there is the sample:
there is a sample; public void SQLLoop()
{
string bp,ap,ep,s,vs;
LocationInfo info = new LocationInfo();
string connection = "Server=Sname;Database=Dname;Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT Bp,Ap,EP,SL,VSr from Table1", conn);
SqlDataReader rs=sqlcmd.ExecuteReader();
while (rs.Read())
{
bp = rs.GetValue(0).ToString();
ap = rs.GetValue(1).ToString();
ep = rs.GetValue(2).ToString();
s = rs.GetValue(3).ToString();
vs = rs.GetValue(4).ToString();
info.loadLocationInfo(ap, bp, ep, s, vs);
h.Add(s, info);
}
conn.Close();
}
public class LocationInfo
{
String A;
String B;
String E;
String S;
String V;
int id;
public LocationInfo()
{
}
public void loadLocationInfo(String a,String b,String e,String s,String v)
{
A =a ;
B =b ;
E=e ;
S =s;
V = v;
}
}
now
public void fun1()
{
var result = (object )h[subject];
///read values from the hash table
}
Supposing you know the type of the result you can cast the objectvar result = (MyType) h[key]
EDIT: use this inside your function to get first value var result = ((LocationInfo) h[key]).A
Update:
Ok well you have the LocationInfo class so do something like this:
LocationInfo result = (LocationInfo)h[key];
Then just make some properties on the LocationInfo class to retrieve your strings.
Your probably need to cast the object that is in the hashtable. So something like:
result = (Type)h[key];
Here is an example of how it would work:
Person1 = new Person("David", "Burris");
Person2 = new Person("Johnny", "Carrol");
Person3 = new Person("Ji", "Jihuang");
//The Add method takes Key as the first parameter and Value as the second parameter.
try
{
MyTable.Add(Person1.Lname, Person1);
MyTable.Add(Person2.Lname, Person2);
MyTable.Add(Person3.Lname, Person3);
}
catch (ArgumentException ae)
{
MessageBox.Show("Duplicate Key");
MessageBox.Show(ae.Message);
}
So when you want to retrieve from the table you would do:
Person result = (Person)h[key];
You have to cast result to the class or interface you are expecting.
var result = (IExpectedObject)h[key];