user2179026
user2179026

Reputation:

How to populate gridview by comma splitted string?

I have created Gridview like below lines of code.

<asp:GridView ID="grdView" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="chkbox" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Jurisdiction">
            <ItemTemplate>
                <asp:Label ID="lblJurisdiction" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="License Number">
            <ItemTemplate>
                <asp:TextBox ID="txtLicenseNumber" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

I have created a method in c# like below

private void FillJurisdictionGrid(string Jurisdiction)
{ 
    Jurisdiction = "Alaska, New York, Alabama";
    /* */ 
}

Now I want that gridview should be populated by string Jurisdiction. The above grid should appear as

Please help me !!!

Upvotes: 2

Views: 1317

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 21825

You can use Split function to split your data based on , delimiter. I hope Jurisdiction is coming as parameter in your method and in question you are showing it just for example purpose;

private void FillJurisdictionGrid(string Jurisdiction)
{ 
    Jurisdiction = "Alaska, New York, Alabama";
    string[] jurisdictionData = Jurisdiction.Split(',');
    grdView.DataSource = jurisdictionData;
    grdView.DataBind();
}

Finally simply add the Text attribute in your label:-

<asp:Label ID="lblJurisdiction" runat="server" Text='<%# Container.DataItem %>' />

Also, set the AutoGenerateColumns property in gridview to turn off the auto generation of columns:-

<asp:GridView ID="grdView" runat="server" AutoGenerateColumns="false">

Upvotes: 1

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14624

Try this

Jurisdiction = "Alaska, New York, Alabama";
string[] names = Jurisdiction.Split(',');
grdView.DataSource = names;
grdView.DataBind();

Upvotes: 0

Related Questions