Adding a List to a TableLayoutPanel through a Loop - c#

I have a file that stores flight information and then I have a search form that allows a user to select a starting city and state, destination city and state, the departure date and number of seats they want to book.
I then have the results of the matched flights getting printed into a TableLayoutPanel. My issue is that when the program loops through to find the flights, it adds them, but if it finds multiple flights, the previous indexes are all replaced with the current one. Here is my code that searches through the flights (the lists are all label lists):
private void searchFlights()
{
StreamReader sr = File.OpenText("F:\\C#\\Airline\\Flight.txt");
string read = null;
Button button = new Button();
button.Text = "Book";
totalSeats = int.Parse(peopleSearchComboBox.Text);
while ((read = sr.ReadLine()) != null)
{
String[] flights = read.Split(' ');
testSeats = int.Parse(flights[6]);
if (cityStartSearchTextBox.Text == flights[2] & stateStartComboBox.Text == flights[3] & cityDestinationSearchTextBox.Text == flights[4] &
stateDestComboBox.Text == flights[5] & dateSearchTextBox.Text == flights[7] & totalSeats <= testSeats)
{
airlineSearchLabel.Text = flights[0];
priceSearchLabel.Text = flights[1];
seatSearchLabel.Text = flights[6];
startCityLabel.Text = flights[2];
startStateLabel.Text = flights[3];
endCityLabel.Text = flights[4];
endStateLabel.Text = flights[5];
price.Add(priceSearchLabel);
airline.Add(airlineSearchLabel);
seatsMatch.Add(seatSearchLabel);
buttons.Add(button);
cityStartMatch.Add(startCityLabel);
stateStartMatch.Add(startStateLabel);
cityDestMatch.Add(endCityLabel);
stateDestMatch.Add(endStateLabel);
flightsMatched++;
Console.WriteLine(airline[0].Text); //I have this to check the index and on each pass through its different
}
}
sr.Close();
}
And here is my code for printing it to the table:
private void fillTable()
{
blankTableLabel.Text = "";
priceTableLabel.Text = "Price";
seatsTableLabel.Text = "Open Seats";
airlineTableLabel.Text = "Airline";
noMatchedFlightsLabel.Text = "No Matches Found";
flightsSearchedTable.RowCount = flightsMatched + 1;
flightsSearchedTable.Controls.Add(blankTableLabel,0,0);
flightsSearchedTable.Controls.Add(priceTableLabel,1,0);
flightsSearchedTable.Controls.Add(airlineTableLabel,2,0);
flightsSearchedTable.Controls.Add(seatsTableLabel,3,0);
if (AppendTexts.totalFlights != 0 & flightsMatched != 0)
{
for (int x = 0; x < flightsMatched; x++)
{
if (WelcomeScreen.memberLoggedInCheck == true)
{
flightsSearchedTable.Controls.Add(buttons[x]);
flightsSearchedTable.Controls.Add(price[x]);
flightsSearchedTable.Controls.Add(airline[x]);
flightsSearchedTable.Controls.Add(seatsMatch[x]);
}
else
{
flightsSearchedTable.Controls.Add(price[x],1,x+1);
flightsSearchedTable.Controls.Add(airline[x],2,x+1);
flightsSearchedTable.Controls.Add(seatsMatch[x],3,x+1);
}
}
}
And this is what an example flight would look like that is stored in the file:
Southwest 80 Austin Texas Miami Florida 180 12/04/2011

Nevermind I was able to figure it out. I just needed to reset the labels each time when going through the loop.

It does not seem like you have your table layout panel setup to allow multiple flights to be added.
I's assuming you are using visual studio. Create a table layout panel using the ui editor and study the code it creates in the design file. Then add another row of data and study the design file again and take note of what was added.
Make sure that your code des everything VS does to make a new row/col.
Then practice populating the rows/columns in VS and make sure your code does the corectly also

Related

Creating a search function in c#, windows form application

I am creating a program as part of a college assignment and must have a database connected to my program. The program is in c# and created in a windows form application with visual studio.
I need to have a text box that allows entry and then a button to search for any values that match that, but I cannot figure out how to read what is inputted, search the database and return them in the text boxes.
I already have the database connected and all of the forms designed and connected together with buttons, however this one part is really baffling me. Any help would be appreciated.P.S I am new to c# and do not fully understand it yet.
Please Take Reference from this link your Answer(along with Database Queries) and Explanation is available
Reference 1
Reference 2
1) Put all the texts from the database in some kind of collection (List for example).
2) Get the text from the textbox by accessing the textbox's Text property. Apply some modifications if you want, such as removing caps, handling keywords etc.
3) Write a linq query that goes something like collection.Where(t => t.Contains(searchString)).ToList(). Alternatively, you can loop over the collection.
4) Feed the resulting list to your output textbox.
In my case, I was used a dataGridView for the DataSet of mysql data and below is the sample code for searchbox.
private void tfSearch_TextChanged(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(tfSearch.Text) == false)
{
dataGridView1.Rows.Clear();
for(int i = 0; i < GlobalState.Items.Tables[0].Rows.Count; i++)
{
string id = GlobalState.Items.Tables[0].Rows[i].ItemArray.GetValue(0).ToString();
string name = GlobalState.Items.Tables[0].Rows[i].ItemArray.GetValue(1).ToString();
string price = GlobalState.Items.Tables[0].Rows[i].ItemArray.GetValue(2).ToString();
string stock = GlobalState.Items.Tables[0].Rows[i].ItemArray.GetValue(3).ToString();
if (name.StartsWith(tfSearch.Text))
{
int index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = id;
dataGridView1.Rows[index].Cells[1].Value = name;
dataGridView1.Rows[index].Cells[2].Value = price;
dataGridView1.Rows[index].Cells[3].Value = stock;
}
}
}
else if(tfSearch.Text == "")
{
dataGridView1.Rows.Clear();
for (int i = 0; i < GlobalState.Items.Tables[0].Rows.Count; i++)
{
string id = GlobalState.Items.Tables[0].Rows[i].ItemArray.GetValue(0).ToString();
string name = GlobalState.Items.Tables[0].Rows[i].ItemArray.GetValue(1).ToString();
string price = GlobalState.Items.Tables[0].Rows[i].ItemArray.GetValue(2).ToString();
string stock = GlobalState.Items.Tables[0].Rows[i].ItemArray.GetValue(3).ToString();
int index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = id;
dataGridView1.Rows[index].Cells[1].Value = name;
dataGridView1.Rows[index].Cells[2].Value = price;
dataGridView1.Rows[index].Cells[3].Value = stock;
}
}
Your Welcome.
Get the textbox text when you click on the button then start a query with that search word so youll get back everything what contains that word
Get input text
Textboxname.text;
Query
SELECT * ON table WHERE tagoridorwhatever = textboxname.text
The query part may be a bit different since im weiting this out of my head on a mobile phone

