I have this code below that supposed to create a new column on datagridview everytimes a button is clicked, now that when a button is clicked a column named "New Column 1"
will be generated but the thing is I was expecting for the "New Column 1"
to be increment to "New Column 1" "New Column 2" "New Column 3" ...
when a button is clicked for greater than once but "New Column 1"
still appears even on multiple clicks.
What I've tried so far,
private void guna2Button4_Click_1(object sender, EventArgs e) {
guna2DataGridView2.Columns.Clear();
// Add new column
string file_path = @"C:\MAIN_TEXT_LOCATION\" label3.Text "\\" label4.Text;
using (StreamWriter swq = File.AppendText(file_path)) {
var curr = 0;
curr ;
swq.Write("[" "New Column " (curr) "]");
}
// Redefine data source
retrieve_data();
}
I believe I have missing some crucial piece of code that I have to add in order to make it works but since I'm a novice I couldn't think further in order to make it works.
CodePudding user response:
Try This
int curr = 0;
private void guna2Button4_Click_1(object sender, EventArgs e) {
guna2DataGridView2.Columns.Clear();
// Add new column
string file_path = @"C:\MAIN_TEXT_LOCATION\" label3.Text "\\" label4.Text;
using (StreamWriter swq = File.AppendText(file_path)) {
curr ;
swq.Write("[" "New Column " (curr) "]");
}
// Redefine data source
retrieve_data();
}
CodePudding user response:
Here is a solution which gets the last number (int) in a string and increments the number by 1.
Add the following class to your project
public static class Helpers
{
public static string NextValue(this string sender)
{
string value = Regex.Match(sender, "[0-9] $").Value;
return sender[..^value.Length] (long.Parse(value) 1)
.ToString().PadLeft(value.Length, '0');
}
}
Add a private int variable in the form private int _columnIndex = 0;
to keep track of the last number for creating a new column.
In the form add using System.Text.RegularExpressions;
then here in a button click event add a new column
public partial class Form1 : Form
{
private int _columnIndex = 0;
public Form1()
{
InitializeComponent();
}
private void NewColumnButton_Click(object sender, EventArgs e)
{
dataGridView1.Columns.Add(
$"newColumnName{_columnIndex 1}",
$"New Column {_columnIndex}".NextValue());
_columnIndex ;
}
}
I expanded the columns in the screenshot after creating the columns manually.