输入数据后,我想将datagridview转换为ini文件。
http://www.hoons.net/Board/qacshap/Content/67073
当我在上方输入网址时,
我尝试将数据放入网格中,然后按导出按钮以节,键,值的形式将其另存为.ini文件。我该怎么办?在代码内部,内容创建为ini文件,而不是网格。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
namespace EXPORT
{
public partial class Form1 : DevExpress.XtraEditors.XtraForm
{
[DllImport('kernel32')]
public static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport('kernel32')]
public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
static string path = 'C:\\Test.ini';
public Form1()
{
InitializeComponent();
dataGridView1.AllowUserToAddRows =true; //자동 행 추가
dataGridView1.AutoGenerateColumns = false;
}
private void button1_Click(object sender, EventArgs e)
{
WritePrivateProfileString('SECTION', 'KEY', 'VALUE', @'C:\ConnectionInfo.ini');
MessageBox.Show('EXPORT successfully to *.INI format');
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void WriteInFile(string section,string key,string value,string path)
{
WritePrivateProfileString(section, key, value, path);
if (value == null)
{
throw new ArgumentException();
}
}
private void button2_Click(object sender, EventArgs e) //ADD_ROW Button
{
DataGridViewButtonColumn button = new DataGridViewButtonColumn();
{
dataGridView1.Rows.Add();
}
}
}
}
答案 0 :(得分:0)
您可以使用我的MadMilkman.Ini库,方法如下:
private void button1_Click(object sender, EventArgs e)
{
IniFile iniFile = new IniFile();
IniSection iniSection = null;
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
if (row.IsNewRow)
break;
string section = row.Cells[0].Value?.ToString();
string key = row.Cells[1].Value.ToString();
string value = row.Cells[2].Value.ToString();
if (!string.IsNullOrEmpty(section))
iniSection = iniFile.Sections.Add(section);
iniSection.Keys.Add(key, value);
}
iniFile.Save("C:\\Test.ini");
}
此外,这是生成的“ Test.ini”文件的样子:
[a]
123=456
789=234
345=678
[b]
123=456
789=234
345=678