【发布时间】:2011-06-19 18:26:42
【问题描述】:
我有一个从列表中填充的 DataGridView。编辑此列表的函数称为LoadCollectionData()'。额外的行被添加到列表中就好了,与该行相关的相关数据会在添加行时填充。
问题是,稍后当其他数据被更改时,会改变数据网格上显示的内容,只有顶行继续更新,所有其他数据保持不变。
这是该方法的代码:
public bool haschanged = false;
public class KeywordDensity
{
public bool included { get; set; }
public string keyword { get; set; }
public string occurences { get; set; }
public string density { get; set; }
}
public int WordCount(string txtToCount)
{
string pattern = "\\w+";
Regex regex = new Regex(pattern);
int CountedWords = regex.Matches(txtToCount).Count;
return CountedWords;
}
public int KeywordCount(string txtToCount, string pattern)
{
Regex regex = new Regex(pattern);
int CountedWords = regex.Matches(txtToCount).Count;
return CountedWords;
}
public List<KeywordDensity> LoadCollectionData()
{
string thearticle = txtArticle.Text.ToLower();
string keywordslower = txtKeywords.Text.ToLower();
string[] keywordsarray = keywordslower.Split('\r');
List<KeywordDensity> lsikeywords = new List<KeywordDensity>();
bool isincluded = false;
double keywordcount = 0;
double wordcount = WordCount(thearticle);
double thedensity = 0;
foreach (string s in keywordsarray)
{
if (s != "")
{
keywordcount = KeywordCount(thearticle, s);
thedensity = keywordcount / wordcount;
thedensity = Math.Round(thedensity, 4) * 100;
if (thearticle.Contains(s))
{
isincluded = true;
}
else
{
isincluded = false;
}
lsikeywords.Add(new KeywordDensity()
{
included = isincluded,
keyword = s,
occurences = keywordcount.ToString(),
density = thedensity.ToString() + "%"
});
}
}
return lsikeywords;
}
private void txtArticle_TextChanged(object sender, EventArgs e)
{
if (haschanged == false)
haschanged = true;
lblWordCountNum.Text = WordCount(txtArticle.Text).ToString();
dataGrid.DataSource = LoadCollectionData();
}
private void dataGrid_MouseUp(object sender, MouseEventArgs e)
{
int cursorpos = 0;
string copied = "";
if (dataGrid.CurrentCellAddress.X == 1) //Only grab content if the "Keyword" column has been clicked on
copied = " " + dataGrid.CurrentCell.Value.ToString() + " ";
cursorpos = txtArticle.SelectionStart;
txtArticle.Text = txtArticle.Text.Insert(cursorpos, copied);
}
更奇怪的是,当我点击任何一行时,它们会立即更新。但是,除非单击该行(除非它是最上面的行),否则它不会更新。
因此,我怀疑可能需要在 dataGrid 本身上设置一些属性,或者我需要以某种方式告诉每一行通过代码刷新。
什么是dealio?
编辑:似乎点击更新的单元格的唯一原因是因为我主动从单元格中抓取内容。我注释掉了下面的代码,即使单击它也停止更新。然后它只会更新第一行的值,就是这样。
代码:
//Moved above in EDIT 3
编辑 2:这是 KeywordDensity 的类声明:
//Moved above in EDIT 3
编辑 3:张贴整个 schebang。
【问题讨论】:
-
如何将数据源分配给网格
-
是的。当我在主文本框中更改文本时,我调用:dataGrid.Datasource = LoadCollectionData();
-
好的,看来我们现在需要查看整个代码.. 你能展示一下吗...
-
好的,该死的贴在整个项目附近。如果有一种方法可以发布 DataGridView 的属性,我也会这样做,尽管我已经删除了当前的,并尝试了一个全新的代码,该代码没有以任何方式从默认值更改,它仍然做了同样的事情。感谢 Shekhar_Pro!
-
有趣.. 在这篇文章中,我在 MSDN 论坛上发现它提到了一个问题,即选中的 DataGridView 行会干扰他的更新。 - social.msdn.microsoft.com/forums/en-us/winformsdatacontrols/… - 我注意到,只要我开始输入 DataGridView 的第一行,即使它没有焦点,它也会被选中。
标签: c# windows winforms visual-studio-2010 datagridview