File upload in ASP.NET and C# - c#

i needed a file upload feature in my project built on ASP.NET 3.5 and C#. I followed the following link to do so.
http://support.microsoft.com/kb/323246.
I created a folder named Data and followed everything as stated in the link.But my files didnt get uploaded in that folder named Data.What should i do to upload a file?

Any exception is thrown? Do you give the permission to the account you program run under? What's size of your file upload? Try a small one first, such as 1K file. ASP.NET has a size limit, and you can change the limit in the config file.

class Proizvod {
public string ceo_red, ime, proizvodjac, ram, tip, kamera,slika, ekran,sifra, cena;
public Proizvod(string x) {
ceo_red = x;
slika = x.Split(',')[0];
sifra = x.Split(',')[1];
ime = x.Split(',')[2];
proizvodjac = x.Split(',')[3];
ram = x.Split(',')[4];
tip = x.Split(',')[5];
kamera = x.Split(',')[6];
ekran = x.Split(',')[7];
cena = x.Split(',')[8];
}
}
List<Proizvod> proizvodi = new List<Proizvod>();
protected void Page_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(#"F:\dji\A8\A8\TextFile1.txt");
for (int i = 0; i < 5; i++)
{
proizvodi.Add(new Proizvod(sr.ReadLine()));
}
for (int i = 0; i < proizvodi.Count; i++)
{
bool isti = false;
for (int j = 0; j < DropDownList1.Items.Count; j++)
{
if (proizvodi[i].proizvodjac == DropDownList1.Items[j].Text) isti = true;
}
if (!isti) DropDownList1.Items.Add(proizvodi[i].proizvodjac);
isti = false;
for (int j = 0; j < DropDownList2.Items.Count; j++)
{
if (proizvodi[i].ram == DropDownList2.Items[j].Text) isti = true;
}
if (!isti) DropDownList2.Items.Add(proizvodi[i].ram);
isti = false;
for (int j = 0; j < DropDownList3.Items.Count; j++)
{
if (proizvodi[i].tip == DropDownList3.Items[j].Text) isti = true;
}
if (!isti) DropDownList3.Items.Add(proizvodi[i].tip);
isti = false;
for (int j = 0; j < DropDownList4.Items.Count; j++)
{
if (proizvodi[i].kamera == DropDownList4.Items[j].Text) isti = true;
}
if (!isti) DropDownList4.Items.Add(proizvodi[i].kamera);
isti = false;
for (int j = 0; j < DropDownList5.Items.Count; j++)
{
if (proizvodi[i].ekran == DropDownList5.Items[j].Text) isti = true;
}
if (!isti) DropDownList5.Items.Add(proizvodi[i].ekran);
}
Table1.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
List<Proizvod> trazeni = new List<Proizvod>();
for (int i = 0; i < proizvodi.Count; i++)
{
if (proizvodi[i].proizvodjac == DropDownList1.Text && proizvodi[i].ram == DropDownList2.Text && proizvodi[i].tip == DropDownList3.Text && proizvodi[i].kamera == DropDownList4.Text && proizvodi[i].ekran == DropDownList5.Text)
{
trazeni.Add(proizvodi[i]);
}
}
for (int i = 0; i < trazeni.Count; i++)
{
TableRow tr = new TableRow();
for (int j = 0; j < 9; j++)
{
TableCell tc = new TableCell();
tc.Text = trazeni[i].ceo_red.Split(',')[j];
tr.Cells.Add(tc);
}
Table1.Rows.Add(tr);
}
Table1.Visible = true;
}
}
}

Related

Merge rows in datagridview

