.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

how to add datacolumn dynamically in a datatable..??

Posted By:      Posted Date: May 22, 2011    Points: 0   Category :ASP.Net


i have a query that is in foreach loop,it fetch values from table.different column value is getting from each iteration of loop.so i want to add this column values to column's of one datatable ..so i have to create different column dynamically in one datatable..Each time the number of column is varying as per user wish.ie,if user select two cases,need two columns generation,,if it is three cases,three columns and so on...

My Query part is

 string[] strngSep1 = str.Split(';');         

      foreach (string strng in strngSep1)       


  SqlDataAdapter adap = new SqlDataAdapter("Select Fecha, Valor from datos where" + strng + "and NumEstacion = @StationID and Fecha between @start_DateTime and @end_DateTime", con2);        

  adap.SelectCommand.Parameters.Add("@start_DateTime", start_query_date);                        adap.SelectCommand.Parameters.Add("@end_DateTime", end_query_date);       

  adap.SelectCommand.Parameters.Add("@StationID", station_var);       

View Complete Post

More Related Resource Links

Dynamically Create Controls in ASP.NET by Using Visual C# .NET

This article demonstrates how to dynamically create a control for an .aspx page. The sample project does the following:
Creates two TextBox controls.
Verifies that the contents (TextBox.text) and the attributes of the TextBox are saved across posts to the server.
Illustrates handling events that are posted by a dynamically-created control

Dynamically Create Controls in ASP.NET with Visual Basic .NET

This step-by-step article describes how to dynamically create controls for an ASPX Web page.

The sample project does the following:
It creates two TextBox controls.
It verifies that the TextBox contents (TextBox.text) and attributes are saved across posts to the server.
It describes how events that are posted by a dynamically created control are handled.

How to bind GridView and DropDownList controls using DataTable object

In .net framework 2.0, you can load a DataTable in memory by consuming a data source using a DataReader. In this version you will find the flexibility in accessing the DataReader means write access code once and use again and again using DataReader. To see the functionality of DataTable consider an example that is created using VS2005.

DataTable - Load from IDataReader - CreateDataReader - ReadXml WriteXml - Free ADO.NET Tutorials

The DataTable in ADO.NET 2.0 has been seriously beefed up and I absolutely love it. Not everything we consume deals with multiple resultsets and requires the ever popular DataSet. With the cool new features in the ADO.NET 2.0 DataTable, we can get many of the cool features in the DataSet without all the extra baggage and memory footprint particular to multiple resultsets.

Load DataTable from IDataReader

dynamically adding sql server columns based on number of files in fileuploader


I want to create a new table to sql database at runtime.  The column names would be "Name", "Date", "Event".  I would also like to have one more column name "Image" but the problem is that since the amount of images will vary, I want the application to count the amount of files in the Multiple fileuploader and then add a image column to the table for the respected amount of files. 

For example if i am uploading 3 files in the multiple fileuploader, the names should be "Name", "Date", "Event", "Image1", "image2", Image3"

I also would like that table name to be name dynamically from the textbox Name when the user enters the information.


I have the following code to make a new table, but I dont know how to name the fields at runtime like previously asked please help!!!


Dim objConn As New SqlConnection("Server=<servername>;uid=<userid>;pwd=<password>;database=master")


Datatable in session


I am creating a simple shopping cart using a datatable that is passed into a session object.  I have a small mini cart that displays the total number of items in the cart as well as the running total - this is displayed in a web control.  When the web control starts up I run a try/catch to see if the session object exists, if it doesn't I create the datatable for the cart and store it in the session.  I then have a datalist control that contains all the information for my products including an "add to cart" button.  When the page loads everything looks fine.  If I click on an "add to cart" button nothing happens to the session information.  If I click on it again, the session information updates - displaying only one item is in the cart and then counts up correctly there after.  Additionally, after adding an item, if I select a different item in the list, the same issue occurs.  I am not sure why this is happeing, if anyone can give me an idea I would appreciate it. 

holding datatable value using session



iam insert record using datable in gridivew,iam using  session to hold the record,

there is any other way to hold the record in datable.


        DataRow row;
        row = dtempty.NewRow();
        row["ratetypeid"] = ddlratetype.SelectedValue;
        row["ratedesc"] = ddlratetype.SelectedItem.Text;
        row["slabs"] = ddlslabs.SelectedValue;   

removing item from datatable


hi to all ..thanks in advance


I have Two datatables dtA,dtB ,both contains column name is "FiledName" I need to remove item

from dtA when same row data exists in dtB.  please tell me how to do it

dtA    dtB   

 A        A

 B        F

 C        C

 D        Z

I want o/p like this







using the linqDataSource control programmatically (dynamically)



my scenario is this: I want to use the linqDataSource control to bind data to a gridview for it's efficient built-in paging and sorting features *but* I don't want the data to be bound until the user has input various search parameters, so I need to bind the data from a button click event. Also, the search options will be somewhat complex in that there will be several optional search parameters, via various dropdowns and textboxes, so I can't just declaratively/statically setup all the WHERE parameters on the linqDataSource (at least I'm assuming I can't, or that it may result in poor performance if I do and just assign default values like the everything wildcard '%' for the cases the user doesn't use a particular search parameter). Given that brief description, here is an example of what I'm doing, but with only one WHERE parameter for simplicity, the real code will be adding anywhere from 1 to about 12 WHERE parameters depending on how the user sets the search options in the GUI.

the linqDataSource on the aspx page:

<asp:LinqDataSource ID="ldsMain" runat="server" 
        Select="new (field1, field2, field3, etc..)" 

