Access the Text Box by the Name

Access the Text Box by the Name

Earlier, text boxes are accessed by index from the Worksheet.TextBoxes collection but now you can also access the text box by name from this collection. This is a convenient and quick way to access your text box if you already know its name.

The following sample code first creates a text box and assigns it some text and name. Then in the next lines, we access the same text box by its name and print its text.

C# code to access the text box by name

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Create an object of the Workbook class
Workbook workbook = new Workbook();
// Access first worksheet from the collection
Worksheet sheet = workbook.Worksheets[0];
// Add the TextBox to the worksheet
int idx = sheet.TextBoxes.Add(10, 10, 10, 10);
// Access newly created TextBox using its index & name it
TextBox tb1 = sheet.TextBoxes[idx];
tb1.Name = "MyTextBox";
// Set text for the TextBox
tb1.Text = "This is MyTextBox";
// Access the same TextBox via its name
TextBox tb2 = sheet.TextBoxes["MyTextBox"];
// Display the text of the TextBox accessed via name
Console.WriteLine(tb2.Text);
Console.WriteLine("Press any key to continue...");
Console.ReadKey();

Console output generated by the sample code

Here is the console output of the above sample code.

This is MyTextBox