I am trying to make a billing software and want to merge the rows with same barcode with a press of a button, and if that row contains remark then the row should not merge.
private void button3_Click(object sender, EventArgs e)
{
int GROW = dataGridView1.RowCount;
for(int i=0; i<GROW; i++)
{
DataGridViewRow row= dataGridView1.Rows[i];
string A = row.Cells[0].Value.ToString();
for(int j = 0; j< GROW; j++)
{
if(j == i)
{
}
else
{
DataGridViewRow rowb= dataGridView1.Rows[j];
string B = rowb.Cells[0].Value.ToString();
if (A == B)
{
string rema = row.Cells[8].Value.ToString();
string remb = rowb.Cells[8].Value.ToString();
if(rema == "" && remb == "")
{
string qa = row.Cells[2].Value.ToString();
string qb = rowb.Cells[2].Value.ToString();
decimal qad = Convert.ToDecimal(qa);
decimal qbd = Convert.ToDecimal(qb);
decimal tqd = qad + qbd;
string ra = row.Cells[7].Value.ToString();
string rb = rowb.Cells[7].Value.ToString();
decimal rad = Convert.ToDecimal(ra);
decimal rbd = Convert.ToDecimal(rb);
decimal trd = rad + rbd;
row.Cells[7].Value = trd;
row.Cells[2].Value= tqd;
dataGridView1.Rows.RemoveAt(j);
// i = i - 1;
GROW--;
}
}
}
}
}
Assuming your value is in Cell[2] and remark in Cell[8], something like this should work:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
int k = 0;
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
// Check if values are same but remarks are different
if (dataGridView1.Rows[i].Cells[2].Value == dataGridView1.Rows[j].Cells[2].Value && dataGridView1.Rows[i].Cells[8].Value != dataGridView1.Rows[j].Cells[8].Value)
{
if (k != 0)
{
items.Rows.RemoveAt(j);
dataGridView1.DataSource = items;
}
k++;
}
}
}
NOTE: I have not tested this code but I hope you get the idea

Why I am not getting the last two entries from the CSV in my program?