Bulk Copy From Datatable To SQL Server Table


 I have read the data of a excle file and captured the data into the dataset to a datatable, now that data is to be inserted into a SQL Server table using bulk copy option. I am using -

 public bool BulkEnterData(DataTable dt, string tblName)
        SqlBulkCopy bulk = new SqlBulkCopy(con);
        bulk.DestinationTableName = tblName;

        return true;

ERROR Getting-
A transport-level error has occurred when receiving results from the server. (provider: Shared Memory Provider, error: 0 - The pipe has been ended.) 

How to resolve the above problem or any other solution is available.


Search for a string in my datasource dynamically


I am displaying an Rssfeed on my page by using XmlDataSource and Datalist controls.

I want the user to be able to limit the information that is returned to my datalist.  To do this I have a textbox on the form that allows the user to enter their search criteria.

I need to be able to dynamically create a query string utilizing the information that the user entered in the textbox.  I am also using a drop down list and allowing the user to select whether they want to search in the title, description, or all parts of the xml file.

I am having trouble figuring out how to reference the data contained in my textbox in my query string.  Where the query string says 'asp', I want to replace 'asp' with the content from my sSearch variable.  Can anyone tell me how to reference my variable in the query string???

string sSearch = txtSearch.Text;
        string SQuery = "";

        if (DropDownList2.SelectedIndex == 0)
            SQuery = "[contains(title), 'asp')]";

While Importing Excel 2007 file to Datatable - headerrow problem


Hi there,


I am trying to simply extract an excel data from an uploaded file an put it into a datatable. In this case the excel file has 3 rows but when I fill the datatable I only see row count of 2.

I tried changing HDR:NO; to HDR:YES and vice versa, but no luck. 

What am I doing wrong? (Note: the excel file cannot have a  headerrow)


string connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pFilePath + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR:NO;\"";
            OleDbConnection conn = new OleDbConnection(connstr);
            DataTable dtTables = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
            string strTablename = dtTables.Rows[0]["TABLE_NAME"].ToString();
            string strSQL = "SELECT * FROM [" + strTablename + "]";

            OleDbCommand cmd = new OleDbCommand(strSQL, conn);

            DataTable dt = new DataTable();
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            //At this point row count=2 which doesn't make sense




Persist data in a dynamically populated ListBox in a user control


Hi All,

I am trying to persist data in a dynamically populated ListBox in a user control. Here are the details

I have a user control which contains a a listBox and button. On Page_Load of user control I am populating the ListBox control with some values. On Click of button, I am trying to fetch the values which I have selected in ListBox. Though this seems very simple and straight forward I am unable to fetch values.

My Page_Load Function

void Page_Load(object sender, EventArgs e)










My Click Function

Protected Void Button1_Click(object sender, EventArgs e)


       string strValue = listBox.SelectedValue



I have placed brake point at Page_Load and on click function, I am seeing that the moment the breakpoin

Problem in accessing resource file dynamically.


Steps I have followed are
1.I have created myres.en-GB.resx file at C:.
2.then created locale specific myres.en-GB.resources using resgen at c: only,
resgen c:\myres.en-GB.resx
3.Linked the Resource File to Assembly using AL.exe which is giving me assembly at c: only.
Al /t:lib /embed:myres.en-GB.resources /out:ClassLibrary1.dll
4.I have created one web application using vs 2008 & then build it.
5.Then placed both resource file & dll in web applications Bin\en-GB folder.
6.Anf finally written code at page load like
 CultureInfo info = new CultureInfo("en-GB");
            Thread.CurrentThread.CurrentCulture = info;
            Assembly asd = Assembly.Load("ClassLibrary1");
            ResourceManager res = new ResourceManager("myres.en-GB", asd.GetSatelliteAssembly(info));
            string sdf = res.GetString("Lab1");

but after running application I m getting following error
MissingManifestResourceException", "Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "Cla

Charset Problem with dynamically generated Word Document


in my asp.net web application i am dynamically generating a word documnet out of a sql data. I have set the char set UTF-8 during the doument creation in code but still when i open the generated document and check it char set .. it is always windows-1252 not the one that i have set. My sql data in the document have special characters whihc can only be understandable using the UTF-8 charset otherwise its always ?T written in place of an apostrophy . Pasting my code here..

         HttpContext.Current.Response.ContentType = "application/msword";
         HttpContext.Current.Response.ContentEncoding = System.Text.UnicodeEncoding.UTF8;
         HttpContext.Current.Response.Charset = "utf-8";
         string strFileName = "Details" + ".doc";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
        StringBuilder strHTMLContent = new StringBuilder();
        string strMessage = " ";
        DataView abstractview = (DataView)dsAbstract.Select(DataSourceSelectArguments.Empty);
        foreach (DataRowView row1 in abstractview)
            strMessage += "<table border='1' cellspacing='0' cellpadding='5' width

dynamically change column names in Crystal reports


I need to develop 3 pages.

On the first page user defines atmost 7 column names to be displayed on the report. I'm saving these names in a Sql DB table 'Columns' with Column_Nm and Column_ID as Table columns.

On the second page I'm retrieving column_Nm from the table and displaying them on the page so that the user enters the data. This data is saved in another table 'Summary' with the Columns column1 through column7.

on the 3rd page I need to show a report of 'Summary' table.

How do I dynamically replace column1 through column7 names with that of 'Column_Nm' on the report?

Any help/suggestions would be appreciated.


Conversion of List to DataTable and ViceVersa


hi ,

           Iam having a requirement where I wil get datatable or Dataview from the DataAccessLayer I need to convert them into GanaricList of entites and ViceVersa from GenericList to Datatable or DataView.

             I tried it but I cant. Can anybody help me out.

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend