Dropdown removing the leading zeros in C# - c#

I have a database in MS Access with one table field named "Seat number" with the text data type having entries 001, 002........100, 62AB. While populating the values, there were no issues but when I try to select seat numbers having leading zeros (e.g. 001,002,009,010 etc.) by doing
string seatList =(ddlSeatList.SelectedValue.ToString());
it removes the leading zero(es).

Assuming that you have up to three digits in seat you can use
string seatList =(ddlSeatList.SelectedValue.ToString("000"));
UPDATE:
Solutions above is completely wrong.
Based on comments dropdown list is initialized in the following way
if (seatselection=="9F")
{
seatalloaction = ("select TCS_Seat_ID,TCS_Seat_Num from TCS_Seat where TCS_Seat_Enable_F=" + "'Y'");
}
DataSet dataTCSSeat = new DataSet();
dataTCSSeat = drpDownList.ExecuteQuery(seatalloaction);
ddlSeatList.Items.Add(new ListItem("TCS_Seat_ID", "TCS_Seat_Num"));
if (dataTCSSeat.Tables.Count > 0)
{
for (int i = 0; i < dataTCSSeat.Tables[0].Rows.Count; i++)
{
ddlSeatList.Items.Add(new ListItem(
dataTCSSeat.Tables[0].Rows[i].ItemArray[1].ToString(),
dataTCSSeat.Tables[0].Rows[i].ItemArray[0].ToString()));
}
}
Thus ddlSeatList.SelectedValue returns values from _TCS_Seat_ID_ field, not from _TCS_Seat_Num_ as visualized. If it is required to get exacly the value from dropdown as it is shown in list control must be initialized in the following way:
for (int i = 0; i < dataTCSSeat.Tables[0].Rows.Count; i++)
{
//both text and value are initialized with TCS_Seat_Num field values
ddlSeatList.Items.Add(new ListItem(
dataTCSSeat.Tables[0].Rows[i].ItemArray[1].ToString(),
dataTCSSeat.Tables[0].Rows[i].ItemArray[1].ToString()));
}

Related

How to set value by call variable name from string c#

