Hi Masters,
I have few doubts in windows forms, i was imported txt file in tabpage with data gridview and also i have some modification done in that data grid view so now i want to save the data in same file name with same location where i imported
So please give advice with some examples
thank you

Abhishek YadavRank #217 · 11.3K reputationPosted Jul 17, 2024, 11:25 PM EDT
Saving Modified Data from DataGridView Back to the Text File in Windows Forms
To save the modified data in a
DataGridViewback to the same text file from which it was imported, you can follow these steps. Below is an example to guide you through the process:Here's a sample implementation in C#:
using System; using System.Data; using System.IO; using System.Linq; using System.Windows.Forms; public partial class Form1 : Form { private string filePath; public Form1() { InitializeComponent(); } private void btnLoadFile_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"; if (openFileDialog.ShowDialog() == DialogResult.OK) { filePath = openFileDialog.FileName; DataTable dataTable = new DataTable(); string[] lines = File.ReadAllLines(filePath); if (lines.Length > 0) { // Create columns string[] headerLabels = lines[0].Split(','); foreach (string headerWord in headerLabels) { dataTable.Columns.Add(new DataColumn(headerWord)); } // Adding Rows for (int i = 1; i () .Select(column => column.ColumnName) .ToArray(); lines[0] = string.Join(",", columnNames); // Get the Rows Data for (int i = 0; i field.ToString()) .ToArray(); lines[i + 1] = string.Join(",", fields); } File.WriteAllLines(filePath, lines); MessageBox.Show("File saved successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("No file path specified.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }Explanation:
Load Data from Text File to DataGridView
btnLoadFile_Clickmethod handles loading data from a text file into aDataTableand then binding thatDataTableto theDataGridView.Modify Data in DataGridView
DataGridView.Save Modified Data Back to Text File
btnSaveFile_Clickmethod converts theDataTableback to a string array with comma-separated values and writes this array back to the original file path usingFile.WriteAllLines.Conclusion:
This code provides a basic framework to import data from a text file into a
DataGridView, allow modifications, and then save the changes back to the same text file. Adapt this example as needed for your specific requirements.If this helps, please accept the answer to help others who might have the same question!