Greetings fellow programmers, I need to ask you for a help.
I have this programm:
private void Import_CSV_Click(object sender, System.Windows.RoutedEventArgs e)
{
List<List<string>> x = new List<List<string>>();
try
{
List<string> row = new List<string>();
OpenFileDialog browseDialog = new OpenFileDialog();
browseDialog.Filter = "CSV Files (*.csv)|*.csv";
browseDialog.ShowDialog();
StreamReader sr = new StreamReader(browseDialog.FileName, Encoding.Default, true);
List<TOsoby> persons = new List<TOsoby>();
var file = sr.ReadToEnd();
var linesinthestream = file.Split(new char[] { '\n' });
for (int i = 0; i < linesinthestream.Count()-2; i++)
{
persons.Add(new TOsoby());
}
sr = new StreamReader(browseDialog.FileName, Encoding.Default, true);
string firstline = Akro.Helpers.String.RemoveDiacritics(sr.ReadLine().ToLower());
string[] values = firstline.Split(';');
for (int i = 0; i < values.Length; i++)
{
row.Add(values[i]);
}
x.Add(row);
while (!sr.EndOfStream)
{
row = new List<string>();
string lines = sr.ReadLine();
values = lines.Split(';');
for (int i = 0; i < values.Length; i++)
{
row.Add(values[i]);
}
x.Add(row);
}
for (int i = 0; i < x[0].Count-2; i++)
{
if (x[0][i] == "jmeno") //Tady je chyba J = 22. a count je 24 upakovaní neprojde.
{
for (int j = 0; j < x.Count-2; j++)
{
persons[j].Jmeno = x[j][i].ToString();
}
}
else if (x[0][i] == "name")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Jmeno = x[j][i].ToString();
}
}
else if (x[0][i] == "firstname")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Jmeno = x[j][i].ToString();
}
}
else if (x[0][i] == "prijmeni")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Prijmeni = x[j][i].ToString();
}
}
else if (x[0][i] == "surname")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Prijmeni = x[j][i].ToString();
}
}
else if (x[0][i] == "lastname")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Prijmeni = x[j][i].ToString();
}
}
else if (x[0][i] == "familyname")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Prijmeni = x[j][i].ToString();
}
}
else if (x[0][i] == "titul")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Titul = x[j][i].ToString();
}
}
else if (x[0][i] == "title")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Titul = x[j][i].ToString();
}
}
else if (x[0][i] == "email")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Email = x[j][i].ToString();
}
}
else if (x[0][i] == "")
{
return;
}
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].OsobaID = 0;
}
}
if (persons == null) //Musím odstranit [0], protože tam je uložený první řádek a taky potřebujeme tam dát 23 řádků, takže nám tam 2 entry chybí (Marie a Michal), ale 22. řádek je uložen jako "", takže to musíme nějak opravit.
{
return;
}
else
{
persons.RemoveAt(0); //Tohle opravý ten první řádek
EntitiesModel em = DB.GetDB();
em.Add(persons); //23 a 24 tam vůbec nejsou (lidi z excelu)
em.SaveChanges();
Checker.CheckAfterEverySave();
}
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
}
My quest is to read the CSV entries and save them into the database, my problem is that last two entries of my CSV are not inside the persons, also on the last index it is empty:
Here is my CSV example I generated:
How should I fix it please?
Have a look at this, I included comments where I did changes to your code.
var csvFile = "A;B;C\nA 1;B 1;C 1\nA 2;B 2;C 2\nA 3;B 3;C 3\nA 4;B 4;C 4\n";
List<List<string>> x = new List<List<string>>();
List<Foo> foos = new List<Foo>();
//use StringSplitOptions.RemoveEmptyEntries to remove potential empty line at the end
var linesinthestream = csvFile.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < linesinthestream.Length - 1; i++) //-1 instead of - 2
foos.Add(new Foo());
List<string> row = new List<string>();
string firstline = linesinthestream[0];
string[] values = firstline.Split(';');
for (int i = 0; i < values.Length; i++)
row.Add(values[i]);
x.Add(row);
//use linesinthestream instead of again reading a stream start for loop at 1 and not 0 to skip the header
//you could remove the above code to read the header with this and start at 0, you don't really do anything different
for (int i = 1; i < linesinthestream.Length; i++)
{
row = new List<string>();
string lines = linesinthestream[i];
values = lines.Split(';');
for (int j = 0; j < values.Length; j++)
row.Add(values[j]);
x.Add(row);
}
//remove -2 to read all columns
for (int i = 0; i < x[0].Count; i++)
{
if (x[0][i] == "A")
{
//remove -2, start loop at 1, fill foo[j-1]
for (int j = 1; j < x.Count; j++)
foos[j-1].HeaderA = x[j][i].ToString();
}
else if (x[0][i] == "B")
{
//remove -2, start loop at 1, fill foo[j-1]
for (int j = 1; j < x.Count; j++)
foos[j-1].HeaderB = x[j][i].ToString();
}
else if (x[0][i] == "C")
{
//remove -2, start loop at 1, fill foo[j-1]
for (int j = 1; j < x.Count; j++)
foos[j-1].HeaderC = x[j][i].ToString();
}
}
//moved this loop outside of the previous loop, don't need to do it for every column
for (int j = 1; j < x.Count; j++)
foos[j-1].Id = 0;
foreach(var foo in foos)
Console.WriteLine($"Id: {foo.Id} | HeaderA: {foo.HeaderA} | HeaderB: {foo.HeaderB} | HeaderC: {foo.HeaderC}");
Find a demo here:
https://dotnetfiddle.net/tj0azu
As was already pointed out you should consider usign a library eg.
https://github.com/JoshClose/CsvHelper
and you can achieve the same result with this code:
using System;
using CsvHelper;
using CsvHelper.Configuration;
using System.Globalization;
using System.IO;
public class Program
{
public static void Main()
{
var csvFile = "A;B;C\nA 1;B 1;C 1\nA 2;B 2;C 2\nA 3;B 3;C 3\nA 4;B 4;C 4\n";
using (var reader = new StringReader(csvFile))
using (var csvReader = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture) { Delimiter = ";" }))
{
csvReader.Context.RegisterClassMap<FooMap>();
var foos = csvReader.GetRecords<Foo>();
foreach(var foo in foos)
Console.WriteLine($"Id: {foo.Id} | HeaderA: {foo.HeaderA} | HeaderB: {foo.HeaderB} | HeaderC: {foo.HeaderC}");
}
}
}
public class Foo
{
public int Id {get;set;}
public string HeaderA {get;set;}
public string HeaderB {get;set;}
public string HeaderC {get;set;}
}
public sealed class FooMap : ClassMap<Foo>
{
public FooMap()
{
AutoMap(CultureInfo.InvariantCulture);
Map(m => m.Id).Ignore();
Map(m => m.HeaderA).Name("A");
Map(m => m.HeaderB).Name("B");
Map(m => m.HeaderC).Name("C");
}
}
Find a demo here:
https://dotnetfiddle.net/1jaYNw
I recommend using FileHelpers. There is a nuget package available. I have used this for parsing several CSV files with no issue.
Here is some example code that will read a CSV file through a Stream and create a List<T> of the class that is provided:
using FileHelpers;
using System;
using System.Collections.Generic;
using System.IO;
public class DataFileConverter<T> : IDisposable where T : class
{
private readonly IFileHelperAsyncEngine<T> _engine;
private bool _disposed = false;
public DataFileConverter()
{
_engine = new FileHelperAsyncEngine<T>();
}
~DataFileConverter()
{
Dispose(false);
}
public bool RemoveHeaderRow
{
get => _engine.Options.IgnoreFirstLines == 1;
set => _engine.Options.IgnoreFirstLines = value ? 1 : 0;
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_engine != null)
{
_engine.Close();
}
}
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public List<T> ReadDataFile(Stream stream)
{
List<T> data = new List<T>();
using var streamReader = new StreamReader(stream);
using (_engine.BeginReadStream(streamReader))
{
foreach (T datum in _engine)
{
data.Add(datum);
}
}
return data;
}
}
using FileHelpers;
using System;
[DelimitedRecord(",")]
public class SomeClass
{
[FieldCaption("column1")]
public string SomeProperty1 { get; set; }
[FieldCaption("column2")]
[FieldConverter(ConverterKind.Date, "yyyy-MM-dd")]
public DateTime SomeProperty2 { get; set; }
}
public class SomeService
{
using DataFileConverter<SomeClass> converter = new DataFileConverter<SomeClass>
{
RemoveHeaderRow = true
};
List<SomeClass> data = converter.ReadDataFile(System.IO.File.OpenRead("path/to/file"));
// do whatever logic with data
}

