如何在数据表中添加行 [英] how to add row into a datatable

查看:84
本文介绍了如何在数据表中添加行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据集中有一个数据表,我不使用tableadapter,我只想向表中添加行

i have a datatable within a dataset , i''m not using tableadapter i just want to add rows into the table

推荐答案

try
            {
                DataTable dt = new DataTable();

                dt.Columns.Add("ID", typeof(int));
                dt.Columns.Add("Name", typeof(string));

                DataRow dr = dt.NewRow();
                dr["ID"] = 100;
                dr["Name"] = "Bala";
                dt.Rows.Add(dr);


               // dataGridView1.DataSource = dt;    

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);  
            }




更新1

1.希望您的数据集声明如下




UPDATE 1

1. Hope your dataset is declared as follows

public partial class Form1 : Form
{
    DataSet ds = new DataSet();

    public Form1()
    {
        InitializeComponent();
    }



2.希望您的数据绑定如下



2. Hope you data binding is as follows

try
           {

               SqlConnection oconn = new SqlConnection();
               oconn.ConnectionString = "Data Source=Localhost;Initial Catalog=TEST_DB;user=sa;password=123";
               oconn.Open();

               SqlDataAdapter oda = new SqlDataAdapter("Select ID,Name from employees", oconn);
               oda.Fill(ds);
               dataGridView1.DataSource = ds.Tables[0];

           }
           catch (Exception ex)
           {

               MessageBox.Show(ex.Message);
           }




3.您可以向表中添加一个新行,该行附加到数据集,如下所示




3. You can add a new row to the table which is attached to a dataset as follows

private void btnAdd_Click(object sender, EventArgs e)
       {
           try
           {
               DataRow dr = ds.Tables[0].NewRow();
               dr["name"] = "bala";
               ds.Tables[0].Rows.Add(dr);

           }
           catch (Exception ex)
           {


           }
       }


尝试这个

Try for this

DataRow row;
//loop for datatables row
for (int index = 0; index < dt.Rows.Count; ++index)
{
row = dt.Rows[index];
// if u want to add new row u can add here
}


这篇关于如何在数据表中添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