C# Use specific element of DataTable drom Data source in Visual Studio

Viewed 35

I added a SQL Table to Data Source in Visual Studio and i want to use the information in this table. I dont understand how to get a specific element from this table, how to call this DataTable in code and get an info from a cell.

1 Answers

Suppose your project is an asp.netframework project. A small case by querying a field of data can help you.

UI page:

enter image description here

Code logic:

Display the name field of the query database through the textbox control.

Query database code:

public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
         Sub_15and10_5returned();
    }

    private void Sub_15and10_5returned()
    {
        Dao dao = new Dao();

        List<string> uni = new List<string>();

        string sql = $"select *  from t_book where author='lmdqdl' ";
        SqlDataReader dr = dao.read(sql);


        DataTable dt = new DataTable();
        dt.Load(dr);  // load data table dataReader .var list = dt.AsEnumerable().Select(c => c.Field<string>("restname")).ToList();
        var list = dt.AsEnumerable().Select(c => c.Field<string>("name")).ToList();

        uni = list;

        textBox1.Text = uni[0];

        textBox2.Text = uni[1];

      
    }

Encapsulates operating database code:

  internal class Dao
  {
    SqlConnection conn;
    public SqlConnection connection()
    {
       // write database connection string
        string connStr = "Data source=localhost;Initial Catalog=student;User ID=sa;Password=123456";
        conn = new SqlConnection(connStr);
        conn.Open();
        return conn;
    }

    public SqlCommand command(string sql)
    {
        SqlCommand cmd = new SqlCommand(sql, connection());
        return cmd;
    }

    public int Execute(string sql)
    {
        return command(sql).ExecuteNonQuery();
    }

    public SqlDataReader read(string sql)
    {
        return command(sql).ExecuteReader();
    }
    public void DaoClose()
    {
        conn.Close();
    }
}

Startup project:

enter image description here

Hope it helps you.

Related