Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

C# how to write to DataTable

Posted on 2013-02-05
6
423 Views
Last Modified: 2013-02-10
I have created a DataSet and a DataTable inside my C# application so I can create a report.  I do not have a SQL database or an Access database.  I want to know how to pass the information from a text box and/or list box to the DataTable that is inside my application.
0
Comment
Question by:millerje
6 Comments
 
LVL 15

Expert Comment

by:Minh Võ Công
ID: 38858113
0
 
LVL 16

Assisted Solution

by:Rose Babu
Rose Babu earned 250 total points
ID: 38858780
Have a look on the code below to add data into DataTable.

Controls used in the form

//TextBox txtData
//ListBox lstBoxData

//Button btnAdditToDt
//Button btnAdditToList
//Button btnAddLstDataToGrid

//DataGridView dataGridView1

Add Data into DataTable Form Design
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WinAppCSHARP
{
    public partial class frmEETxtToDt : Form
    {
        public frmEETxtToDt()
        {
            InitializeComponent();
        }

		// Initialise DataTable
        DataTable dt = new DataTable();
        DataRow dr;

        private void frmEETxtToDt_Load(object sender, EventArgs e)
        {
			// Add a temporary column
            dt.Columns.Add("Data");

            BindGrid();
        }

        void BindGrid()
        {
            dataGridView1.Columns.Clear();
            dataGridView1.DataSource = null;

            dataGridView1.DataSource = dt;
        }
		
		// Add TextBox value to DataTable
        private void btnAdditToDt_Click(object sender, EventArgs e)
        {			
            if (txtData.Text.Trim().Length > 0)
            {
                dr = dt.NewRow();
                dr["Data"] = txtData.Text;

                dt.Rows.Add(dr);
            }

            BindGrid();
        }

		// Add TextBox value to ListBox
        private void btnAdditToList_Click(object sender, EventArgs e)
        {
            if (txtData.Text.Trim().Length > 0)
            {
                lstBoxData.Items.Add(txtData.Text.Trim());
            }
        }

		// Populate ListBox value to DataGridView
        private void btnAddLstDataToGrid_Click(object sender, EventArgs e)
        {
            dt.Rows.Clear();

            for (int i = 0; i < lstBoxData.Items.Count - 1; i++)
            {
                dr = dt.NewRow();
                dr["Data"] = lstBoxData.Items[i].ToString();

                dt.Rows.Add(dr);
            }

            BindGrid();
        }
    }
}

Open in new window

Hope this code will help you a lot.
0
 
LVL 4

Expert Comment

by:Srinivasulu Muppala
ID: 38858834
using System;
using System.Data;

class Program
{
    static void Main()
    {
      // Create two DataTable instances.
      DataTable table1 = new DataTable("patients");
      table1.Columns.Add("name");
      table1.Columns.Add("id");
      table1.Rows.Add("sam", 1);
      table1.Rows.Add("mark", 2);

      DataTable table2 = new DataTable("medications");
      table2.Columns.Add("id");
      table2.Columns.Add("medication");
      table2.Rows.Add(1, "atenolol");
      table2.Rows.Add(2, "amoxicillin");

      // Create a DataSet and put both tables in it.
      DataSet set = new DataSet("office");
      set.Tables.Add(table1);
      set.Tables.Add(table2);

      // Visualize DataSet.
      Console.WriteLine(set.GetXml());
    }
}
0
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

 
LVL 4

Expert Comment

by:Srinivasulu Muppala
ID: 38858848
if you want to store data whatever added in data table(s) use this code

//it will write xml file
set.WriteXml("filename.xml");

//it will read xml file
ds.ReadXml("filename.xml");

rebind the dataset once you read xml file, so you can load saved data.
0
 
LVL 1

Author Comment

by:millerje
ID: 38860043
I think all the above information is good.  I want to make sure my original question was clear though.  In my project I have added a new item and selected "dataset" and named it DataSet_SysInfo.xsd.  In the dataset design view I created a "DataTable" and named it AssetInfo and added columns to it.  I have then designed my report.rdlc to point to that datatable.  So on my report form, in the report viewer I pointed it to report.rdlc. So how to I add information to the datatable I have alread created in design view?
0
 
LVL 9

Accepted Solution

by:
rg20 earned 250 total points
ID: 38873593
If it gets stored in the datatable properly, then you could use
DataTable dt = results.tables[0];
then cycle through the rows

something like
DataTable table = GetTable(); // Get the data table.
      foreach (DataRow row in table.Rows) // Loop over the rows.
      {
          Console.WriteLine("--- Row ---"); // Print separator.
          foreach (var item in row.ItemArray) // Loop over the items.
          {
            Console.Write("Item: "); // Print label.
            Console.WriteLine(item); // Invokes ToString abstract method.
          }
      }
0

Featured Post

The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Getting error in connectionstring with Excel. 30 45
Object Oriented Programming, C#, referencing, scoping. 13 69
collection output issue 9 36
how to just get time from a date 6 31
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
The viewer will learn how to implement Singleton Design Pattern in Java.
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

792 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question