我正在尝试创建自定义DataGridViewButtonCell,以便在单击后下载文件。该类完美无缺,但在使用rows.add()方法时不会将自身添加到DataGridView中。它似乎只是为标签使用ToString()方法,然后从CellTemplate创建自己的。
特定列的类型是DataGridViewDownloadColumn。我还运行测试输出网格视图中保存的值,它是正确实例化的类。
这是我没有布局信息的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using MS.Internal.Xml;
using System.Net;
namespace RSS_Catcher
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
XmlReader objReader = XmlReader.Create("http://revision3.com/filmriot/feed/Xvid-Large");
while (objReader.ReadToFollowing("enclosure"))
{
objReader.MoveToFirstAttribute();
Uri objURI = new Uri(objReader.ReadContentAsString());
string[] objString = objURI.Segments;
DownloadButton objDL = new DownloadButton(objURI, objString[objString.Length - 1]);
this.dataGridView1.Rows.Add(false, "Hello!", objDL);
}
}
}
public class DataGridViewDownloadColumn : DataGridViewButtonColumn
{
public DataGridViewDownloadColumn()
{
CellTemplate = new DownloadButton();
}
}
class DownloadButton : DataGridViewButtonCell
{
WebClient objDownloader = new WebClient();
Uri fileURL;
string strSavePath;
public DownloadButton()
{
}
public DownloadButton(Uri fileURI, string strFilename) : base()
{
objDownloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgChanged);
this.fileURL = fileURI;
this.strSavePath = strFilename;
this.Value = "Download";
}
protected override void OnClick(DataGridViewCellEventArgs e)
{
// If it's downloading, cancel the download
if (objDownloader.IsBusy)
{
objDownloader.CancelAsync();
this.Value = "Download";
}
else
objDownloader.DownloadFileAsync(fileURL, strSavePath);
base.OnClick(e);
}
void ProgChanged(object sender, DownloadProgressChangedEventArgs e)
{
this.Value = e.ProgressPercentage + "%";
}
public override string ToString()
{
return
"Download Button:\n" +
this.fileURL.ToString();
}
}
}
我一直在和这个垃圾斗争几个小时。任何帮助表示赞赏。
答案 0 :(得分:0)
似乎由于某种原因,如果使用独立构造函数创建自定义对象,datagridview.rows.add(对象列表)不会删除它。您需要做的是创建一个新行,单独添加单元格,然后将该行放入列表中。
while (objReader.ReadToFollowing("enclosure"))
{
objReader.MoveToFirstAttribute();
Uri objURI = new Uri(objReader.ReadContentAsString());
string[] objString = objURI.Segments;
string strFileName = objString[objString.Length - 1];
// No string constructor?! What the crap?
DataGridViewTextBoxCell objFileCell = new DataGridViewTextBoxCell();
objFileCell.Value = strFileName;
DataGridViewRow objRow = new DataGridViewRow();
objRow.Cells.Add(new DataGridViewCheckBoxCell(false));
objRow.Cells.Add(objFileCell);
objRow.Cells.Add(new DownloadButton(objURI, strFileName));
this.dataGridView1.Rows.Add(objRow);
}