datagridview count cells c#

I have a problem. I need to count cells that I activate, they are yellow, but I dont know how i can do it. In geniral I need to select only maximum 15 cells, so i need to count them, but all my tries seems so far away. I tried to cteate a counter, but it doest work. Please, help.
dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
//выделение только ячеек
// создаём массив
int[,] Array = new int[8, 10];
byte numbers = 1;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 10; j++)
{
Array[i, j] = numbers;
numbers++;
}
}
dataGridView1.RowCount = 8;
dataGridView1.ColumnCount = 10;
// программно записываем массив и задаём стиль ячеек
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 10; j++)
{
dataGridView1.Columns[j].Width = 30;
dataGridView1.Rows[i].Height = 30;
dataGridView1.Rows[i].Cells[j].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Rows[i].Cells[j].Style.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);
dataGridView1.Rows[i].Cells[j].Value = Array[i, j].ToString();
}
}
}
private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e) // выделение ячеек
{
for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
{
if (dataGridView1.SelectedCells[i].Style.BackColor == Color.Yellow)
{
dataGridView1.SelectedCells[i].Style.BackColor = Color.White;
}
else
{
dataGridView1.SelectedCells[i].Style.BackColor = Color.Yellow;
}
dataGridView1.CurrentCell = null;
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
byte _selected = 0;
for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
{
counter(_selected);
}
}
public void counter(int count)
{
count++;enter code here
MessageBox.Show(count.ToString());
}
Here is how form look.
form
The name of the game is Keno and i try to create it. Maybe i have some mistakes, sorry.
Here's my spin on your code. In this snippet I am using int yellowed to keep track of how many cells are yellow. When a user clicks on a cell, the cell counter sets the yellow count. When the mouse button is up(dataGridView1_CellMouseUp), then only the appropriate number of cells are allowed to be made yellow.
using System.Drawing;
using System.Windows.Forms;
namespace DataGridView_47478857
{
public partial class Form1 : Form
{
DataGridView dataGridView1 = new DataGridView();
int yellowed = 0;
int maxYellowed = 15;
public Form1()
{
InitializeComponent();
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.CellMouseUp += dataGridView1_CellMouseUp;
dataGridView1.CellClick += dataGridView1_CellClick;
this.Controls.Add(dataGridView1);
dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
//выделение только ячеек
// создаём массив
int[,] Array = new int[8, 10];
byte numbers = 1;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 10; j++)
{
Array[i, j] = numbers;
numbers++;
}
}
dataGridView1.RowCount = 8;
dataGridView1.ColumnCount = 10;
// программно записываем массив и задаём стиль ячеек
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 10; j++)
{
dataGridView1.Columns[j].Width = 30;
dataGridView1.Rows[i].Height = 30;
dataGridView1.Rows[i].Cells[j].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Rows[i].Cells[j].Style.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);
dataGridView1.Rows[i].Cells[j].Value = Array[i, j].ToString();
}
}
}
private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e) // выделение ячеек
{
for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
{
if (dataGridView1.SelectedCells[i].Style.BackColor == Color.Yellow)
{
dataGridView1.SelectedCells[i].Style.BackColor = Color.White;
}
else
{
if (yellowed < maxYellowed)//only color code this cell if the yellow cell count has not been exceeded
{
dataGridView1.SelectedCells[i].Style.BackColor = Color.Yellow;
yellowed++;
}
}
}
dataGridView1.ClearSelection();
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
yellowed = 0;
foreach (DataGridViewRow currentRow in dataGridView1.Rows)
{
foreach (DataGridViewCell currentCell in currentRow.Cells)
{
if (currentCell.Style.BackColor == Color.Yellow)
{
yellowed++;
}
}
}
}
}
}
You can use this link to count cell, but you can use another components or WPF to this game.
https://msdn.microsoft.com/en-us/library/x8x9zk5a(v=vs.85).aspx

