我已经在datagridview中读取了textfile中的数据现在我想在用户在运行时更改datagridview值时对文本文件进行更改吗? 这是我现在读取文件的代码,我想更新该特定位置的文本文件中的数据并写入..
private void button1_Click(object sender, EventArgs e)
{
string line = "";
string text = "";
bool si = false;
int w = 0;
bool t = false;
bool counter = false;
int length = 0;
const Int32 BufferSize = 128;
int groupid = -1;
int stringid = -1;
string[] split;
int tnog = 0;
if (file.Contains("random.TST"))
{
using (var fileStream = File.OpenRead(this.file))
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize))
while ((line = streamReader.ReadLine()) != null)
{
if (line.Contains('$') && (line.Contains('@') || line.Contains('}')))
{
split = line.Split(' ', '@', '}');
}
else if (line.Contains('$'))
{
}
else if (line.Contains('|'))
{
counter = false;
}
else if (!(counter))
{
split = line.Split(' ', '@');
for (int i = 0; i < split.Length; i++)
{
if (t)
{ }
else if (!t)
{
if (split[i].Trim() == "")
{
groupid = 0;
}
else if (split[i].Trim() != "")
{
groupid = Convert.ToInt16(split[i]);
t = true;
tnog++;
}
}
counter = true;
}
}
else if (counter)
{
//split = line.Split(' ');
if (line.Contains('|'))
{
counter = false;
}
else if (counter)
{
split = line.Split(' ', '@', '}');
for (int i = 0; i < split.Length; i++)
{
if (si)
{
if (split[i].Trim() == "")
{
//text[i] = " ";
}
else if (split[i].Trim() != "")
{
text += Convert.ToString(split[i]);
text += " ";
length = text.Length;
}
}
else if (!si)
{
if (split[i].Trim() == "")
{
// sid[i] = 0;
}
else if (split[i].Trim() != "")
{
stringid = Convert.ToInt16(split[i]);
si = true;
}
}
}
if ((groupid == -1) || (stringid == -1))
{ }
else
{
dataGridView1.Rows.Add(groupid, stringid, text, length);
text = "";
if (tnog % 2 == 0)
{
dataGridView1.Rows[w].DefaultCellStyle.ForeColor = Color.Gray;
dataGridView1.Rows[w].DefaultCellStyle.BackColor = Color.Yellow;
}
else
{
dataGridView1.Rows[w].DefaultCellStyle.ForeColor = Color.Plum;
dataGridView1.Rows[w].DefaultCellStyle.BackColor = Color.RoyalBlue;
}
w++;
}
si = false;
t = false;
}
}
}
textBox1.Text = Convert.ToString(tnog);
}
else
{
MessageBox.Show("Invalid File:");
}
}
答案 0 :(得分:0)
你真的应该考虑将数据绑定到datagridview(你可以从文件中给我们一些示例行吗?),但如果不是......
将整个文件读入字符串,并使用唯一的占位符计数器替换所有相关值,即{1},{2}。在将字符串写回文件之前,用datagridview数据替换占位符计数器。