Wayne L Waag Wayne L Waag - 2 months ago 7
C# Question

Access a local variable from one method a different method on a form

I have a very simple form that produces a Datagridview with 4 columns. No problem generating the form. Only the last column can be edited. After editing, I want to hit the OK button and join elements of the list in the last column into a string. How do I make that list (current) available inside the the OK button object sender. Sorry for my poor grammar. I'm an obvious newbie. Thanks.

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Avisynth_Script
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
public string current_values = null;

private void Load_Tweaker(object sender, EventArgs e)
{
string[] deshake_parts = EntryPoint.deshakeSettings.Split(',');
List<String> settings = new List<string>(deshake_parts);
string[] default_values = EntryPoint.deshakeDefaultValues.Split(',');
List<String> defaults = new List<string>(default_values);
string[] current_settings = current_values.Split('|');
//current_settings[0] = current_settings[0].Substring(1);
//current_settings[66] = current_settings[66].Substring(0, 6);
List<String> current = new List<string>(current_settings);

dataGridView1.Rows.Clear();
for (int i=0; i < settings.Count; i++)
{
dataGridView1.Rows.Add(i+1 ,settings[i], defaults[i], current[i]);
}
}

private void OK_button_Click(object sender, EventArgs e)
{
EntryPoint.deshaker_param = string.Join('|', current.ToArray());
}
}


}

Answer

You have an unbound DataGridView with four columns and want to concatenate the values in the fourth column separated by a "|" in the OK_button_Click method.

You could use a foreach loop to iterate each row in the DataGridView's row collection and pull the value from the fourth column (index=3) to achieve this, or you could use a Linq query to perform the iteration.

Here is a Linq solution.

private void OK_button_Click(object sender, EventArgs e)
{
    EntryPoint.deshaker_param = string.Join("|", dataGridView1.Rows.Cast<DataGridViewRow>().Where(row => (!row.IsNewRow)).Select(row =>((row.Cells[3].Value ?? string.Empty).ToString())));
}