Unable to fetch value of web element even though it exists

I am trying to fetch the Text of All table rows in a web page using Selenium C#.
Below is the code for retriving all tr's from the web page:
var trElements = driver.FindElements(By.TagName("tr"));
This shows the data correctly. For example, tr element number 35 has text 'canara bank' in it, that can be seen in below image.
Now I am trying to extract only text of all the tr elements. Either by using LINQ or by using for loop:
string[] strrr= trElements.Select(t => t.Text).ToArray();
Surprisingly, Text property of most of the element does not show up the data that was shown in web element. Randomly data of some elements keeps showing up or goes off.
I want to ensure that data of web elements is correctly converted to string array. How to achieve this?
I think there are 3 possibilities.
1. The rows are not visible. So element.Text can't give you the text. In this case, you need to use element.GetAttribute("innerText") instead of element.Text.
string[] strrr = trElements.Select(t => t.GetAttribute("innerText")).ToArray();
2. The script does not have enough wait time. In this case, you just need to add wait to check text length.
var trElements = driver.FindElements(By.TagName("tr"));
List<string> strrr = new List<string>();
foreach (var tr in trElements)
{
IWait<IWebElement> wait = new DefaultWait<IWebElement>(tr);
wait.Timeout = TimeSpan.FromSeconds(10);
try
{
wait.Until(element => element.Text.Trim().Length > 1);
strrr.Add(element.Text.Trim());
}
catch (WebDriverTimeoutException)
{
strrr.Add("");
}
}
3. The text will be displayed when you scroll down.
int SCROLL_PAUSE_TIME = 1;
int SCROLL_LENGTH = 500;
var jsExecutor = driver as IJavaScriptExecutor;
int pageHeight = Int32.Parse((string)jsExecutor.ExecuteScript("return document.body.scrollHeight"));
int scrollPosition = 0;
while (scrollPosition < pageHeight)
{
scrollPosition = scrollPosition + SCROLL_LENGTH;
jsExecutor.ExecuteScript("window.scrollTo(0, " + scrollPosition + ");");
System.Threading.Thread.Sleep(SCROLL_PAUSE_TIME);
}
var trElements = driver.FindElements(By.TagName("tr"));

