[Solved] ASP.Net String.Split Error: Index was outside the bounds of the array

Mehram
 
on Jul 09, 2021 11:10 PM
1381 Views

Sir

When I am applying this code showing error

Bold first word from string in GridView BoundField using C# and VB.Net in ASP.Net

There is an error {"Index was outside the bounds of the array."}

e.Row.Cells(0).Text = String.Format("<b>{0}</b><br/>{1}",
e.Row.Cells(0).Text.Split(vbLf)(0).Trim(), e.Row.Cells(0).Text.Split(vbLf)(1).Trim())

If replacing with the following working without bold

e.Row.Cells(3).Text = e.Row.Cells(3).Text.Replace(vbCrLf, "<br/>")

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jul 10, 2021 12:10 AM

Hi Mehram,

The main issue is with the SELECT query.

If one of the column has null value then the query returns NULL.

So you need to use ISNULL function in the query to replace the NULL value with empty.

Example:

SELECT TOP 5 Narration = ISNULL(t.ContactName, '') + CHAR(13) + CHAR(10) + ISNULL(t.Fax, '') FROM Customers t

Then modify the code to check the length of the string after spliting.

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

HTML

<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
    <Columns>
        <asp:BoundField DataField="Narration" HeaderText="Narration">
            <HeaderStyle HorizontalAlign="Left" />
        </asp:BoundField>
    </Columns>
</asp:GridView>

Namespaces

C#

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

VB.Net

Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        string query = "SELECT TOP 5 Narration = ISNULL(t.ContactName, '') + CHAR(13) + CHAR(10) + ISNULL(t.Fax, '') FROM Customers t";
        using (SqlConnection con = new SqlConnection(conString))
        {
            SqlCommand cmd = new SqlCommand(query);
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    gvDetails.DataSource = dt;
                    gvDetails.DataBind();
                }
            }
        }
    }
}

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string[] stringSeparators = new string[] { "\r\n" };
        string[] texts = e.Row.Cells[0].Text.Split(stringSeparators, StringSplitOptions.None);
        if (texts.Length > 1)
        {
            e.Row.Cells[0].Text = string.Format("<b>{0}</b><br/>{1}", texts[0].Trim(), texts[1].Trim());
        }
        else
        {
            e.Row.Cells[0].Text = string.Format("<b>{0}</b>", texts[0].Trim());
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim query As String = "SELECT TOP 5 Narration = ISNULL(t.ContactName, '') + CHAR(13) + CHAR(10) + ISNULL(t.Fax, '') FROM Customers t"
        Using con As SqlConnection = New SqlConnection(conString)
            Dim cmd As SqlCommand = New SqlCommand(query)
            Using sda As SqlDataAdapter = New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As DataTable = New DataTable()
                    sda.Fill(dt)
                    gvDetails.DataSource = dt
                    gvDetails.DataBind()
                End Using
            End Using
        End Using
    End If
End Sub

Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim stringSeparators As String() = New String() {vbCrLf}
        Dim texts As String() = e.Row.Cells(0).Text.Split(stringSeparators, StringSplitOptions.None)
        If texts.Length > 1 Then
            e.Row.Cells(0).Text = String.Format("<b>{0}</b><br/>{1}", texts(0).Trim(), texts(1).Trim())
        Else
            e.Row.Cells(0).Text = String.Format("<b>{0}</b>", texts(0).Trim())
        End If
    End If
End Sub

Screenshot