从文本文件 C# 向表单添加表
本文关键字:表单 添加 文本 文件 | 更新日期: 2023-09-27 18:36:47
我有一个文本文件,上面有两个表格,如下所示
1:"Transmitter",1,grid,32,6
2:"Parameters", 2,list,64
我想在我的表单中显示两个表,如果需要,用户可以向文本文件添加更多表。如果用户向窗体中添加更多表,则其他表将显示在窗体中。
我正在使用选项卡控件将选项卡添加到文件中指定的表单中,对于表,我正在使用数据网格视图
这是我的代码:
public partial class Form1 : Form
{
String line;
String typeOfTable;
int amountOfRows;
int amountOfColumns;
private const String TABS = "TABS";
private const String TABLES = "TABLES";
private const String GRID = "grid";
private const String LIST = "list";
private const int LOCATION_TABLE_TYPE = 2;
private const int LOCATION_TABLE_AMOUNT_ROWS = 3;
private const int LOCATION_TABLE_AMOUNT_COLUMNS = 4;
private const int AMOUNT_Columns_IN_LIST = 2;
String[] splitTableArray;
public Form1()
{
InitializeComponent();
getFormContentFromFile();
}
private void getFormContentFromFile()
{
using (StreamReader reader = new StreamReader("neo2G.res"))
{
while (!reader.EndOfStream)
{
line = reader.ReadLine();
if (line.Equals(TABS))
{
while (!line.Equals(".."))
{
line = reader.ReadLine();
if (!line.Equals(".."))
{
createTabInForm(line);
}
}
}
if (line.Equals(TABLES))
{
while (!line.Equals(".."))
{
line = reader.ReadLine();
if (!line.Equals(".."))
{
splitTableLineToArray(line);
typeOfTable = splitTableArray[LOCATION_TABLE_TYPE];
amountOfRows = int.Parse(splitTableArray[LOCATION_TABLE_AMOUNT_ROWS]);
if(typeOfTable.Equals(GRID))
{
amountOfColumns = int.Parse(splitTableArray[LOCATION_TABLE_AMOUNT_COLUMNS]);
dataGridView1.DataSource = createGridForForm(amountOfRows, amountOfColumns);
}
else if( typeOfTable.Equals(LIST))
{
dataGridView1.DataSource = createListForForm(amountOfRows);
}
}
}
}
}
}
}
private void createTabInForm(String tabName)
{
tabName = Regex.Replace(tabName, @"['d-]", string.Empty);
tabName = tabName.Trim(':', '"');
TabPage myTabPage = new TabPage(tabName);
tabControl1.TabPages.Add(myTabPage);
}
private void splitTableLineToArray(String tableLine)
{
splitTableArray = tableLine.Split(',');
}
public DataTable createGridForForm(int rows, int columns)
{
// Create the output table.
DataTable table = new DataTable();
for (int i = 1; i <= columns; i++)
{
table.Columns.Add("column " + i.ToString());
}
for (int i = 1; i < rows; i++)
{
DataRow dr = table.NewRow();
// populate data row with values here
table.Rows.Add(dr);
}
return table;
}
/// <summary>
/// This method builds a DataTable of the data.
/// </summary>
public DataTable createListForForm(int rows)
{
// Create the output table.
DataTable table = new DataTable();
for (int i = 1; i <= AMOUNT_Columns_IN_LIST ; i++)
{
table.Columns.Add("My column " + i.ToString());
}
for (int i = 1; i < rows; i++)
{
DataRow dr = table.NewRow();
// populate data row with values here
table.Rows.Add(dr);
}
return table;
}
}
}
使用设计器添加一个或(更好的)两个表。
分析设计器添加的代码,并将其用作从代码添加表的起点。