Download an XML file from the cell click event of DataGridView

Niladri.Biswas
Posted by in C# category on for Beginner level | Points: 250 | Views : 2511 red flag

In this article we will look into as how we can download an XML file from the cell click event of DataGridView.We will prepare the xml file on the fly.


 Download source code for Download an XML file from the cell click event of DataGridView

Introduction

In this article we will look into as how we can download an XML file from the cell click event of DataGridView.We will prepare the xml file on the fly.

Straight to Experiment

First of all let us create an UI by dragging only a "DataGridViewControl" on to the form layout

Next in the code behind create a class as under

public class FileInformation        
{
	public string FileName { get; set; }
	public string Download { get { return "Download File"; } }        
}

This class holds the information about "FileName" and the "Download" link

Next let us write the code that will give a good look and fell to our grid

private void PrepareGrid()
{

	var fileNameColumn = new DataGridViewTextBoxColumn
	{
		Name = @"FileName",
		HeaderText = "File Name",
		DataPropertyName = @"FileName",
		AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
		ReadOnly = false,
		Frozen = false
	};
	dataGridView1.Columns.Add(fileNameColumn);

	var downloadColumn = new DataGridViewLinkColumn

	{
		Name = @"Download",
		HeaderText = @"Download",
		DataPropertyName = @"Download",
		AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
		ReadOnly = true
	};
	dataGridView1.Columns.Add(downloadColumn);
	this.dataGridView1.AllowUserToAddRows = false;
	this.dataGridView1.AllowUserToDeleteRows = false;
	this.dataGridView1.AllowUserToResizeRows = false;
	this.dataGridView1.RowHeadersVisible = false;
	this.dataGridView1.MultiSelect = false;
	this.dataGridView1.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
	this.dataGridView1.AutoGenerateColumns = false; 
}

In the "PrepareGrid()" method, we are giving mainly a Name, HeaderText and DataPropertyName to the columns that should participate in the DataGridViewControl.

Once done, the next task is to populate teh grid content

private void DisplayResult()
{
	lstScriptInfo = LoadItems();
	dataGridView1.DataSource = lstScriptInfo;
}

private List LoadItems()
{
	var lstScriptInfo = new List();
	for (int i = 1; i <= 5; i++)
	{
		lstScriptInfo.Add(new FileInformation { FileName = "File" + i.ToString() + ".txt" });
	}
	return lstScriptInfo;
}

The code is preety straight forward.We are preparing a list of 5 items and binding the same to the grid

Next write the code in the Cell click event of the DataGridViewControl

void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
	if (e.RowIndex == -1) return;     // for header row        

	if (e.ColumnIndex == 1)
		DownloadFile(lstScriptInfo[e.RowIndex]);   // for the download row        
}

The "DownloadFile()" method is as under

private void DownloadFile(FileInformation fileInformation)
{
	List<string> warnings = WarningsList();
	List<string> remarks = RemarksList();

	string fileName = fileInformation.FileName;
	string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
	FileInfo fileInfo = new FileInfo(fileName);
	string fileExtension = ".xml";
	
	//prepare the xml document
	var xDoc = PrepareTheDocument(fileName, warnings, remarks);
	
	//show save as dialog
	using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
	{
		//Set Save dialog properties
		saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
		saveFileDialog1.Title = "Save File as";
		saveFileDialog1.CheckPathExists = true;
		saveFileDialog1.FileName = fileNameWithoutExtension + fileExtension;

		if (saveFileDialog1.ShowDialog() == DialogResult.OK)
		{
			xDoc.Save(saveFileDialog1.FileName);
			MessageBox.Show("File Saved successfully", "FileSaved");
		}
	} 
}

The code is simple.We are preparing the XML document on the fly and then creating an instance of the save dialog where we are saving the xml file based on the path choosen by user.

The XML file is created as under

private static XDocument PrepareTheDocument(string fileName, List<string> warnings, List<string> remarks)
{
	return
		new XDocument(
		new XElement("scriptfilenames",
			new XElement("SqlEye",
				new XElement("scriptfilename", new XAttribute("fileName", fileName),
					new XElement("warnings",
					warnings.Select(x => new XElement("warning", new XAttribute("value", x)))),
					new XElement("remarks",
					remarks.Select(x => new XElement("remark", new XAttribute("value", x))))
					))));
}

The final output of a downloaded file is as under

Conclusion

Hope this article has given an idea of how to download an XML file from the cell click event of DataGridView.Thanks for reading the article.Zipped file is attached.

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)