Showing data in a form in .NET with Postgres - c#

I tried to use this code to show data from a database in a form but I got an error in the DataAdapter.Fill, I tried to delete it but nothing appears when I execute the program, I don't know what else can I do. Here you have the code and the screenshot of the error:
https://i.stack.imgur.com/faQ32.png
public partial class ShowData : Form
{
public ShowData()
{
InitializeComponent();
NpgsqlConnection conn = new NpgsqlConnection();
conn.ConnectionString = "Server=localhost;Port=5432;Database=firstdatabase;User Id=postgres";
conn.Open();
string sql = "SELECT * FROM first_schema.customers";
NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
NpgsqlDataReader dr = cmd.ExecuteReader();
NpgsqlDataAdapter ad = new NpgsqlDataAdapter(cmd);
DataTable dt = new DataTable();
DataSet ds = new DataSet();
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
Console.Write("{0} \t \n", dr[i].ToString());
}
ad.Fill(dt);
// ad.Fill(ds);
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
Console.Write("{0} \t \n", row[i].ToString());
}
}
conn.Close();
}
}

Related

Why when i write ItemListView it gives me error?

I'm working on a job about checking in and out of a school. And when I write ListViewItem this always gives an error:
Here is my code:
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Alunos WHERE EntradaSaida = 0", conn);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
ListViewItem item = new ListViewItem(dr["ID"].ToString());
item.SubItems.Add(dr["Nome"].ToString());
item.SubItems.Add(dr["Sobrenome"].ToString());
item.SubItems.Add(dr["TurmaID"].ToString());
item.SubItems.Add(dr["Data"].ToString());
lvEntrada.Items.Add(item);
}
if (lvEntrada.SelectedItems.Count > 0)
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE Alunos SET ID =#ID EntradaSaida =#Entrada, Data = #Data ", conn))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#Data", DateTime.Now);
cmd.Parameters.AddWithValue("#Entrada", 1);
int rows = cmd.ExecuteNonQuery();
}
}
Add
using System.Windows.Forms;
at the top of your cs file.
Or you know what else.... don't pass in a parameter to your listView...
ListViewItem item = new ListViewItem();
item.SubItems.Add(dr["ID"].ToString());
item.SubItems.Add(dr["Nome"].ToString());
item.SubItems.Add(dr["Sobrenome"].ToString());
item.SubItems.Add(dr["TurmaID"].ToString());
item.SubItems.Add(dr["Data"].ToString());
lvEntrada.Items.Add(item);
What is lvEntrada? does it have a property named Items?

Check row length if greater then 0 then print data and while printing add for (i = 0; i <= dt.Rows.Count - 1; i++)

Iam trying to print data base value and the radio buttons in to a div but my problem is first if there are no rows in the table i need to show that there are no rows and the second probllem i want to add for (i = 0; i <= dt.Rows.Count - 1; i++) for condition as am using radio buttons that are dynamically generated i need to add i means number to each fetch.
string xxx= SessionManager.xxxxxxxx;
string htmlStr = "";
using (MySqlConnection myConnection = new MySqlConnection(constr))
{
string oString = "Select * from xxxxx WHERE xxxx=#xxxx and xxxx=#xxxx ";
MySqlCommand oCmd = new MySqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#xxxx", "0");
oCmd.Parameters.AddWithValue("#xxxx", "0");
myConnection.Open();
using (MySqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
string Name = oReader["xxxx"].ToString();
// string Pass = oReader["xxxx"].ToString();
htmlStr += "<tr><td>" + Name + "</td><td><input type='radio' name='Present' value='Present'></td><td><input type='radio' name='Absent' value='Absent'></td><td><input type='radio' name='Leave' value='Leave'></td></tr>";
}
myConnection.Close();
}
}
STUDENT_LIST.InnerHtml = htmlStr;
MySqlDataReader has a readonly property called as "HasRows". The usage of it is;
if(oReader.HasRows)
{
// Perform operation
}
else
// Some other operation
The link for detailed list of members and methods of MySqlDataReader is here
UPDATE:
If you are looking for an example for the usage of MySqlDataAdapter, I would suggest you to go through the DataSet & MySqlDataAdapter section of this link
Hope this helps.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("select * from your_table", con);
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
int num = ds.Tables[0].Rows.Count;
for (int i = 0; i < num - 1; i++)
//Do something here
}
catch (Exception ex)
{
//...
}
finally
{
con.Close();
}
Hope it helps

How to connect to database through ODBC

