How to export specific number of rows? - c#

I want to export specific number of rows. For example, I want to just export 500 rows or 100 rows. I am stuck with this code.
private void Form1_Load_1(object sender, EventArgs e)
{
// TODO: This line of code loads data into the '_GPS_TrackerDataSet.ParsedReadings' table. You can move, or remove it, as needed.
this.parsedReadingsTableAdapter.Fill(this._GPS_TrackerDataSet.ParsedReadings);
}
private void button1_Click_1(object sender, EventArgs e)
{
using (SaveFileDialog SFD = new SaveFileDialog() { Filter = "Excel Workbook |*.xlsx" })
{
if (SFD.ShowDialog() == DialogResult.OK)
{
try
{
XLWorkbook XLW = new XLWorkbook();
XLW.Worksheets.Add(this._GPS_TrackerDataSet.ParsedReadings.CopyToDataTable(), "ParsedReadings");
XLW.SaveAs(SFD.FileName);
MessageBox.Show("Success.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

You can use some LINQ to extract nth number of rows from the DataSet.
DataTable table = _GPS_TrackerDataSet.Tables[0].AsEnumerable().ToList().Take(100).CopyToDataTable();
This assumes the you are using the first table in the dataset, and you want the first 100.

Related

I need to filter my DataGridView with selected column

I'm developing a generic SQLManipulator with Windows Forms. I need to Filter my columns but I don't know how to convert:
private void AdvancedDataGridView_FilterStringChanged(object sender, EventArgs e)
{
this.customerBindingSource.Sort = this.advancedDataGridView.SortStrings;
}
That's not my code I watched it from that tutorial. My application is not connected with DB. I have login form that when you enter server Name you get a combobox with DB names and than you are transferred to the next form, choose table here, and datagridview is populated.
That's how my form looks like:
But everytime the column will be with different names?
I'm not really sure what should I do here?
And do I need to convert customerBindingSource, or I should do something else?
I'm able to do this by using BindingSource
Filter columns
private void AdvancedDataGridView_FilterStringChanged(object sender, EventArgs e)
{
try
{
BindingSource source1 = new BindingSource();
source1.DataSource = AdvancedDataGridView.DataSource;
AdvancedDataGridView.DataSource = source1;
source1.Filter = AdvancedDataGridView.FilterString;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Sorting columns
private void AdvancedDataGridView_SortStringChanged(object sender, EventArgs e)
{
try
{
BindingSource source1 = new BindingSource();
source1.DataSource = AdvancedDataGridView.DataSource;
AdvancedDataGridView.DataSource = source1;
source1.Sort = AdvancedDataGridView.SortString;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Hope it's help.

If I have a text file with a list of names, how can I sort this list by their last names first using C#?

I'm trying to write a program that will read a text file with a list of names listed like
Michael Jordan
Kobe Bryant
Larry Bird
Lebron James
I've written the code to open the file and rewrite the file and included it.
Once Loaded how can I sort this list by Last Name and then by First name?
List<string> cstrName = new List<string>();
private void Sorter_Load(object sender, EventArgs e)
{
try
{
//Load the array with the data in the file
FileStream nameFile = new FileStream("input.txt",FileMode.Open);
StreamReader nameStreamReader = new StreamReader(nameFile);
while (nameStreamReader.Peek() != -1)
{
cstrName.Add(nameStreamReader.ReadLine());
}//End Loop
nameFile.Close(); //Close file
}
//Sets an error message if there is an issue opening the file
catch (Exception ex)
{
MessageBox.Show("Error Opening File. Data not loaded " +
ex.Message,"File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void btnSortByName_Click(object sender, EventArgs e)
{
{
cstrName.Sort();
}
//display names in a list box
displayNames();
}
private void button1_Click(object sender, EventArgs e)
{
System.IO.File.WriteAllLines("input2.txt", cstrName);
this.Close();
}
Swap your cstrName.Sort(); for
cstrName = cstrName.OrderBy(x => x.Split(' ').Last()).ToList();
Make sure you have Using System.Linq; at the top of your file.
It orders cstrName by the last word in the string (working out words by splitting the string by spaces ' ').

Rename a file listed on C# windows form listBox

I am new to C#. I am working on a Windows Form that should do the following:
Browse files on local drive
Allow the user to select files
List the selected files in a listBox
Allow the user to input a new file name and, when they click the rename button, it renames the selected file in the ListBox.
I am not able to do step 4 as the new text is changed in the listBox but the actual file name is still the same in folder. How can I do that? I have listed below the Form.cs
Thank you.
public partial class everSupportForm : Form
{
private void buttonSelect_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
var myDialog = new OpenFileDialog();
myDialog.InitialDirectory = #"c:\";
myDialog.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
// + "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" //If you want to add filters for browsing only images.
myDialog.FilterIndex = 1;
myDialog.RestoreDirectory = true;
myDialog.Multiselect = true;
myDialog.Title = "Please Select File(s) to Rename";
if (myDialog.ShowDialog() != DialogResult.OK) return;
{
foreach (var file in myDialog.FileNames)
{
try
{
if ((myStream = myDialog.OpenFile()) != null)
{
using (myStream)
{
outputListBox.Items.Add(System.IO.Path.GetFileName(file));
}
}
}
catch (Exception ex)
{
// Could not load File specifying the causes
MessageBox.Show("Cannot display the File");
}
}
}
}
private void buttonExit_Click(object sender, EventArgs e) => Application.Exit();
// Removes a selected item
private void buttonRemove_Click(object sender, EventArgs e)
{
if (outputListBox.SelectedIndex >= 0)
outputListBox.Items.RemoveAt(outputListBox.SelectedIndex);
}
// Clears the listed images ListBox
private void buttonClear_Click(object sender, EventArgs e) => outputListBox.Items.Clear();
private void buttonRename_Click(object sender, EventArgs e)
{
if (outputListBox.SelectedIndex >= 0)
outputListBox.Items[outputListBox.SelectedIndex] = newNametextBox.Text;
else MessageBox.Show("There is no Files in the Above list to be Selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
First of all, you have a problem here.
You're adding the files names using Path.GetFileName, so you won't have the files paths anymore => you can't rename them.
Solution 1 - Adding the paths to the listbox
You simple remove the Path.GetFileName and in when the rename button is clicked, you use an InputBox to ask the user for the new file name:
N.B: Add a reference to Microsoft.VisualBasic, InputBoxis in the Microsoft.VisualBasic.Interaction namespace.
private void buttonRename_Click(object sender, EventArgs e)
{
if (outputListBox.SelectedIndex >=0)
{
string fileToRename = outputListBox.Items[outputListBox.SelectedIndex].ToString();
string newFileName = InputBox("Please enter the new file's name:", "Rename file", "Default value");
if (!string.IsNullOrEmpty(newFileName))
{
string fileName = Path.GetFileName(fileToRename);
string newFilePath = fileToRename.Replace(fileName, newFileName);
System.IO.File.Move(fileToRename, newFilePath);
outputListBox.Items[outputListBox.SelectedIndex] = newFilePath;
}
}
else
{
MessageBox.Show("There is no Files in the Above list to be Selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Solution 2 -- Keep a seperate list containing the paths
The concept is the same as the first solution, but instead of adding the file paths to your listbox, you add the file names but you keep a seperate list of paths that is synced with your listbox.
Meaning that, if you modify the listbox, modify the list of paths.
After that you can access the file paths using the listbox's SelectedIndex (since they are synced).

Howto edit selected row but save as new row (textBox, DataGridView, SQL)

Im totaly new to coding but im trying to learn:)
In the application Im working on I have a button that adds a new row
Edit(true);
dbDocSet.DocData.AddDocDataRow(dbDocSet.DocData.NewDocDataRow());
docDataBindingSource.MoveLast();
and then I save from textboxes with another button
Edit(false);
docDataBindingSource.EndEdit();
docDataTableAdapter.Update(dbDocSet.DocData);
dataGridView1.Refresh();
I can also edit a row
Edit(true);
How can I edit a row but after edit save it to a new row instead of overwriting the one im editing?
Or, maybe I shold change it to work like this:
Instead of
- Add new row with newbutton
- Fill in textboxes
- Save with savebutton
Do like this:
- Fill in textboxes
- Save to new row with savebutton
Edit:
- Populate textboxes by selecting a row
- Make changes in textboxes
- Save to same row with changebuttonenter image description here
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Rectangle resolutionRect = System.Windows.Forms.Screen.FromControl(this).Bounds;
if (this.Width >= resolutionRect.Width || this.Height >= resolutionRect.Height)
{
this.WindowState = FormWindowState.Maximized;
}
this.docDataTableAdapter.Fill(this.dbDocSet.DocData);
Edit(false);
}
private void Edit(bool value)
{
textBox1.Enabled = value;
textBox2.Enabled = value;
textBox3.Enabled = value;
And then more textBox.Enable = value (143 st)
private void button1_Click(object sender, EventArgs e)
{ //-----Nytt dokument-----
try
{
Edit(true);
dbDocSet.DocData.AddDocDataRow(dbDocSet.DocData.NewDocDataRow());
docDataBindingSource.MoveLast();
textBox1.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
dbDocSet.DocData.RejectChanges();
}
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value.ToString() == "" || dataGridView1.Rows[i].Cells[1].Value.ToString() == "")
{
dataGridView1.Rows.RemoveAt(i);
i--;
}
}
}
private void button3_Click(object sender, EventArgs e)
{ //-----Öppna upp för att kunna ändra-----
Edit(true);
textBox1.Focus();
}
private void button4_Click(object sender, EventArgs e)
{ //-----Avbryt ifyllnad dokument-----
Edit(false);
docDataBindingSource.ResetBindings(false);
}
private void button2_Click(object sender, EventArgs e)
{ //-----Spara dokument-----
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
MessageBox.Show("Dokumenttyp måste anges !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Focus();
}
else
if (string.IsNullOrWhiteSpace(textBox2.Text))
{
MessageBox.Show("Dokumentnamn måste anges !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox2.Focus();
}
else
if (string.IsNullOrWhiteSpace(textBox3.Text))
{
MessageBox.Show("Revision för dokumentet måste anges !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox3.Focus();
}
else
try
{
Edit(false);
docDataBindingSource.EndEdit();
docDataTableAdapter.Update(dbDocSet.DocData);
dataGridView1.Refresh();
textBox1.Focus();
MessageBox.Show("Dokument sparat med lyckat resultat !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
dbDocSet.DocData.RejectChanges();
}
}
private void dataGridView1_KeyDown_1(object sender, KeyEventArgs e)
{ //-----Ta bort valt dokument-----
if (e.KeyCode == Keys.Delete)
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
if (MessageBox.Show("Är du säker på att du vill ta bort dokumentet ?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
}
}
Try using dataGridView1_CellValidating - LINK. It occurs when a cell loses input focus, enabling content validation. So when validating if you want to add new row instead of editing current one, just get current values from row and use it to add new row, and at the end of validating use e.Cancel to cancel row edit.
If you want to copy data from some row to textboxes, make changes in textboxes and then with button add new row you can use dataGridView1_CellClick - LINK. So basically when user click cell, you get that row index of that cell, and then with that you can access every cell of that row. With that you populate textboxes, make some changes, and on save button you just add new row.
If your question is also how to add new row to datagridview you have answer here: LINK

Access Database Not Updating or Inserting or Deleting C# using Table Adapters and DataBinding

I am trying to update my Access File Using Table Adapter .
When i add the Data my DataGridview shows that data has been added or deleted
But when I Check my access file it stays the same
THere is no Compilation Error or No Excetion Error
This is the Following Code
This is the Image of the Data Grid View
....
private void adminFlights_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'appData.Airline' table. You can move, or remove it, as needed.
this.airlineTableAdapter.Fill(this.appData.Airline);
airlineBindingSource.DataSource = this.appData.Airline;
}
private void dataGridView2_KeyDown(object sender, KeyEventArgs e)
{//TO delete data from Data Grid view
if (e.KeyCode == Keys.Delete)
{
MessageBox.Show(e.KeyCode.ToString());
if (MessageBox.Show("Are You Sure You want TO Delete ?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
airlineBindingSource.RemoveCurrent();
}}}
private void btnSave_Click(object sender, EventArgs e)
{//this the Button i am using save the Data into acess using DatagridView
try
{
dataGridView2.DataSource = airlineBindingSource.DataSource;
airlineBindingSource.EndEdit();
airlineTableAdapter.Update(this.appData.Airline);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
}
}
private void Add_flights_Click(object sender, EventArgs e)
{
try
{
panel.Enabled = true;
Airline_add.Focus();
this.appData.Airline.AddAirlineRow(this.appData.Airline.NewAirlineRow());
airlineBindingSource.MoveLast();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
airlineBindingSource.ResetBindings(false);
}
}

Categories