Now I'm new for c# development.
I have 100 data from Array and also have 100 variables.
How can I match 100 data with 100 variables?
for example
for(int count = 0 ; count < array.lenght ; count++)
{
Var+count = array[count];
}
Something like this.
or you guy have another solution please help me. I don't want to do like
set Var1 to Var100 by hand.
More Information
Actually I need to add the arrays values to text object in CrystalReport
For example if I want to add the value
TextObject txtLot1 = (TextObject)report.ReportDefinition.Sections["Section4"].ReportObjects["txtLot1"];
txtLot1.Text = Arrays[i]
something like this. so , I try to use dictionary but I don't think it will work.
Here is an example of doing what you are asking for on the fly with a System.Collections.Generic.Dictionary, all keys in a dictionary must be unique, but since you are appending 1 to each key in your loop this will suffice:
Dictionary<string, int> myKeyValues = new Dictionary<string, int>();
for(int count = 0 ; count < array.length; count++)
{
//Check to make sure our dictionary does not have key and if it doesn't add key
if(!myKeyValues.ContainsKey("someKeyName" + count.ToString())
{
myKeyValues.Add("someKeyName" + count.ToString(), count);
}
else
{
//If we already have this key, overwrite, shouldn't happen as you are appending a new int value to key each iteration
myKeyValues["someKeyName" + count.ToString()] = count;
}
}

c# Read lines from a file and replace with text from DataGridView Data

I am relatively new to c#, I am creating an windows application which would read all the lines from a text file. The user will input the string which needs to be replaced in Column[0] and the text with which it needs to be replaced in Column1 of the DataGridView control.
I have created two string arrays column0 and column1.
However, I am getting an error while replacing the string in line (column0, column1)
The following is my code:
string[] column0 = new string[dgvMapping.Rows.Count];
string[] column1 = new string[dgvMapping.Rows.Count];
int j = 0;
foreach(DataGridViewRow row in dgvMapping.Rows)
{
if (!string.IsNullOrEmpty(Convert.ToString(row.Cells[0].Value)))
{
column0[j] = Convert.ToString(row.Cells[0].Value);
column1[j] = Convert.ToString(row.Cells[1].Value);
j++;
}
}
var _data = string.Empty;
String[] arrayofLine = File.ReadAllLines(ofd.FileName);
using (StreamWriter sw = new StreamWriter(ofd.FileName + ".output"))
{
for (int i = 0; i < arrayofLine.Length; i++)
{
string line = arrayofLine[i];
line = line.Replace(column0[i], column1[i]);
sw.WriteLine(line);
}
}
I am using OpenFileDialog to select the file.
The Error While Executing:
You are looping around a file of unknown number of lines, and assuming that the count of lines in the grid is exactly the same as that of the file. Your code will only work if both the file and the gridView have the same number of lines.
One of the solutions, is to loop over the array of lines (as you have already did), and search for the GridViewRow in which the current line contains a key in your DGV. If this is the case, then replace all the occurences of the key by the value (obtained from the gridView) in that line, otherwise do nothing.
Check out the code below :
// Convert the row collection to a list, so that we could query it easily with Linq
List<DataGridViewRow> mySearchList = dataGridView1.Rows.Cast<DataGridViewRow>().ToList();
const int KEY_INDEX = 0; // Search index in the grid
const int VALUE_INDEX = 1; // Value (replace) index in the grid
for (int i = 0; i < arrayofLines.Length; i++)
{
string line = arrayofLines[i];
// Get data grid view Row where this line contains the key string
DataGridViewRow matchedRow = mySearchList.FirstOrDefault(obj => line.Contains(obj.Cells[KEY_INDEX].Value.ToString()));
// If this row exists, replace the key with the value (obtained from the grid)
if (matchedRow != null)
{
string key = matchedRow.Cells[KEY_INDEX].Value.ToString();
string value = matchedRow.Cells[VALUE_INDEX].Value.ToString();
line = line.Replace(key, value);
sw.WriteLine(line);
}
else
{
// Otherwise, do nothing
}
}
Stuartd is correct… there are more lines in the file than there are elements to search. I am not sure what the search is doing in a sense that it seems somewhat limited. The code appears to search for each item depending on what line it is. The searched value in column 0 and the replace value in column 1 of row 0… will only replace those values for the FIRST line in the file. The DataGridViews second row values will search/replace only the SECOND line and so on. This seems odd.
Example the two string arrays (column0 and column1) have sizes set to the number of rows in dgvMapping. Let’s say there are 5 rows in the grid, then the array sizes will be 5 strings. When you start the loop to write the strings, the loop starts at 0 and stops at the number of lines in the file. The code uses this i variable as an index into the two arrays. If there are more lines in the file, than there are rows in the grid… then you will get the error.
Again, this seems odd to do the search and replace this way. Assuming you want to search for EACH term in all the rows in column 0 and replace the found searched string with the replace string in column 1, then you will need to loop through EACH row of the grid for EACH line in the file. This will replace ALL the search/replace terms in the grid with ALL the lines in the file. If this is what you what to accomplish below is one way to achieve this, however…there are possibly better ways to accomplish this.
The code below reads the file into one big string. Then the code loops through ALL the grid rows to search/replace the strings in the big string. Hope this helps.
string bigString = File.ReadAllText(ofd.FileName);
try {
using (StreamWriter sw = new StreamWriter(ofd.FileName + ".output")) {
for (int k = 0; k < dgvMapping.Rows.Count; k++) {
if (dgvMapping.Rows[k].Cells[0].Value != null && dgvMapping.Rows[k].Cells[1].Value != null) {
string searchTerm = dgvMapping.Rows[k].Cells[0].Value.ToString();
string replaceTerm = dgvMapping.Rows[k].Cells[1].Value.ToString();
if (searchTerm != "") {
bigString = bigString.Replace(searchTerm, replaceTerm);
} else {
// one of the terms is empty
}
} else {
// one of the terms is null}
}
}
sw.WriteLine(bigString);
}
}
catch (Exception ex) {
MessageBox.Show("Write Erro: " + ex.Message);
}

Access variable's value via its string name C#

I want to store a series (six to be precise) of Windows Forms labels in an array. There are six labels, which follow the naming convention orderLabel0, orderLabel1... orderLabel5.
I would like to store the pointers to the orderLabels in an array:
Label[] orderLabels = new Label[6];
for(int index = 0; index < 6; index++)
{
orderLabels[index] = orderLabel + [index]; //Error!
}
The code somehow needs to treat the string as variable name and store them as "labels" rather than string in the orderLabels array. In other words, when orderLabels[0] is accessed, I am actually accessing orderLabel0.
Research here and there have led me to dynamic, Reflection and Dictionary options. However, they all require me to specify the object names (correct me if I am wrong), and I am trying to follow the "Do Not Repeat" yourself rule by not having to specify the object six times.
Please advise, thank you.
You can use the Controls form variable to look up the control by name:
Label[] orderLabels = new Label[6];
for(int index = 0; index < 6; index++)
{
orderLabels[index] = Controls[string.Format("orderLabel{0}", index)] as Label;
}

Count the filled array elements and display result into label

I've got a string[] Brands = new string[10];
With the following code i'm giving it 4 standard values. I can add values with a add button. (I already got this part of code)
public Form1()
{
{
InitializeComponent();
Merken[0] = "Yamaha";
Merken[1] = "Suzuki";
Merken[2] = "Harley";
Merken[3] = "Kawasaki";
merkNr = 4;
listBoxMotoren.DataSource = Brands;
}
}
I want to display the FILLED elements of the array into a `label.text.
So, when I run the program the label shows the numer 4 (because 4 elements of the array are filled). When I add a value to the array with btnclick, the label needs to display the number 5 and so on...`
You can use Linq to get count of filled elements from array.
int count = Merken.ToList().Where(x => (!string.IsNullOrEmpty(x))).Count();
yourLabel.Text = count.ToString();
An easier way would be to use a List<string> and display the Count() of the list. Lists are data structures which grow dynamically, thus each time you add an item to the list, the list grows automatically.
If you want to use arrays, you could start from the first element and use the String.IsNullorEmpty(string str) and a counter which is incremented each time you find a string which is neither null or empty.
Once that you hit a null/empty string, you stop your loop and display the counter.
Forgive me if I'm interpreting this as more simple than it is, but as far as I can tell all you need to do is add "[name of label on form].Text = Merken.Count().ToString();" in the code that adds the new item.
Is there a particular reason you used Merken in the setup but declared it initially as Brands?
why you arent using List
it has Count property. and if you need array for export you call .ToArray() method to get array of your list.
Will you ever have blank indexes?
Merken[4] = ""
Merken[5] = "Honda"
If you are not going to ever have blank indexes, you can set your label to:
[arrayName].length
This will add together the number of indexes in the array.
EDIT: OP says there will be blank indexes
I would recommend looping through the array to see which indexes have values and then increment a counter which you will set as the label text.
int indexesWithValues = 0;
for (int i = 0; i < Brands.length; i++)
{
if (Brands[i] != "")
{
indexesWithValues++;
}
}
Then you set your label text to the counter.
You can get the number of elements in array using
Using System.LINQ
-----
Marken.Count();

Insert an underlying value into a non-existing index

I'm trying to solve a simple algorithm a specific way where it takes the current row and adds it to the top most row. I know there are plenty of ways to solve this but currently I have a text file that gets read line by line. Each line is converted to an sbyte (there's a certain reason why I am using sbyte but it's irrelevant to my post and I won't mention it here) and added to a list. From there, the line is reversed and added to another list. Here's the code I have for that first part:
List<List<sbyte>> largeNumbers = new List<List<sbyte>>();
List<string> total = new List<string>();
string bigIntFile = #"C:\Users\Justin\Documents\BigNumbers.txt";
string result;
StreamReader streamReader = new StreamReader(bigIntFile);
while ((result = streamReader.ReadLine()) != null)
{
List<sbyte> largeNumber = new List<sbyte>();
for (int i = 0; i < result.Length; i++)
{
sbyte singleConvertedDigit = Convert.ToSByte(result.Substring(i, 1));
largeNumber.Add(singleConvertedDigit);
}
largeNumber.Reverse();
largeNumbers.Add(largeNumber);
}
From there, I want to use an empty list that stores strings which I will be using later for adding my numbers. However, I want to be able to add numbers to this new list named "total". The numbers I'll be adding to it are not all the same length and because so, I need to check if an index exists at a certain location, if it does I'll be adding the value I'm looking at to the number that resides in that index, if not, I need to create that index and set it's value to 0. In trying to do so, I keep getting an IndexOutOfRange exception (obviously because that index doesn't exist). :
foreach (var largeNumber in largeNumbers)
{
int totalIndex = 0;
foreach (var digit in largeNumber)
{
if (total.Count == 0)
{
total[totalIndex] = digit.ToString(); //Index out of Range exception occurs here
}
else
{
total[totalIndex] = (Convert.ToSByte(total[totalIndex]) + digit).ToString();
}
totalIndex ++;
}
}
I'm just at a loss. Any Ideas on how to check if that index exists; if it does not create it and set it's underlying value equal to 0? This is just a fun exercise for me but I am hitting a brick wall with this lovely index portion. I've tried to use SingleOrDefault as well as ElementAtOrDefault but they don't seem to be working so hot for me. Thanks in advance!
Depending on if your result is have small number of missing elements (i.e. have more than 50% elements missing) consider simply adding 0 to the list till you reach neccessary index. You may use list of nullable items (i.e. List<int?>) instead of regular values (List<int>) if you care if item is missing or not.
Something like (non-compiled...) sample:
// List<long> list; int index; long value
if (index >= list.Count)
{
list.AddRange(Enumerable.Repeat(0, index-list.Count+1);
}
list[index] = value;
If you have significant number of missing elements use Dictionary (or SortedDictionary) with (index, value) pairs.
Dictionary<int, long> items;
if (items.ContainsKey(index))
{
items[key] = value;
}
else
{
items.Add(index, value);
}

Categories