-2

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;


                }
8
  • I ran the export and added what type of control is in the cells. Hyperlinks work and I'm able to get the text and strip out the control. Cells with LiteralControls can't read the controls text. Commented Aug 23, 2016 at 14:26
  • add more appropriate tags. seems like asp.net question
    – Versatile
    Commented Aug 23, 2016 at 14:28
  • What is happening are you getting literal control as null or Text property is an empty string? Are you sure cell.Controls[0] is literal control? Have you checked it by inspecting its type? Commented Aug 23, 2016 at 14:37
  • It's an empty string. It knows it's a LiteralControl but the text doesn't get read. Commented Aug 23, 2016 at 14:39
  • Edited and add complete code. The hyperlinks and LinkButton text gets read. Commented Aug 23, 2016 at 14:41

2 Answers 2

2

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.

1
  • This worked: case "LiteralControl": cell.Text = (cell.Controls[1] as HyperLink).Text; cell.Controls.Clear(); break; Commented Aug 23, 2016 at 15:35
0

((System.Web.UI.WebControls.Literal)agentGrid.Rows[0].Cells[0].Controls[1]).Text

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.