I have a problem with messagebox.
Form1:
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var dialog = new OpenFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
Class1 excel = new Class1(dialog.FileName, 1);
string path = dialog.FileName + ".txt";
TextWriter tw = new StreamWriter(path, true);
tw.Write(excel.ReadCell(0, 0));
tw.Close();
}
}
}
}
Class1:
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
class Class1
{
string path = "";
_Application excel = new _Excel.Application();
Workbook wb;
Worksheet ws;
private object excelWorksheet;
public Class1(string path, int Sheet)
{
this.path = path;
wb = excel.Workbooks.Open(path);
ws = (Worksheet)wb.Worksheets[Sheet];
}
public string ReadCell(int row, int column)
{
column += 1;
do
{
row++;
if(((_Excel.Range)ws.Cells[row, column]).Value2 == null)
break;
_Excel.Range range = (_Excel.Range)ws.Cells[row, column];
if (range.Value.ToString() == "Z_KomSilnice_L (24200)/7")
{
range = (_Excel.Range)ws.Cells[row, column + 1];
return range.Value.ToString();
}
else
{
MessageBox.Show("Hodnota nenalezena!");
}
} while (true);
return "";
}
}
}
When I write the code like this, the messagebox always appears.
But I would need him to show up only if the value is not in the excel file.
if (range.Value.ToString() == "Z_KomSilnice_L (24200)/7")
{
range = (_Excel.Range)ws.Cells[row, column + 1];
return range.Value.ToString();
}
else
{
MessageBox.Show("Hodnota nenalezena!");
}
The problem is this checks the first cell, finds that the value is not found and writes a messagebox.
So I know where the problem is and why the problem is, but I don't know how to combine it to make it work.
Thank you all for the advice.
If I understand correctly;
You're returning if you find the value already, so instead of giving same message when every column is read in the "else" section.
It will be correct to give a message when you cannot find all the data except do{}while(true).
Like this;
public string ReadCell(int row, int column)
{
column += 1;
do
{
row++;
if(((_Excel.Range)ws.Cells[row, column]).Value2 == null)
break;
_Excel.Range range = (_Excel.Range)ws.Cells[row, column];
if (range.Value.ToString() == "Z_KomSilnice_L (24200)/7")
{
range = (_Excel.Range)ws.Cells[row, column + 1];
return range.Value.ToString();
}
} while (true);
MessageBox.Show("Hodnota nenalezena!");
return "";
}
Related
I am currently making a fitness class booking system for some study I am doing so please bare with me.
I have done most of the code but I am having this strange issue with my 2nd radio button for selecting what class you want.
I have set up my code so a message box appears if the Member ID you have entered is already registered to the fitness class you have selected. For my RadioButton1 (rbCardioClass) and RadioButton2 (rbPilatesClass), the error message box works great and works as it should. But my RadioButton2 (rbSpinClass) will make the error message box appear everytime, even if the MemberID is not associated to the 'Spin Class'.
I have tried different uses of if statements, different radio buttons etc but can't seem to get it to work the way I want.
If I go to my servicesErrorCheck(string[] description)method and just the temp variable to true all radio buttons save to the database table correctly BUT I then lose my erroring, which makes me thinks it is something to do with the way I have set up the message box, maybe.
Here is a screenshot of the prototype form just for reference. FitnessClassBooking Form
Here is a screenshot of the table while the app is running App Running Fitness Form
Here is the error being thrown with MemberID that has no 'Spin' class associated with it App Running Error
Here is my code in question -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace Membership_Formv2
{
public partial class FitnessClassBooking : Form
{
public FitnessClassBooking()
{
InitializeComponent();
}
private void bMainMenu_Click(object sender, EventArgs e)
{
new MainMenu().Show();
this.Hide();
}
private void fitnessInformationBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.fitnessInformationBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.databaseDataSet);
}
private void FitnessClassBooking_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'databaseDataSet.Members' table. You can move, or remove it, as needed.
this.membersTableAdapter.Fill(this.databaseDataSet.Members);
// TODO: This line of code loads data into the 'databaseDataSet.FitnessInformation' table. You can move, or remove it, as needed.
this.fitnessInformationTableAdapter.Fill(this.databaseDataSet.FitnessInformation);
}
private void fitnessInformationDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private string descriptionfit()
{
string className = "";
if (rbCardioClass.Checked == true)
{
className = "Cardio";
}
else if (rbSpinClass.Checked == true)
{
className = "Spin";
}
else if (rbPilatesClass.Checked == true)
{
className = "Pilates";
}
return className;
}
private string classDescription()
{
string serviceSeletionString = "Class";
if (rbCardioClass.Checked == true)
{
serviceSeletionString = rbCardioClass.Text;
this.Refresh();
}
else if (rbSpinClass.Checked == true)
{
serviceSeletionString = rbSpinClass.Text;
this.Refresh();
}
else if (rbPilatesClass.Checked == true)
{
serviceSeletionString = rbPilatesClass.Text;
this.Refresh();
}
return serviceSeletionString;
}
private bool errorCheckingID()
{
bool statusDB = true;
//Getting row info from MembersTa table
DatabaseDataSet.MembersRow newEntry = databaseDataSet.Members.FindByMemberID(Int32.Parse(textBox3.Text));
//Getting information from BookingTa table
if (newEntry == null)
{
statusDB = false;
return (statusDB);
}
return (statusDB);
}
public bool servicesErrorCheck(string[] description)
{
bool temp = true;
string serviceSeletionString = "";
if (rbCardioClass.Checked == true)
{
serviceSeletionString = rbCardioClass.Text;
this.Refresh();
}
else if (rbSpinClass.Checked == true)
{
serviceSeletionString = rbSpinClass.Text;
this.Refresh();
}
else if (rbPilatesClass.Checked == true)
{
serviceSeletionString = rbPilatesClass.Text;
this.Refresh();
}
for (int t = 0; t < description.Length; t++)
{
if (serviceSeletionString.Contains(description[t].Trim()))
{
temp = false;
break;
}
}
return (temp);
}
private string originalaccesdb()
{
string a = "";
DatabaseDataSet.FitnessInformationRow newRow = databaseDataSet.FitnessInformation.NewFitnessInformationRow();
newRow.Fitness_Booking_ID = databaseDataSet.FitnessInformation.Count + 1;
newRow.Description = descriptionfit();
newRow.MemberID = Int32.Parse(textBox3.Text);
databaseDataSet.FitnessInformation.AddFitnessInformationRow(newRow);
return a;
}
private string[] accessDB()
{
int t = 0;
int temp;
string[] servicesList = { "n", "n", "n" }; //This variable will store the data
//Same code too extract table information
foreach (DataRow r in databaseDataSet.FitnessInformation.Rows)
{
temp = Int32.Parse(r["MemberID"].ToString());
if (temp == Int32.Parse(textBox3.Text))
{
//Store inside the array all the services/description against the ID.
//Note that this array will remain "" for all the elements inside the array
//if no descritopn/services (i.e., record) is found against the input ID
servicesList[t] = r["Description"].ToString();
t = t + 1;
}
}
return (servicesList);
}
private void button1_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
textBox1.Text = "";
int a = Int32.Parse(textBox2.Text);
DatabaseDataSet.MembersRow newID = databaseDataSet.Members.FindByMemberID(Int32.Parse(textBox2.Text));
string booking = "";
int temp;
foreach (DataRow r in databaseDataSet.FitnessInformation.Rows)
{
temp = Int32.Parse(r["MemberID"].ToString());
if (temp == Int32.Parse(textBox2.Text))
{
booking = r["Description"].ToString() + ", " + booking;
}
}
textBox1.Text = "Member ID is: " + (newID.MemberID).ToString() + Environment.NewLine +
"First Name is: " + (newID.First_Name).ToString() + Environment.NewLine +
"Last Name is: " + (newID.Last_Name).ToString() + Environment.NewLine +
"Bookings: " + booking;
}
public void button2_Click(object sender, EventArgs e)
{
bool status1, status2;
string[] description;
//Error control at the outer level for valid ID
status1 = errorCheckingID();
//Proceed only if ID is valid or status1 is true
if (status1)
{
//Retrieve information from the other database. Ideally you want this method to return
//an array containing registered services. This would be an array of strings.
description = accessDB();
//Services error checking
status2 = servicesErrorCheck(description);
//Now this is the code that would call the method to save data ito database
//when status2 and 2 are true
if (status2)
{
//Code for saving into database.
DatabaseDataSet.FitnessInformationRow newRow = databaseDataSet.FitnessInformation.NewFitnessInformationRow();
newRow.Fitness_Booking_ID = databaseDataSet.FitnessInformation.Count + 1;
newRow.Description = classDescription();
newRow.MemberID = Int32.Parse(textBox3.Text);
databaseDataSet.FitnessInformation.AddFitnessInformationRow(newRow);
}
else
{
//Show error that this service is not available
MessageBox.Show("This Class is already assigned to that Member ID");
}
}
else
{
//Error message invalid ID
MessageBox.Show("Invalid ID");
}
}
private void radioButton1_Click(object sender, EventArgs e)
{
}
private void radioButton4_Click(object sender, EventArgs e)
{
}
private void radioButton3_Click(object sender, EventArgs e)
{
}
}
}
I am really not sure why this is happening so I would really appreciate any help.
You are checking each string in descriptions as follows:
serviceSeletionString.Contains(description[t].Trim())
which considering at least one of the strings is just n it will always match Spin.
Quite why you are always returning an array with the blank ones having n, I don't know. Personally I would just use a List<string> and Add each item from the database to it. But that is a separate point.
Either change it to serviceSeletionString == description[t] (don't see why you need Trim()) or just replace the whole foreach loop with description.Contains(serviceSeletionString)
I want to write a program that save all the data from a .csv into a database.
I use a service-based database.
But when I want to use the addtoTablesName like what I used to do and I learned at university, it suddenly throws an error.
This is my code:
class Program
{
static void Main(string[] args)
{
Database1Entities1 dbb = new Database1Entities1();//object database
excel.Application xlApp;
excel.Workbook xlWb;
excel._Worksheet xlWs;
excel.Range xlRange;
excel.Application xlApp1;
excel.Workbook xlWb1;
excel._Worksheet xlWs1;
excel.Range xlRange1;
int rowFile = 0;
int colFile = 0;
string[][] dataFile;
DateTime date = DateTime.Now;
string tgl = date.Date.ToString("dd");
string bln = date.Month.ToString("d2");
string thn = date.Year.ToString();
string tglskrg = thn+bln+tgl;
string[] items;
DateTime otime2 = DateTime.ParseExact(tglskrg, "yyyyMMdd", null);
xlApp = new excel.Application();
string[] filesindirectory = Directory.GetDirectories(#"C:\Users\u532246\Desktop\TRAVELOKA");
foreach (string files in filesindirectory)
{
string name = Path.GetFileName(files);
string subname = name.Substring(10, 8);
DateTime subTime = DateTime.ParseExact(subname, "yyyyMMdd", null);
TimeSpan span = otime2.Subtract(subTime);
if(span.Days < 2)
{
// Console.WriteLine(files);
foreach(string subfiles in Directory.GetFiles(files))
{
xlWb = xlApp.Workbooks.Open(subfiles);
xlWs = xlWb.Sheets[1];
xlRange = xlWs.UsedRange;
rowFile = xlRange.Rows.Count;
colFile = xlRange.Columns.Count;
dataFile = new string[rowFile][];
for(int i = 0; i < dataFile.Length; i++)
{
dataFile[i] = new string[colFile];
}
for(int i = 0; i<rowFile;i++)
{
for(int j = 0; i<colFile;j++)
{
try
{
dataFile[i][j] = xlWs.Cells[i + 1, j + 1].value2.ToString();
//MessageBox.Show(dataMapping[i][j]);
}
catch (Exception ee)
{
dataFile[i][j] = "";
}
}
}
CMRTable cmr = new CMRTable();
for(int i = 0; i < rowFile; i++)
{
items = dataFile[i][0].Split(';');
cmr.Id = i + 1;
cmr.Merchant_Name = items[1];
cmr.Sett_Date = items[2];
cmr.Proc_Date = items[3];
cmr.Mid = items[4];
cmr.CardType = items[5];
cmr.Trx_Date = items[6];
cmr.Jam_Trx = items[7];
cmr.Auth = items[8];
cmr.CardNo = items[9];
cmr.Trx_Type = items[10];
cmr.Amount = items[11];
cmr.Rate = items[12];
cmr.Disc_Amt = items[13];
cmr.Tenor_Ins = items[14];
cmr.Rate_Ins = items[15];
cmr.Disc_Ins = items[16];
cmr.Net_Amt = items[17];
cmr.Purchase_Id = items[18];
cmr.Mechant_Descriptor = items[19];
dbb.AddToCMRTables(cmr); #I CANT USE THIS FUNCTION , DONT KNOW WHY
dbb.SaveChanges();
}
Console.WriteLine(subfiles);
}
}
}
}
}
Can someone help me? I think I already do everything exactly like I did in university ..
EDIT: here's the error I get:
Database1Entities1 does not contain a definition for AddToCMRTables and no accessible extension method AddToCMRTables accepting a first argument of type Database1Entities1 could be found
I copy what i used to do in university (here's the code)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{//dipakai ketika ingin menginsert data ke database.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
displayData();
}
Database1Entities db = new Database1Entities();//object database
private void displayData()
{
var query = from x
in db.MsStudents
select x;
dataGridView1.DataSource = query;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
txtID.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString();
txtName.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString();
}//buat ngeklik yg ada di data grid view
private void txtSearch_TextChanged(object sender, EventArgs e)
{
search(txtSearch.Text);
}
public void search(string kata) {
var query = from x
in db.MsStudents
where x.Name.Contains(kata)//apa yang muncul di kotak search itu di select
select x;
dataGridView1.DataSource = query;
}//function buat search
private void btnInsert_Click(object sender, EventArgs e)
{
MsStudent student = new MsStudent();
student.ID = Int32.Parse(txtID.Text);
student.Name = txtName.Text;
db.AddToMsStudents(student);
db.SaveChanges();
displayData();
}
private void btnReset_Click(object sender, EventArgs e)
{
foreach (Control a in this.Controls)
{
if (a.GetType() == typeof(TextBox))
{
a.Text = "";
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Okay so yes I am doing homework and I am SO close on this one I know it, but ive been messing with it for over an hour and now I'm going insane, if i take the loop out my program will read the file and say weather you passed but it wont write the wrong answers in the listbox, if i put in my foreach code it gives me a syntax error.
this is my current code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace DriversLicenseExam
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] answerArray ={"B","D","A","A","C",
"A", "B","A","C","D",
"B", "C","D","A","D",
"C", "C","B","D","A"};
string[] studentansArray = new string[20];
List<string> incorrectList = new List<string>();
int count = 0, index = 0, qnumber = 0;
try
{
string filename = "../../" + filenametxt.Text;
StreamReader inputFile = File.OpenText(filename);
while(!inputFile.EndOfStream)
{
studentansArray[index] = inputFile.ReadLine();
if (studentansArray[index] == answerArray[index])
count++;
else
{
qnumber = index + 1;
incorrectList.Add(qnumber.ToString());
}
index++;
}
inputFile.Close();
if (count >= 15)
{
resultoutput.Text = "You Passed The Test!";
}
else
resultoutput.Text = "You Failed The Test... You're a Failure!";
}
foreach (string str in incorrectList) // <<-- error is here
{
lbox.Items.Add(str);
} // <<-- error is here
catch (Exception)
{
MessageBox.Show("File Not Found");
}
}
private void button2_Click(object sender, EventArgs e)
{
filenametxt.Text = "";
resultoutput.Text = "";
lbox.Items.Clear();
}
private void exitbutton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I'm not 100% sure about this, but your foreach is between your try and catch block, maybe try with that:
try
{
string filename = "../../" + filenametxt.Text;
StreamReader inputFile = File.OpenText(filename);
while(!inputFile.EndOfStream)
{
studentansArray[index] = inputFile.ReadLine();
if (studentansArray[index] == answerArray[index])
count++;
else
{
qnumber = index + 1;
incorrectList.Add(qnumber.ToString());
}
index++;
}
inputFile.Close();
if (count >= 15)
{
resultoutput.Text = "You Passed The Test!";
}
else
resultoutput.Text = "You Failed The Test... You're a Failure!";
foreach (string str in incorrectList)
{
lbox.Items.Add(str);
}
}
catch (Exception)
{
MessageBox.Show("File Not Found");
}
This is my xml file;
<UserClass>
<Id>1</Id>
<Name>oss</Name>
<Address>
<Id>1</Id>
<Street>asstreet</Street>
</Address>
</UserClass>
So I want to add these "nodes" to comboBox items.
When user typed UserClass and type "."(dot) to end of "UserClass"; Id, Name and other things have to listed in combobox.
User typed "UserClass." and -> combobox get these;
UserClass.Id
UserClass.Name
UserClass.Address.Id
UserClass.Address.Street
I tried many things, include that one;
...
try
{
string parsedNode = ParseComboBox();
XmlReader rdr = XmlReader.Create(new System.IO.StringReader(_globalXml));
comboBox1.Items.Clear();
while (rdr.Read())
{
if (rdr.NodeType == XmlNodeType.Element)
{
comboBox1.Items.Add(rdr.LocalName);
}
comboBox1.DroppedDown = true;
}
//string parsedNode = ParseComboBox();
//XmlNodeList childList = xml.GetElementsByTagName(parsedNode);
////comboBox1.Items.Clear();
//foreach (XmlNode node in childList)
//{
// foreach (var osman in node.ChildNodes)
// {
// comboBox1.Items.Add(parsedNode + "." + osman);
// }
//}
}
catch (Exception)
{
MessageBox.Show("fuuu");
}
}...
private string ParseComboBox()
{
string resultAsXmlNodes = null;
string text = comboBox1.Text;
if (text.EndsWith("."))
{
char[] delimiterChars = { '.' };
string[] words = text.Split(delimiterChars);
foreach (string s in words)
{
resultAsXmlNodes += s;
}
}
return resultAsXmlNodes;
}
It's not working correctly. I believe there is an easy way to do it.
So, what is the simple way? Or simply,
How can I show node names in comboBox ?
I found multiple problems with this. Here's some example code that I got working for a form project with an XML File and one ComboBox control:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.KeyDown += comboBox1_KeyDown;
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Decimal:
case Keys.OemPeriod:
LoadComboItems(comboBox1.Text);
break;
default:
break;
}
}
void LoadComboItems(string userInput)
{
comboBox1.Items.Clear();
string lookupName = userInput.Trim();
if (lookupName.Length > 0)
{
string _globalXML = Application.StartupPath + #"\XMLFile1.xml";
XmlReader rdr = XmlReader.Create(_globalXML);
while (rdr.Read())
{
if (rdr.LocalName == lookupName)
{
string ElementName = "";
int eCount = 0;
int prevDepth = 0;
while (rdr.Read())
{
if (rdr.NodeType == XmlNodeType.Element)
{
ElementName += '.' + rdr.LocalName;
eCount++;
}
else if (rdr.NodeType == XmlNodeType.EndElement && eCount == rdr.Depth)
{
if (rdr.Depth >= prevDepth)
{
comboBox1.Items.Add(lookupName + ElementName);
int pos = ElementName.LastIndexOf('.');
ElementName = ElementName.Substring(0, pos);
prevDepth = rdr.Depth;
}
eCount--;
}
}
}
}
if (rdr != null)
{
rdr.Close();
}
comboBox1.DroppedDown = true;
}
}
}
}
In my application, there is requirement to export datagridview into Excel.
I am using the following source code. I wanted expert advice on following questions.
Is my code is correct or not? because i am not getting any file saved at the selected path.
Is there any performance issue while exporting data from grid, because there could be as many as data available in grid?
I am using Namespace "Microsoft.Office.Interop.Excel", not sure if that is right?
private void btnSaveResult_Click(object sender, EventArgs e)
{
try
{
if (this.saveFileDialog.ShowDialog() == DialogResult.OK)
{
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File To";
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 30;
for (int i = 0; i < grdResult.Rows.Count; i++)
{
DataGridViewRow row = grdResult.Rows[i];
for (int j = 0; j < row.Cells.Count; j++)
{
ExcelApp.Cells[i + 1, j + 1] = row.Cells[j].ToString();
}
}
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
MessageBox.Show("The Save button was clicked or the Enter key was pressed" + "\nThe file would have been saved as " + this.saveFileDialog.FileName);
}
else MessageBox.Show("The Cancel button was clicked or Esc was pressed");
}
catch (Exception ex)
{
MessageBox.Show("Cancelled Save Operation");
this.Close();
}
}
get handle to workbook whe you add, and call Workbook.SaveCopyAs(filePath);
Try Following class
using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/// <summary>
/// Summary description for GridViewExportUtil
/// </summary>
public class GridViewExportUtil
{
public GridViewExportUtil()
{
//
// TODO: Add constructor logic here
//
}
public static void ExportGridView(string fileName, GridView gv, Label header, Label date)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
gv.AllowPaging = false;
// Create a table to contain the grid
Table table = new Table();
// include the gridline settings
table.GridLines = gv.GridLines;
gv.Style["font-family"] = "Tahoma";
// add the header row to the table
if (gv.HeaderRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
gv.HeaderRow.BackColor = System.Drawing.Color.Lavender;
gv.HeaderRow.ForeColor = System.Drawing.Color.Green;
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
GridViewExportUtil.PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
htw.WriteLine("<br>");
// htw.WriteLine(" ");
if (header.Text != null)
{
header.Font.Size = 15;
header.Font.Bold = true;
header.ForeColor = System.Drawing.Color.Blue;
header.RenderControl(htw);
}
htw.WriteLine("</p>");
// render the table into the htmlwriter
table.RenderControl(htw);
htw.WriteLine("<br>");
htw.WriteLine("Report taken on :", System.Drawing.FontStyle.Bold);
if (date.Text != null)
{
date.ForeColor = System.Drawing.Color.Blue;
date.RenderControl(htw);
}
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
/// <summary>
/// Replace any of the contained controls with literals
/// </summary>
/// <param name="control"></param>
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
else if (current is Label)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as Label).Text));
}
if (current.HasControls())
{
GridViewExportUtil.PrepareControlForExport(current);
}
}
}
}
And use it as below
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Visible = true;
Label2.Visible = true;
Label1.Text = "Login Information Data";
Label2.Text = Convert.ToString(System.DateTime.Now);
if (GridView1.Visible == true)
{
// GridViewExportUtil.Export("StateReport.xls", GridView1);
GridViewExportUtil.ExportGridView("LoginInformation.xls", GridView1, Label1, Label2);
}
}
Remove labels if you do not want them.. make changes as per your need.
Implementation weaknesses:
- you don't free resouces you use;
- you export items one by one (it's extremely slow), there's range designed for that, where you can set object[,] (of boxed int, strings, ...);
- you don't handle formatting of text (Excel's decisions about format are not right),
- you mix view and export logic.