I have a two dimensional array with 3 columns and 2 rows. I also have a database table with 3 columns. I want to insert the 2D array directly into the database.
Is there any way to that?
Any help is appreciated. I can supply more details if needed.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace _2DArrayIntoDatabaseTest
{
public partial class Form1 : Form
{
string[,] LoginInfo = new string[2, 3]{{"1", "Admin", "123"},{"2", "Admin2", "456"}};
string query;
SqlCommand Sqlcmd;
SqlConnection conn = new SqlConnection(@"Data Source=MIRAZ-PC\SQLEXPRESS;
Initial Catalog=2DArrayIntoDatabaseTest;
Integrated Security=True");
DataTable dbdataset;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.tTableAdapter.Fill(this._2DArrayIntoDatabaseTestDataSet.t);
}
int i = 0, j = 0;
private void button1_Click(object sender, EventArgs e)
{
try
{
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3;j++ )
query = "INSERT INTO t(SerialNumber,UserName,Password)
values( '" + LoginInfo[i, 0] + "','"
+ LoginInfo[i, 1] + "','"
+ LoginInfo[i, 2] + "')";
}
Sqlcmd = new SqlCommand(query, conn);
conn.Open();
Sqlcmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
try
{
query = "SELECT * from t";
Sqlcmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = Sqlcmd;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
//dataGridView1.Columns.Remove("rownum");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
Now this piece of code compiles fine. But in Data Grid View I can only see 1 row instead of 2.
How to solve that?
Note: Here I am trying to use a nested loop to create a dynamic query to insert a row of data one at a time.