C# NetSuite WebServices: Get value from custom field in saved search (ItemSearchAdvanced)

I'm using C# MVC to connect to NetSuite using their WebServices API. I have some current code that calls a saved search of inventory items. Here is the current code that is working perfectly:
ItemSearchAdvanced searchItems = new ItemSearchAdvanced();
searchItems.savedSearchId = "128";
SearchResult result = netSuiteSvc.search(searchItems);
int totalRecords = 0;
int processedRecords = 0;
UpdateNetsuitePriceListModel returnObj = new UpdateNetsuitePriceListModel();
returnObj.NewPriceList = new List<NetSuitePriceListRecord>();
if (result.status.isSuccess)
{
SearchRow[] searchRows = result.searchRowList;
if (searchRows != null && searchRows.Length >= 1)
{
for (int i = 0; i < searchRows.Length - 1; i++)
{
ItemSearchRow itemRow = (ItemSearchRow)searchRows[i];
if (itemRow.basic.itemId != null && itemRow.basic.mpn != null && itemRow.basic.basePrice != null && itemRow.basic.salesDescription != null)
{
returnObj.NewPriceList.Add(new NetSuitePriceListRecord()
{
ItemId = itemRow.basic.itemId[0].searchValue,
ManufacturerPartNumber = itemRow.basic.mpn[0].searchValue,
ContractPrice = Convert.ToDecimal(itemRow.basic.basePrice[0].searchValue),
Cost = CalculateProductCostForIngram(Convert.ToDecimal(itemRow.basic.basePrice[0].searchValue)),
Description = itemRow.basic.salesDescription[0].searchValue
});
processedRecords++;
}
totalRecords++;
}
}
else
{
throw new Exception("NetSuite Part List Blank");
}
}
else
{
throw new Exception("NetSuite Part List Search Failure");
}
Now I have need to pull the itemId from a custom added field rather than the default itemId field.
Obviously since this is a custom field it isn't a property of ItemSearchRowBasic. It looks like instead of the property I can choose "customFieldList" which is an array of "SearchColumnCustomField". If I choose an index for the array I can see that SearchColumnCustomField contains:
customLabel
internalId
scriptId
I imagine I should be able to get the internalId of the SearchColumnCustomField and somehow use that to get the search value for that custom column but I've had some trouble finding any examples that fit so far.
This custom field is a free form text field added to all inventory items.
Try setting scriptId with the ID of the field ("custitem_xyz"). That should work.
Before 2013 one would use internalId, but since then it changed to scriptId.
You would need to loop over the CustomRecord items in the customFieldList. I then usually check for a specific type so I can cast to the correct object, but with some reflection you could probably avoid that.
foreach (Record r in mySearchResponse.recordList){
foreach (CustomFieldRef cr in ((CustomRecord)r).customFieldList){
if (cr.GetType().Name == "SelectCustomFieldRef"){
if (((SelectCustomFieldRef)cr).scriptId == "my_custom_field"){
internalID = ((CustomRecord)r).internalId;
}
}
}
}

Why am I getting index out of bounds error from database

