我有 datagridview 从文件中读取一些字符串和一些日期。这是我用来存储这些数据的字典(用于添加新记录和存储日期时间值)
private Dictionary<string, DateTime> gDict = new Dictionary<string, DateTime>();
这就是我将数据保存到文件的方式:
public bool SaveTableToFile()
{
System.Data.DataTable curr_table = dgv.DataSource as System.Data.DataTable;
try
{
using (System.IO.StreamWriter strwr = new System.IO.StreamWriter(filePath + @"\" + fileName, false))
{
strwr.WriteLine("__FILE_BEGIN__");
foreach (KeyValuePair<string, DateTime> kvp in gDict)
{
strwr.WriteLine("__LINE_BEGIN__");
strwr.WriteLine("Date=" + kvp.Value.ToString("dd.MM.yyyy hh:mm:ss"));
strwr.WriteLine("IP=" + kvp.Key);
strwr.WriteLine("__EOL__");
strwr.Flush();
}
strwr.WriteLine("__EOF__");
strwr.Close();
return true;
}
}
catch { return false; }
}
//刚刚注意到我错过了finally块,我的捕获很糟糕
这就是我从文件http://pastebin.com/uZN4CdxZ中读取它的方式
此日期在表格中显示为时间跨度 -
DateTime now = DateTime.Now;
...
DateTime dt = new DateTime();//15.03.2013 3:01:13 //dd.MM.yyyy hh:mm:ss
dt = DateTime.ParseExact(preparedString[1], "dd.MM.yyyy hh:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
TimeSpan timediff = (now - dt);
当我运行我的程序时,它会从文件中读取所有条目,计算时间差并将其显示在表格中。还有问题 - 所有时差都是错误的,它有额外的 12 小时。
当我在加载表格后添加新行时
public void TryAddNewRow(string ex_IP)
{
if (!gDict.ContainsKey(ex_IP))
{
System.Data.DataTable curr_table = dgv.DataSource as System.Data.DataTable;
System.Data.DataRow theRow = curr_table.NewRow();
DateTime dt = DateTime.Now;
theRow["Date"] = (dt - DateTime.Now);
theRow["IP"] = ex_IP;
curr_table.Rows.Add(theRow);
gDict.Add(ex_IP, dt);
}
else
{
TimeSpan ts = DateTime.Now - gDict[ex_IP];
System.Windows.Forms.MessageBox.Show("IP already exists, it was used" + Environment.NewLine + ts.Hours+" hours, "+ts.Minutes +" minutes, and "+ts.Seconds+" seconds ago.");
}
}
首先它显示零(类似于 0:00:00)。但是,当每分钟运行一次的计时器刷新表时,它就变成了 12 小时 1 分钟。
private void timer1_Tick(object sender, EventArgs e)
{
gTable.SaveTableToFile();
gTable.UpdateTable();
label1.Text = DateTime.Now.ToString("HH:mm.ff") + ": Table updated.";
}
public void UpdateTable()
{
CreateNewDataSource();
//reading data from file and creating rows
ReadTableFromFile();
}
private void CreateNewDataSource()
{
dgv.DataSource = null;
System.Data.DataSet myDataSet = new System.Data.DataSet();
System.Data.DataTable aTable = new System.Data.DataTable("Table 1");
myDataSet.Tables.Add("Table 1");
List<System.Data.DataColumn> columnsList = new List<System.Data.DataColumn>();
foreach (TableField curr_field in fTableFields.ftfList)
columnsList.Add(new System.Data.DataColumn(curr_field.Name, curr_field.FieldType));
foreach (System.Data.DataColumn column in columnsList)
myDataSet.Tables["Table 1"].Columns.Add(column);
dgv.DataSource = myDataSet.Tables["Table 1"];
foreach (TableField curr_field in fTableFields.ftfList)
dgv.Columns[curr_field.Name].Width = curr_field.HeaderWidth;
}