private void Form7_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Integrated Security=true;database=EDIXfer");
SqlDataAdapter da = new SqlDataAdapter("select EDIScheduleID from ETAProcessSchedule", cn);
DataTable dt = new DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
comboBox1.Items.Add(dt.Rows[x][0].ToString());
}
}
The above code is working fine, but in case of OLEDB or ODBC, it's not working (namespaces added for both OLEDB and ODBC).
using System.Data.Odbc;
private void Form7_Load(object sender, EventArgs e)
{
OdbcConnection cn = new OdbcConnection("Integrated Security=true;database=EDIXfer");
OdbcDataAdapter da = new OdbcDataAdapter("select EDIScheduleID from ETAProcessSchedule", cn);
DataTable dt = new DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
comboBox1.Items.Add(dt.Rows[x][0].ToString());
}
}
How to correctly connect to database using ODBC?
This might help,
using (OdbcCommand com = new OdbcCommand(
"SELECT ColumnWord FROM OkieTable WHERE MagicKey = ?", con))
{
com.Parameters.AddWithValue("#var", paramWord);
using (OdbcDataReader reader = com.ExecuteReader())
{
while (reader.Read())
{
string word = reader.GetString(0);
// Word is from the database. Do something with it.
}
}
}

How to Display Warning message if quantity is less than 5 items