I know what index out of bounds is all about. When I debug I see why as well. basically what is happening is I do a filter on my database to look for records that are potential/pending. I then gather a array of those numbers send them off to another server to check to see if those numbers have been upgraded to a sale. If it has been upgraded to a sale the server responds back with the new Sales Order ID and my old Pending Sales Order ID (SourceID). I then do a for loop on that list to filter it down that specific SourceID and update the SourceID to be the Sales Order ID and change a couple of other values. Problem is is that when I use that filter on the very first one it throws a index out of bounds error. I check the results returned by the filter and it says 0. Which i find kind of strange because I took the sales order number from the list so it should be there. So i dont know what the deal is. Here is the code in question that throws the error. And it doesn't do it all the time. Like I just ran the code this morning and it didn't throw the error. But last night it did before I went home.
filter.RowFilter = string.Format("Stage = '{0}'", Potential.PotentialSale);
if (filter.Count > 0)
{
var Soids = new int[filter.Count];
Console.Write("Searching for Soids - (");
for (int i = 0; i < filter.Count; i++)
{
Console.Write(filter[i][1].ToString() + ",");
Soids[i] = (int)filter[i][1];
}
Console.WriteLine(")");
var pendingRecords = Server.GetSoldRecords(Soids);
var updateRecords = new NameValueCollection();
for (int i = 0; i < pendingRecords.Length; i++)
{
filter.RowFilter = "Soid = " + pendingRecords[i][1];
filter[0].Row["Soid"] = pendingRecords[i][0];
filter[0].Row["SourceId"] = pendingRecords[i][1];
filter[0].Row["Stage"] = Potential.ClosedWon;
var potentialXML = Potential.GetUpdatePotentialXML(filter[0].Row["Soid"].ToString(), filter[0].Row["Stage"].ToString());
updateRecords.Add(filter[0].Row["ZohoID"].ToString(), potentialXML);
}
if i'm counting right line 17 is the error where the error is thrown. pendingRecords is a object[][] array. pendingRecords[i] is the individual records. pendingRecords[i][0] is the new Sales OrderID (SOID) and pendingRecords[i][1] is the old SOID (now the SourceID)
Any help on this one? is it because i'm changing the SOID to the new SOID, and the filter auto updates itself? I just don't know
Well I ended up changing how it worked all together and it actually sorts it a bit nicer now. The code i am about to post has a bunch of hard coded numbers due to the structure of my table that is returned. Sorry about that. I have learned since then to not do that, but i am working on a different project now and will change that when I have to change the program. But here is the solution.
var potentials = Server.GetNewPotentials(); //loads all records from server
for (int i = 0; i < potentials.Length; i++)
{
var filter = AllPotentials.DefaultView;
var result1 = CheckSoidOrSource(potentials[i].Soid, true);
var result2 = CheckSoidOrSource(potentials[i].SourceID,false) ;
//This potential can't be found at all so let's add it to our table
if (result1+result2==0)
{
Logger.WriteLine("Found new record. Adding it to DataTable and sending it to Zoho");
AllPotentials.Add(potentials[i]);
filter.RowFilter = string.Format("Soid = '{0}'", potentials[i].SourceID);
var index = AllPotentials.Rows.IndexOf(filter[0].Row);
ZohoPoster posterInsert = new ZohoPoster(Zoho.Fields.Potentials, Zoho.Calls.insertRecords);
AllPotentials.Rows[index]["ZohoID"] = posterInsert.PostNewPotentialRecord(3, filter[0].Row);
}
//This potential is not found, but has a SourceId that matches a Soid of another record.
if (result1==0 && result2 == 1)
{
Logger.WriteLine("Found a record that needs to be updated on Zoho");
ZohoPoster posterUpdate = new ZohoPoster(Zoho.Fields.Potentials, Zoho.Calls.updateRecords);
filter.RowFilter = string.Format("Soid = '{0}'", potentials[i].SourceID);
var index = AllPotentials.Rows.IndexOf(filter[0].Row);
AllPotentials.Rows[index]["Soid"] = potentials[i].Soid;
AllPotentials.Rows[index]["SourceId"] = potentials[i].SourceID;
AllPotentials.Rows[index]["PotentialStage"] = potentials[i].PotentialStage;
AllPotentials.Rows[index]["UpdateRecord"] = true;
AllPotentials.Rows[index]["Amount"] = potentials[i].Amount;
AllPotentials.Rows[index]["ZohoID"] = posterUpdate.UpdatePotentialRecord(3, filter[0].Row);
}
}
AllPotentials.AcceptChanges();
}
private int CheckSoidOrSource(string Soid, bool checkSource)
{
var filter = AllPotentials.DefaultView;
if (checkSource)
filter.RowFilter = string.Format("Soid = '{0}' OR SourceId = '{1}'",Soid, Soid);
else
filter.RowFilter = string.Format("Soid = '{0}'", Soid);
return filter.Count;
}
basically what is happening is that i noticed something about my data when I filter it this way. The two results would only return the following results (0,0) (0,1) and (1,0) (0,0) means that the record doesn't exist at all in this table so I need to add it. (1,0) means that the Sales Order ID (Soid) matches another Soid in the table so it already exists. Lastly (0,1) means that the Soid doesn't exist in this table but i found a record that has the Soid as it's source...which to me means that the one that had it as a source has been upgraded from a potential to a sale, which in turn means i have to update the record and Zoho. This worked out to much less work for me because now I don't have to search for won and lost records, i only have to search for lost records. less code same results is always a good thing :)

