Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Data.DuplicateNameException in DataTable

Tags:

c#

asp.net

I am adding columns dynamically to a static Data table in the !IsPostBack.

static DataTable dtflow = new DataTable();

protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            dtp.Columns.Add("slno");
            dtp.Columns.Add("portname");
            dtp.Columns.Add("type");
            dtp.Columns.Add("portid");
            dtp.Columns.Add("longitude");
            dtp.Columns.Add("latitude");
            dtp.Columns.Add("add1");
            dtp.Columns.Add("add2");
            dtp.Columns.Add("dist");
            dtp.Columns.Add("state");
            dtp.Columns.Add("country");
        }
    }

But when I run my website for second time it shows an Exception like this

Exception Details: System.Data.DuplicateNameException: A column named 'slno' already belongs to this DataTable.

Can anybody tell me how to resolve this problem

like image 636
Arun Anand Avatar asked Mar 16 '13 12:03

Arun Anand


1 Answers

A static datatable means that it will always be there regardless of instances of your webpages. So when you run the webpage for the first time, your Page_Load creates the datatable and everything is good.

But when you load that page a second time or if someone else tries loading your page, the datatable is still there since it's static, so your trying to add columns to your datatable when they already exist.

3 ways you could get around this:
1. Remove and then add the columns again. Don't ever do this, it is redundant and bad code in every aspect.
2. Add an if statement around your dtp.Columns.Adds to ensure it only runs them the first time the page is loaded. You could check to see if the columnds exist, you could create a bool flag, or another means that you think of.
3. Remove static from your variable declaration so that every time the page loads a new datatable is created. If you do this then you probably want to base the datatable off of a static datasource.

like image 72
Gander7 Avatar answered Nov 06 '22 11:11

Gander7