CheckedListBox.SelectedItems.Count = 1?

In C#, I have checked list boxes, that I need to store the data in arrays, but when I start the event that writes the objects to the array, I have to set the size of the array, which I naturally set to the amount of items checked. However, the items checked, for both checked list boxes I have is 1, no matter how many I check. Can someone help?
public partial class Form3 : Form
{
public static object[] dtype;
public static bool loaded = false;
bool typeselecte = false;
bool typeselectd = false;
public Form3()
{
InitializeComponent();
}
private void Form3_Shown(object sender, EventArgs e)
{
if (loaded)
{
int counte = 0;
int countd = 0;
types1.Items.AddRange(dtype);
types2.Items.AddRange(dtype);
if (typeselecte)
{
for (int i = 0; i < types1.Items.Count; i++)
{
if (i == Form1.enumber[counte])
{
types1.SelectedItems[i] = Form1.esearch[i];
counte++;
}
}
}
if (typeselectd)
{
for (int j = 0; j < types2.Items.Count; j++)
{
if (j == Form1.dnumber[countd])
{
types2.SelectedItems[j] = Form1.dsearch[j];
countd++;
}
}
}
}
}
public void dtypes()
{
dtype = new object[types1.Items.Count];
for (int i = 0; i < types1.Items.Count; i++)
{
dtype[i] = types1.Items[i];
}
}
private void button1_Click(object sender, EventArgs e)
{
if (types1.SelectedItems.Count > 0)
typeselecte = true;
if (types2.SelectedItems.Count > 0)
typeselectd = true;
Form1.esearch = new object[types1.SelectedItems.Count];
Form1.dsearch = new object[types2.SelectedItems.Count];
Form1.enumber = new int[types1.SelectedItems.Count];
Form1.dnumber = new int[types2.SelectedItems.Count];
int counte = 0;
int countd = 0;
if (typeselecte)
{
for (int i = 0; i < types1.SelectedItems.Count; i++)
Form1.esearch[i] = types1.SelectedItems[i];
}
if (typeselectd)
{
for (int j = 0; j < types2.SelectedItems.Count; j++)
Form1.dsearch[j] = types2.SelectedItems[j];
}
if (typeselecte)
{
for (int k = 0; k < types1.Items.Count; k++)
{
if (Form1.esearch[k] == types1.Items[k])
{
Form1.enumber[counte] = k;
counte++;
}
else
{
k--;
}
}
}
if (typeselectd)
{
for (int l = 0; l < types2.Items.Count; l++)
{
if (Form1.dsearch[l] == types2.Items[l])
{
Form1.dnumber[countd] = l;
countd++;
}
else
{
l--;
}
}
}
this.Close();
}
}
Form1.esearch and dsearch are object arrays, which the size hasn't been picked yet, and e and dnumber are int arrays that have unknown size as well, I just didn't feel the need to put in that code.
I believe you need to use the property CheckedItems as opposed to SelectedItems.

