I have read some threads that seem to be similar to this but can't find the fix for my issue, I've not used stack overflow much so pls bear with me
I have a while loop using an SqlDataReader which is pulling information from a DB and putting it into a List for Development Requests as below
public ListOfDevelopmentRequestsModel GetDevRequests(List<SelectListItem> evaluators)
{
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetDevRequests, Conn);
cmd.CommandType = CommandType.StoredProcedure;
ListOfDevelopmentRequestsModel ListOfDevRequests = new ListOfDevelopmentRequestsModel();
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
DateTime requestDate = Convert.ToDateTime(reader["DateCreated"].ToString());
string requestorFirstName = reader["Staff First Name"].ToString();
string requestorLastName = reader["Staff Last Name"].ToString();
string requestorEmailAddress = reader["Staff Email"].ToString();
string solutionName = reader["SolutionName"].ToString();
string solutionDescription = reader["SoultionDescription"].ToString();
string solutionElementName = reader["SolutionElementName"].ToString();
string solutionElementDescription = reader["SolutionElementDescription"].ToString();
string itemToChange = reader["ItemChange"].ToString();
string changeDetails = reader["ChangeDetail"].ToString();
List<SelectListItem> evaluatorList = new List<SelectListItem>(DisplayCurrentEvaluator(evaluators, evaluator));
DevelopmentRequestModel DevRequest = new DevelopmentRequestModel
{
RequestDate = requestDate,
RequestorName = $"{requestorFirstName} {requestorLastName}",
RequestorEmailAddress = requestorEmailAddress,
SolutionName = solutionName,
SolutionDescription = solutionDescription,
SolutionElementName = solutionElementName,
SolutionElementDescription = solutionElementDescription,
ItemToChange = itemToChange,
ChangeDetails = changeDetails,
AccordionHeading = $"{(changeID.PadLeft(4, '0'))} - {requestorFirstName} {requestorLastName} - {itemToChange}"
};
ListOfDevRequests.DevelopmentRequests.Add(DevRequest);
}
Conn.Close();
return ListOfDevRequests;
}
I also have a List for getting Evaluators of the requests
public static List<SelectListItem> GetEvaluators()
{
List<SelectListItem> evaluators = new List<SelectListItem>();
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetEvaluators, Conn);
cmd.CommandType = CommandType.StoredProcedure;
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
evaluators.Add(
new SelectListItem
{
Text = reader["Staff Name"].ToString(),
Value = reader["Staff Code"].ToString(),
});
}
Conn.Close();
return evaluators;
}
Finally I have a List that will pass the above Evaluators List in and the Evaluator that was pulled from the DB: string evaluator = reader["Evaluator"].ToString(); and will set the default value of the select list based on whether the Evaluator name matches the Text value, and set it as the selected select list item.
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
foreach (var item in evaluators)
{
if (item.Text == evaluator)
{
item.Selected = true;
}
else
{
item.Selected = false;
}
}
return evaluators;
}
The issue is that the first item in the loop has the Evaluator "Bill" and "Bill" is selected, and works fine, however the second item in the loop is "John", and when it sets "John" to selected, it replaces "Bill" as the selected value in the first item with "John"
The code has ended up a mess as I have tried multiple different ways to fix but I'm stumped and would appreciate help.
Sorry if the post is formatted poorly to read, I can try to reformat and provide more information if requested.
Cheers
EDITED CODE:
GetDevRequests()
public ListOfDevelopmentRequestsModel GetDevRequests(List<SelectListItem> evaluators)
{
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetDevRequests, Conn);
cmd.CommandType = CommandType.StoredProcedure;
ListOfDevelopmentRequestsModel ListOfDevRequests = new ListOfDevelopmentRequestsModel();
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
List<SelectListItem> evaluatorList = new List<SelectListItem>();
while (reader.Read())
{
string changeID = reader["ChangeID"].ToString();
string evaluator = reader["Evaluator"].ToString();
string status = reader["Status"].ToString();
string priority = reader["Priority"].ToString();
string eliteID = reader["RequestorID"].ToString();
DateTime requestDate = Convert.ToDateTime(reader["DateCreated"].ToString());
string requestorFirstName = reader["Staff First Name"].ToString();
string requestorLastName = reader["Staff Last Name"].ToString();
string requestorEmailAddress = reader["Staff Email"].ToString();
string solutionName = reader["SolutionName"].ToString();
string solutionDescription = reader["SoultionDescription"].ToString();
string solutionElementName = reader["SolutionElementName"].ToString();
string solutionElementDescription = reader["SolutionElementDescription"].ToString();
string itemToChange = reader["ItemChange"].ToString();
string changeDetails = reader["ChangeDetail"].ToString();
evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);
DevelopmentRequestModel DevRequest = new DevelopmentRequestModel
{
ChangeID = (changeID.PadLeft(4, '0')),
Evaluator = evaluator,
Evaluators = evaluatorList,
Status = status,
Priority = priority,
EliteID = eliteID,
RequestDate = requestDate,
RequestorName = $"{requestorFirstName} {requestorLastName}",
RequestorEmailAddress = requestorEmailAddress,
SolutionName = solutionName,
SolutionDescription = solutionDescription,
SolutionElementName = solutionElementName,
SolutionElementDescription = solutionElementDescription,
ItemToChange = itemToChange,
ChangeDetails = changeDetails,
AccordionHeading = $"{(changeID.PadLeft(4, '0'))} - {requestorFirstName} {requestorLastName} - {itemToChange}"
};
ListOfDevRequests.DevelopmentRequests.Add(DevRequest);
}
Conn.Close();
return ListOfDevRequests;
}
DisplayCurrentEvaluator()
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> selectListItems, string selectListDefaultItem)
{
foreach (var item in selectListItems)
{
item.Selected = item.Text == selectListDefaultItem;
}
return selectListItems;
}
The problem is in this line:
List<SelectListItem> evaluatorList = new List<SelectListItem>(DisplayCurrentEvaluator(evaluators, evaluator));
First, this can also be written as
List<SelectListItem> evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);
Your DisplayCurrentEvaluator already returns a correct list, so there is no need to copy it into a new one.
But this is a minor point as you don't use that evaluatorList as far as I can see. In every iteration of that while-loop you are creating a new one (which probably isn't what you want) and then you forget about it. I also don't see where evaluator is set, but that is probably in code you didn't show.
So you will need to generate this list once, outside the loop and keep it (probably in a class-level field or property).
And an extra tip, that DisplayCurrentEvaluator method can also be written as
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
foreach (var item in evaluators)
{
item.Selected = item.Text == evaluator;
}
return evaluators;
}
EDIT after code was shown that set evaluator and used the resulting evaluatorList
Your DisplayCurrentEvaluator updates the original evaluators list and returns it. This effectively results in every evaluatorList pointing to the same list, where the last update wins. So make sure you return a new list.
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
var result = new List<SelectListItem>(evaluators.Count);
foreach (var item in evaluators)
{
result.Add(new SelectListItem { Text = item.Text, Value = item.Value, Selected= item.Text == evaluator};
}
return result;
}
Additionally, declare the evaluatorList (only) inside of the loop.
var evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);
Related
How to change decimal separator in string, e.g. in mnoz_obj item the returned value is 24,000 and I need to have 24.000. The values are from database to JSON.
I tried ToString(new CultureInfo etc.) but this doesn't work. I expect that myString.Replace(",",".") is not correct way to do it.
public static string getDoklad()
{
var dbCon = ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
string[] fileArguments = Environment.GetCommandLineArgs();
List<ZebraPolozky> zebraPolozky = new List<ZebraPolozky>();
using (var cn = new OdbcConnection(dbCon))
{
OdbcCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT * FROM cis06zebrap";
cn.Open();
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
ZebraPolozky zebraPolozka = new ZebraPolozky
{
doklad = reader["doklad"].ToString(),
sklad = reader["sklad"].ToString(),
reg = reader["reg"].ToString(),
mnoz_obj = reader["mnoz_obj"].ToString(),
mnoz_vyd = reader["mnoz_vyd"].ToString(),
kc_pce = reader["kc_pce"].ToString(),
sarze = reader["sarze"].ToString(),
datspo = reader["datspo"].ToString(),
veb = reader["veb"].ToString(),
poc2 = reader["poc2"].ToString(),
pvp06pk = reader["pvp06pk"].ToString(),
znacky = reader["znacky"].ToString(),
stav = reader["stav"].ToString(),
//prac = reader["prac"].ToString(),
//exp = reader["exp"].ToString()
};
zebraPolozky.Add(zebraPolozka);
}
}
}
cn.Close();
}
//var collw = new { polozky = zebraPolozky };
var jsonString = JsonConvert.SerializeObject(zebraPolozky);
return jsonString;
}
{
"doklad": "568375",
"sklad": "901",
"reg": "185121",
"mnoz_obj": "24,000",
"mnoz_vyd": "0,000",
"kc_pce": "240,72",
"sarze": "",
"datspo": "",
"veb": "24,00",
"poc2": "1",
"pvp06pk": "116783437",
"znacky": "R1902",
"stav": "0"
}
OdbcDataReader gives the value in its native format as stated in the doc.
You should then be able to cast it and use the overload of .ToString() you need.
Try something like:
((decimal)reader["mnoz_obj"]).ToString("N2")
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);
i have added multiple values to an array using 3 different classes that i have created when i use the foreach loop i only get the values from the first class is there any way to use foreach on multiple classes?
AdvertDao advert = new AdvertDao();
var array = new ArrayList();
array = advert.fillAdvert();
foreach (Member m in array)
{
txtBoxEmail.Text = m.Email;
txtBoxPhone.Text = m.Phone.ToString();
txtBoxUsername.Text = m.Username;
}
foreach (Consoles c in array)
{
cmbConsole.Text = c.ConsoleName;
}
foreach (Advert a in array)
{
cmbGenre.Text = a.Genre;
lblDateStarted.Text = a.Date.ToString("dd/MM/yyyy");
txtBoxPrice.Text = a.Price.ToString();
txtBoxName.Text = a.Name;
txtBoxDesc.Text = a.Description;
}
fillAdvert() method:
public ArrayList fillAdvert()
{
Member member = new Member();
Advert advert = new Advert();
Consoles console = new Consoles();
Picture picture = new Picture();
ArrayList advertList = new ArrayList();
if (!DatabaseConnection.IsOpen)
{
DatabaseConnection.Open();
}
OracleCommand cmd = new OracleCommand();
cmd.Connection = DatabaseConnection.Connection;
string str = "SELECT * FROM ADVERT_ADPIC_MEMBER_CONSOLE WHERE username = '" + GlobalVariables.Username + "' AND name = '" + GlobalVariables.SellingName + "'";
cmd.CommandText = str;
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
member.Username = dr.GetString(0);
member.MemberID = dr.GetInt32(1);
member.Phone = dr.GetInt32(2);
member.Email = dr.GetString(3);
console.ConsoleName = dr.GetString(5);
advert.Description = dr.GetString(6);
advert.Genre = dr.GetString(7);
advert.Date = dr.GetDateTime(8);
advert.Price = dr.GetDouble(9);
advert.Name = dr.GetString(4);
advertList.Add(member);
advertList.Add(console);
advertList.Add(advert);
}
return advertList;
}
could be an easier way but its the way they want it done in the college.
You can use one foreach block with object as the element type, but you need to check the type of the element, convert the element to the correct type, and implement the logic according to the type of the element.
foreach (object obj in array)
{
if (obj is Member)
{
Member m = (Member)obj;
txtBoxEmail.Text = m.Email;
txtBoxPhone.Text = m.Phone.ToString();
txtBoxUsername.Text = m.Username;
}
else if (obj is Consoles)
{
Consoles c = (Consoles)obj;
cmbConsole.Text = c.ConsoleName;
}
else if (obj is Advert)
{
Advert a = (Advert)obj;
cmbGenre.Text = a.Genre;
lblDateStarted.Text = a.Date.ToString("dd/MM/yyyy");
txtBoxPrice.Text = a.Price.ToString();
txtBoxName.Text = a.Name;
txtBoxDesc.Text = a.Description;
}
}
The foreach looping requires that the object implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface.
So, the answer is "no"
There isn't a direct way to use more than ONE object in a foreach looping.
One way to do what you want is with interfaces and a foreach looping, if you make your three classes implement the same Interface. ex:
public interface IInterface
{
string Text { get; }
}
Then, if you implement this interface in every class, you can do something like this:
foreach (IInterface i in array)
{
//do whatever you want with the text here.
}
But you will be able to use only the properties you implement in the interface.
SO if you need "different" properties depending on the object, you will have to use some kind of indicator of type and use if's or switchs inside the looping, besides having to implement all the required properties in the interface.
I need return List on textbox and others controls... In my Gridview the result is ok.
I use grv.Datasouce = method... Its ok. But i dont return single values.
public Configuracoes()
{
}
public int conId { get; set; }
public string conDescricao { get; set; }
}
}
public List<Configuracoes> GetConfiguracoes()
{
List<Configuracoes> list = new List<Configuracoes>();
using (SQLiteConnection conn = new SQLiteConnection(strAppDir))
{
conn.Open();
SQLiteCommand command = new SQLiteCommand("SELECT * FROM CAP_CONFIGURACAO ORDER BY conId", conn);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Configuracoes configuracoes = new Configuracoes();
configuracoes.conDescricao = reader["conDescricao"].ToString();
list.Add(configuracoes);
}
}
return list;
}
how to return this for a text box ?
txt.Text = ?
your function returns an object of type List<Configuracoes>, now you want to set it to a textbox Text property wich is a string, there is not way in this world that can be possible.
what you can do is make a string of your array and set it in the Text property of your textbox. something like
var myConfigs = GetConfiguracoes();
string myString;
foreach(var config in myConfigs){
myString += config.conDescricao;
}
txt.Text = myString;
hope it helps
Got It !
I used DataBinding on my textbox
txtPastaProcessada.DataBindings.Add(new Binding("Text", ds, "columnoftable", false, DataSourceUpdateMode.OnPropertyChanged));
I have this piece of code:
while (reader.Read())
{
count++;
string Text = (String.Format("{0}", Object.Equals(Variables.buffering, reader.GetValue(0))));
List<string> mystring = new List<string>();
mystring.Add(Text);
if (Convert.ToBoolean(Text))
{
string myText = new TextRange(mainWindow.richtextbox2.Document.ContentStart, mainWindow.richtextbox2.Document.ContentEnd).Text;
var str = Regex.Replace(myText, #"( |\r?\n)\1+", "$1", RegexOptions.Multiline);
mainWindow.Dispatcher.Invoke(new Action(() =>
mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run("hello")))));
string text = "s";
mainWindow.WriteSerial(text);
Console.WriteLine(Text);
}
}
foreach (string element in mystring)
{
Console.WriteLine(element);
}
why is that the mystring in my foreach loop has an error of:
Error 2 The name 'mystring' does not exist in the current context
*This is another problem encountered. Please neglect the previous one.
I suspect that
Convert.ToBoolean(Text)
Evaluates to false
Did you step through the code in debug?
And why a Reader for a single row:
RowCount = (Int32)createCommand.ExectueScalar.ToString();
If you just want the row count, you don't have to select on a specific column. Just do this:
using(SQLiteConnection sqliteCon = new SQLiteConnection(dBConnectionString))
{
sqliteCon.Open();
using(SQLiteCommand createCommand = new SQLiteCommand("SELECT COUNT(*) FROM EmployeeList", sqlliteCon))
{
createCommand.CommandType = System.Data.CommandType.Text;
int RowCount = 0;
RowCount = Convert.ToInt32(createCommand.ExecuteScalar());
}
}
Note Updated for proper use of using statements