I'm creating an inventory system which should display the products that needs to be restock. If the quantity of the product is only 5 it should display a message that says you need to restock now. But I don't know how to do that because I'm creating an Inventory System only and not Sales and Inventory so how should I deduct it if I don't have sales system? I'm sorry, hope u guys understand.
Here is my code:
public void all()
{
SqlConnection MySqlConnection;
DataTable p_table = new DataTable();
MySqlConnection = new SqlConnection("Data Source=christina\\sqlexpress;Initial Catalog=cafe_inventory;User ID=sa;Password=tina;");
MySqlConnection.Open();
SqlCommand command1 = new SqlCommand("Select * from inventory", MySqlConnection);
//Clear the datatable to prevent duplicate generation of data in gridview.
p_table.Clear();
SqlDataAdapter m_da = new SqlDataAdapter("Select * from inventory", MySqlConnection);
//DataSet ds = new DataSet();
//DataTable dtable = ds.Tables["empinfo1"];
m_da.Fill(p_table);
// Clear the ListView control
//listView3.Items.Clear();
// Display items in the ListView control
for (int i = 0; i < p_table.Rows.Count; i++)
{
DataRow drow = p_table.Rows[i];
// Only row that have not been deleted
if (drow.RowState != DataRowState.Deleted)
{
// Define the list items
//(drow["bnum"].ToString());
ListViewItem lvi = new ListViewItem(drow["pnum"].ToString());
lvi.SubItems.Add(drow["pname"].ToString());
lvi.SubItems.Add(drow["descr"].ToString());
lvi.SubItems.Add(((DateTime)drow["dater"]).ToShortDateString());
//lvi.SubItems.Add(drow["exp"].ToString());
lvi.SubItems.Add(((DateTime)drow["exp"]).ToShortDateString());
lvi.SubItems.Add(drow["qt"].ToString());
// Add the list items to the ListView
listView2.Items.Add(lvi);
}
}
}
edited code:
public void stock()
{
SqlConnection MySqlConnection;
DataTable p_table = new DataTable();
MySqlConnection = new SqlConnection("Data Source=christina\\sqlexpress;Initial Catalog=cafe_inventory;User ID=sa;Password=tina;");
MySqlConnection.Open();
SqlCommand command1 = new SqlCommand("Select pname from inventory where qt < 5", MySqlConnection);
//Clear the datatable to prevent duplicate generation of data in gridview.
p_table.Clear();
SqlDataAdapter m_da = new SqlDataAdapter("Select pname from inventory where qt < 5", MySqlConnection);
m_da.Fill(p_table);
SqlDataReader reader;
reader = command1.ExecuteReader();
StringBuilder productNames = new StringBuilder();
while (reader.Read())
{
productNames.Append(reader["pname"].ToString() + Environment.NewLine);
}
MySqlConnection.Close();
MessageBox.Show("There are products that needs restocking, check to restock now." + productNames);
// Display items in the ListView control
for (int i = 0; i < p_table.Rows.Count; i++)
{
DataRow drow = p_table.Rows[i];
// Only row that have not been deleted
if (drow.RowState != DataRowState.Deleted)
{
// Define the list items
//ListViewItem lvi = new ListViewItem(drow["bnum"].ToString());
ListViewItem lvi = new ListViewItem(drow["pnum"].ToString());
lvi.SubItems.Add(drow["pname"].ToString());
lvi.SubItems.Add(drow["descr"].ToString());
lvi.SubItems.Add(((DateTime)drow["dater"]).ToShortDateString());
//lvi.SubItems.Add(drow["exp"].ToString());
lvi.SubItems.Add(((DateTime)drow["exp"]).ToShortDateString());
lvi.SubItems.Add(drow["qt"].ToString());
lvi.SubItems.Add(drow["interval"].ToString());
// Add the list items to the ListView
listView4.Items.Add(lvi);
}
}
}
Try This:
void DisplayLowQuantityItems()
{
MySqlConnection con = new MySqlConnection("Data Source=christina\\sqlexpress;
Initial Catalog=cafe_inventory;User ID=sa;Password=tina;");
MySqlCommand command = new MySqlCommand("Select pname from inventory
where qt < 5", con);
con.Open();
MySqlDataReader reader = commad.ExecuteReader();
StringBuilder productNames= new StringBuilder();
while(reader.Read())
{
productNames.Append(reader["pname"].ToString()+Environment.NewLine);
}
con.Close();
MessageBox.Show("Following Products quantity is lessthan 5\n"+productNames);
}
Solution 2:
edited code:
public void stock()
{
MySqlConnection con;
DataTable p_table = new DataTable();
con = new MySqlConnection("Data Source=christina\\sqlexpress;Initial
Catalog=cafe_inventory;User ID=sa;Password=tina;");
con.Open();
MySqlCommand command1 = new MySqlCommand("Select pname from inventory where
qt < 5", con);
//Clear the datatable to prevent duplicate generation of data in gridview.
p_table.Clear();
MySqlDataAdapter m_da = new MySqlDataAdapter("Select * from inventory where
qt < 5", con);
m_da.Fill(p_table);
MySqlDataReader reader;
reader = command1.ExecuteReader();
StringBuilder productNames = new StringBuilder();
while (reader.Read())
{
productNames.Append(reader["pname"].ToString() + Environment.NewLine);
}
con.Close();
MessageBox.Show("There are products that needs restocking,
check to restock now." + productNames);
// Display items in the ListView control
for (int i = 0; i < p_table.Rows.Count; i++)
{
DataRow drow = p_table.Rows[i];
// Only row that have not been deleted
if (drow.RowState != DataRowState.Deleted)
{
// Define the list items
//ListViewItem lvi = new ListViewItem(drow["bnum"].ToString());
ListViewItem lvi = new ListViewItem(drow["pnum"].ToString());
lvi.SubItems.Add(drow["pname"].ToString());
lvi.SubItems.Add(drow["descr"].ToString());
lvi.SubItems.Add(((DateTime)drow["dater"]).ToShortDateString());
//lvi.SubItems.Add(drow["exp"].ToString());
lvi.SubItems.Add(((DateTime)drow["exp"]).ToShortDateString());
lvi.SubItems.Add(drow["qt"].ToString());
lvi.SubItems.Add(drow["interval"].ToString());
// Add the list items to the ListView
listView4.Items.Add(lvi);
}
}
}
another way of checking your data
DataTable p_table = new DataTable();
con = new MySqlConnection("Data Source=christina\\sqlexpress;Initial
Catalog=cafe_inventory;User ID=sa;Password=tina;");
con.Open();
MySqlCommand command1 = new MySqlCommand("Select pname from inventory where
qt < 5", con);
p_table.load(command1.ExecuteReader());

Index was outside the bounds of the array. c# OleDbDataReader

Could someone please tell me what I am doing wrong here. I have compiled my code and I get it to read the ROWS and return the count. However, I get an error when saying the "Index was outside the bounds of the array" when I pass it to this line of code: rowData += dbReader.GetValue(iRow).ToString();
//Create SQL strings
string sql = "SELECT 'Computers' FROM [Sheet1$]";
//Create the instances
OleDbConnection dbConnection;
OleDbDataAdapter dbAdapter;
OleDbCommand dbCommand;
OleDbDataReader dbReader;
DataTable dataTable;
//Call the instance
dbConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + #"\\slcnpr97\Desktop\Game Changers\\computers.xls" + "';Extended Properties='Excel 12.0 Xml;HDR=YES'");
dbConnection.Open();
dbAdapter = new OleDbDataAdapter(sql, dbConnection);
dbCommand = new OleDbCommand(sql, dbConnection);
dataTable = new DataTable();
dbReader = dbCommand.ExecuteReader();
dbAdapter.Fill(dataTable);
//Method Variable
int iRow = dataTable.Rows.Count;
string rowData = null;
while (dbReader.Read())
{
for (int i = 0; i < iRow; i++)
{
rowData += dbReader.GetValue(iRow).ToString();
}
}
//Close Connections
dbReader.Close();
dbConnection.Close();
MessageBox.Show(rowData);
You should modify
int iRow = dataTable.Rows.Count;
to
int numFields = dbReader.FieldCount;
Your for loop then becomes
for (int i = 0; i < numFields; i++)
{
rowData += dbReader.GetValue(numFields).ToString();
}
try with (Set dbReader.GetValue(0).ToString())
while (dbReader.Read())
{
for (int i = 0; i < iRow; i++)
{
rowData += dbReader.GetValue(0).ToString();
}
}

Categories

Resources