Sorting string values without using any method/function

I trying to do sorting without use of any method or function
My Code :
string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };
string name = string.Empty;
Console.WriteLine("Sorted Strings : ");
for (int i = 0; i < names.Length; i++)
{
for (int j = i + 1; j < names.Length; j++)
{
for (int c = 0; c < names.Length; c++)
{
if (names[i][c] > names[j][c])
{
name = names[i];
names[i] = names[j];
names[j] = name;
}
}
}
Console.WriteLine(names[i]);
}
Please let me bring any solution for this code ?
In this code i am getting "Index was outside the bounds of the array" exception
int temp = 0;
int[] arr = new int[] { 20, 65, 98, 71, 64, 11, 2, 80, 5, 6, 100, 50, 13, 9, 80, 454 };
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i] > arr[j])
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
Console.WriteLine(arr[i]);
}
Console.ReadKey();
You need to implement a sorting algorithm.
A very simple algorithm you can implement is the insertion sort:
string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };
for (int i = 0; i < names.Length; i++)
{
var x = names[i];
var j = i;
while(j > 0 && names[j-1].CompareTo(x) > 0)
{
names[j] = names[j-1];
j = j-1;
}
names[j] = x;
}
string[] names = { "Flag", "Next", "Cup", "Burg", "Yatch", "Nest" };
string name = string.Empty;
Console.WriteLine("Sorted Strings : ");
for (int i = 0; i < names.Length; i++)
{
int c = 0;
for (int j = 1; j < names.Length; j++)
{
if (j > i)
{
Sort:
if (names[i][c] != names[j][c])
{
if (names[i][c] > names[j][c])
{
name = names[i];
names[i] = names[j];
names[j] = name;
}
}
else
{
c = c + 1;
goto Sort;
}
}
}
Console.WriteLine(names[i]);
}
I you were conflicting in length of names array and comparing string. Below is the working solution . I have tested it it's working now
static void Main(string[] args)
{
int min=0;
string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };
string name = string.Empty;
Console.WriteLine("Sorted Strings : ");
for (int i = 0; i < names.Length-1; i++)
{
for (int j = i + 1; j < names.Length;j++ )
{
if(names[i].Length < names[j].Length)
min =names[i].Length;
else
min =names[j].Length;
for(int k=0; k<min;k++)
{
if (names[i][k] > names[j][k])
{
name = names[i].ToString();
names[i] = names[j];
names[j] = name;
break;
}
else if(names[i][k] == names[j][k])
{
continue;
}
else
{
break;
}
}
}
}
for(int i= 0;i<names.Length;i++)
{
Console.WriteLine(names[i]);
Console.ReadLine();
}
}
}
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] {9,1,6,3,7,2,4};
int temp = 0;
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length;j++)
{
if(arr[i]>arr[j])
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
Console.Write(arr[i]+",");
}
Console.ReadLine();
}
for (int i = 0; i < names.Length; i++)
{
string temp = "";
for (int j = i + 1; j < names.Length; j++)
{
if (names[i].CompareTo(names[j]) > 0)
{
temp = names[j];
names[j] = names[i];
names[i] = temp;
}
}
}
public int compareing(string a, string b)
{
char[] one = a.ToLower().ToCharArray();
char[] two = b.ToLower().ToCharArray();
int ret = 0;
for (int i = 0; i < one.Length; i++)
{
for (int j = 0; j < two.Length; j++)
{
Loop:
int val = 0;
int val2 = 0;
string c = one[i].ToString();
char[] c1 = c.ToCharArray();
byte[] b1 = ASCIIEncoding.ASCII.GetBytes(c1);
string A = two[j].ToString();
char[] a1 = A.ToCharArray();
byte[] d1 = ASCIIEncoding.ASCII.GetBytes(a1);
int sec = d1[0];
int fir = b1[0];
if (fir > sec)
{
return ret = 1;
break;
}
else
{
if (fir == sec)
{
j = j + 1;
i = i + 1;
if (one.Length == i)
{
return ret = 0;
}
goto Loop;
}
else
{
return 0;
}
}
}
}
return ret;
}
public void stringcomparision(List<string> li)
{
string temp = "";
for(int i=0;i<li.Count;i++)
{
for(int j=i+1;j<li.Count;j++)
{
if(compareing(li[i],li[j])>0)
{
//if grater than it throw 1 else -1
temp = li[j];
li[j] = li[i];
li[i] = temp;
}
}
}
Console.WriteLine(li);
}
for (int i = 0; i < names.Length - 1; i++)
{
string temp = string.Empty;
for (int j = i + 1; j < names.Length; j++)
{
if (names[i][0] > names[j][0])
{
temp = names[i].ToString();
names[i] = names[j].ToString();
names[j] = temp;
}
}
}
for (int i = 0; i < names.Length - 1; i++)
{
int l = 0;
if (names[i][0] == names[i + 1][0])
{
string temp = string.Empty;
if (names[i].Length > names[i + 1].Length)
l = names[i + 1].Length;
else
l = names[i].Length;
for (int j = 0; j < l; j++)
{
if (names[i][j] != names[i + 1][j])
{
if (names[i][j] > names[i + 1][j])
{
temp = names[i].ToString();
names[i] = names[i + 1].ToString();
names[i + 1] = temp;
}
break;
}
}
}
}
foreach (var item in names)
{
Console.WriteLine(item.ToString());
}
string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };
string temp = "";
int tempX = 0, tempY = 0;
int tempX1 = 0, tempY1 = 0;
for (int i = 0; i<names.Length; i++)
{
for (int j = i+1; j<names.Length; j++)
{
if (((string)names[i])[0] > ((string)names[j])[0])
{
temp=(string)names[i];
names[i]=names[j];
names[j]=temp;
}
else if (((string)names[i])[0] == ((string)names[j])[0])
{
tempX=0; tempY=0;
tempX1=names[i].Length;
tempY1=names[j].Length;
while (tempX1 > 0 && tempY1 >0)
{
if (((string)names[i])[tempX] !=((string)names[j])[tempY])
{
if (((string)names[i])[tempX]>((string)names[j])[tempY])
{
temp=(string)names[i];
names[i]=names[j];
names[j]=temp;
break;
}
}
tempX++;
tempY++;
tempX1--;
tempY1--;
}
}
}
}
You can do it using bubble sort:
Assume you have the array of names called name
The tempName is just to not change the original array (You can use the original array instead)
void sortStudentsAlphabetically()
{
int nameIndex;
string temp;
string[] tempName = name;
bool swapped = true;
for(int i = 0; i < name.Length-1 && swapped ; i++)
{
swapped = false;
for(int j = 0; j < name.Length-1; j++)
{
nameIndex = 0;
recheck:
if (name[j][nameIndex]> name[j+1][nameIndex])
{
temp = tempName[j];
tempName[j] = tempName[j+1];
tempName[j+1] = temp;
swapped = true;
}
if (name[j][nameIndex] == name[j + 1][nameIndex])
{
nameIndex++;
goto recheck;
}
}
}
foreach(string x in tempName)
{
Console.WriteLine(x);
}
}
User Below code :
int[] arrayList = new int[] {2,9,4,3,5,1,7};
int temp = 0;
for (int i = 0; i <= arrayList.Length-1; i++)
{
for (int j = i+1; j < arrayList.Length; j++)
{
if (arrayList[i] > arrayList[j])
{
temp = arrayList[i];
arrayList[i] = arrayList[j];
arrayList[j] = temp;
}
}
}
Console.WriteLine("Sorting array in ascending order : ");
foreach (var item in arrayList)
{
Console.WriteLine(item);
}
Console.ReadLine();
Output:
Sorting array in ascending order : 1 2 3 4 5 7 9

Categories