0
我想从c#中的文本文件导出数据到gridview。文本文件只包含数字。 文本文件格式 1313232,12323232,7676768,8786868 ......从文本文件导出数据到gridview
我需要设置表格列为10,然后是新行,直到文本文件中的数字完成。 谢谢。
我想从c#中的文本文件导出数据到gridview。文本文件只包含数字。 文本文件格式 1313232,12323232,7676768,8786868 ......从文本文件导出数据到gridview
我需要设置表格列为10,然后是新行,直到文本文件中的数字完成。 谢谢。
我希望这不是你的功课。如果是这样,请尽你的责任来改进这个有点代码的代码。您还必须使用System.IO读入文件并将其存入字符串中。
ASP.NET
<asp:GridView ID="gvNumbers" runat="server" AutoGenerateColumns="true"></asp:GridView>
C#
var dt = new DataTable();
string fileText = "1313232 , 12323232, 7676768, 8786868,1313232 , 12323232, 7676768, 8786868,1313232 , 10, 7676768, 8786868,1313232 , 12323232, 7676768, 8786868,1313232 , 12323232, 7676768, 20,1313232 , 12323232, 7676768, 8786868,1313232 , 12323232, 7676768, 8786868,1313232 , 12323232, 7676768, 8786868,";
string[] nums = fileText.Split(',');
//set up columns
for (int i = 1; i < 11; i++)
{
dt.Columns.Add("Col" + i, typeof(int)); //add integer columns and name them
}
int colCount = 0;
int[] oneRow = new int[10];
int n, failCount = 0;
foreach (string s in nums)
{
if (int.TryParse(s, out n))
{
oneRow[colCount] = n;
colCount++;
}
else //invalid integer
{
failCount++; //you could use this value if you want to see if the file was fully valid or not.
}
//check if row is complete
if (colCount == 10)
{
dt.Rows.Add(oneRow[0], oneRow[1], oneRow[2], oneRow[3], oneRow[4], oneRow[5], oneRow[6], oneRow[7], oneRow[8], oneRow[9]);
colCount = 0;
oneRow = new int[10]; //reset array
}
}
if (colCount > 0) dt.Rows.Add(oneRow[0], oneRow[1], oneRow[2], oneRow[3], oneRow[4], oneRow[5], oneRow[6], oneRow[7], oneRow[8], oneRow[9]); //add final incomplete row
//reference the DataTable as a source to the GridView and bind it.
gvNumbers.DataSource = dt;
gvNumbers.DataBind();
导入使用的读取器,.Split( '')的字符串的文件作为单个串,解析所得到的阵列,并创建一个方式将其存入DataTable中。使用DataTable作为GridView的源代码并绑定它。你有没有尝试过你的例子? – secretwep