PigsIncorporated PigsIncorporated - 3 months ago 18
ASP.NET (C#) Question

C# Cell LiteralControl Get Text Value

How come this doesn't work for getting the text value of a literalcontrol on export of a gridview to Excel?

cell.Text = (cell.Controls[0] as LiteralControl).Text;


Edit: (Complete Code)

if (cell.HasControls())
{

switch (cell.Controls[0].GetType().Name)
{
case "HyperLink":
cell.Text = (cell.Controls[0] as HyperLink).Text;
cell.Controls.Clear();
cell.ForeColor = System.Drawing.ColorTranslator.FromHtml("#000000");
break;
case "LinkButton":
cell.Text = (cell.Controls[0] as LinkButton).Text;
cell.Controls.Clear();
cell.ForeColor = System.Drawing.ColorTranslator.FromHtml("#000000");
break;
case "LiteralControl":
cell.Text = (cell.Controls[0] as LiteralControl).Text;
cell.Controls.Clear();
cell.ForeColor = System.Drawing.ColorTranslator.FromHtml("#000000");
break;
}

//cell.Text = cell.Controls[0].GetType().Name;


}

Answer

Asp.Net adds LiteralControl by default in gridview template field for spacing or whatever reason, so you are referring that control instead of yours, try using

cell.Controls[1] 

instead of

cell.Controls[0] 

in case of LiteralControl.

Also if possible you can assign ID to controls and use those ID, in that case this problem of referring incorrect element will not surface as you will refer control with its specific ID.