Need help in using MySqlTransaction

Hi all i would like to use MySqlTransaction in my requirement. Actually i am having a doubt regarding that i.e as per my requirement i will have to delete different values from database.
The process i am doing is as follows. Assume that i am having 2 EmpIDs where this EmpID will hold different values which may be multiple. I will store the corresponding values for that particular EmpID using Dictionary and then i will save them to a list corresponding to the EmpID.
Assume that i am having list element as follows
For EmpID 1 i will have 1,2. I will check for the maximum value from the datbase in this list if exists i would like to delete this EmpID from the database.
For EmpID 2 i will have 1,2. But in my database i will have 3 as maximum values. So this one fails . I would like to rollback the previously deleted item .
Is it possible to do with a transaction if so can any one help me in solving this
Sample i code
if(findMax(lst,iEmpID)
{
obj.delete("storeprocname"); // this will occur when my list has maximum value
}
else
{
//Here i would like to rollback my previous one referring to the delete method in class file
}
My sample code
if (findMaxPayPeriodID(lstPayPeriodID, iEmpIDs)) //Assume for the first time maxpayperiod exists and for the second time it fails how to rollback then
{
if (findSequence(lstPayPeriodID)) // Assume this is also true for first time
{
for (int ilstPayperiodID = 0; ilstPayperiodID < lstPayPeriodID1.Count; ilstPayperiodID++)
{
oAdmin.Payperiodnumber = (int)lstPayPeriodID1[ilstPayperiodID];
for (int ilistPayYear = iPayYearcnt; ilistPayYear < lstPayYear1.Count; ilistPayYear++)
{
oAdmin.PayYear = (int)lstPayYear1[ilistPayYear];
iPayYearcnt++;
break;
}
for (int ilistDateTime = idtcnt; ilistDateTime < lstDateTime1.Count; ilistDateTime++)
{
idtcnt++;
oAdmin.PaymentDate = lstDateTime1[ilistDateTime];
break;
}
}
if (oAdmin.deletePayRoll(oSqlTran))
{
oMsg.Message = "Deleted Sucessfully";
oMsg.AlertMessageBox(out m_locallblMessage);
Page.Controls.Add(m_locallblMessage);
oAdmin.FedTaxID = ddlFedTaxID.SelectedValue;
oAdmin.PayFrequency = ddlPaymentType.SelectedValue.ToString();
mlocal_strStoredProcName = "uspSearchPayRoll";
oAdmin.getPayRollDetails(out mlocal_ds, mlocal_strStoredProcName);
//grdPayroll.Visible = true;
grdPayroll.DataSource = mlocal_ds;
grdPayroll.DataBind();
if (mlocal_ds != null)
{
btnDelete.Visible = true;
}
else
btnDelete.Visible = false;
}
lstPayPeriodID.Clear();
lstDateTime.Clear();
lstPayYear.Clear();
iPayIDcnt = 0;
iPayYearcnt = 0;
idtcnt = 0;
}
else
{
rollback should be done
}
You don't provide enough information - esp. since it seems that you will use a Stored Procedure for the delete operation all bets are off...
The only option I can think of is to make sure that you find first the maximum EmpId not from one list BUT from all lists first... then just check that against the DB and act accordingly...
This way the DB will only be hit twice (for the check and for the delete/Stored Procedure)... which is definetely better in terms of scaling etc.

Categories

Resources