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