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

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();
}
}

Related

shopping cart in c# does not work correctly

Actually I am preparing an app in c# like a shopping cart and my bill does not work. When I load the page it keeps loading and shows no error or something else, it just keeps loading and shows nothing. The app is built in c# with asp.net webforms. I have tried without including loop while and i and then it just display one row. I dont know why the loop does not work.
public partial class myQueries : System.Web.UI.Page
{
public SqlDataAdapter da;
public DataSet ds;
public SqlConnection sqlConn;
public SqlConnection sqlConn1;
protected void Page_Load(object sender, EventArgs e)
{
string uID = Session["uID"].ToString();
int userID = int.Parse(uID);
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("requestID");
dt.Columns.Add("request");
dt.Columns.Add("solution");
dt.Columns.Add("qtyn");
dt.Columns.Add("price");
dt.Columns.Add("totalprice");
sqlConn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["OHDConn"].ConnectionString);
sqlConn.Open();
string queryRequest = "select requestID,request,solution,qtyn,price from request where userID = '" + userID + "' and solution is not Null";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = queryRequest;
cmd.Connection = sqlConn;
da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
int totalrows = ds.Tables[0].Rows.Count;
int i = 0;
while (i < totalrows)
{
dr = dt.NewRow();
dr["requestID"] = ds.Tables[0].Rows[i]["requestID"].ToString();
dr["request"] = ds.Tables[0].Rows[i]["request"].ToString();
dr["solution"] = ds.Tables[0].Rows[i]["solution"].ToString();
dr["qtyn"] = ds.Tables[0].Rows[i]["qtyn"].ToString();
dr["price"] = ds.Tables[0].Rows[i]["price"].ToString();
double price = Convert.ToDouble(ds.Tables[0].Rows[i]["price"].ToString());
int qty = Convert.ToInt16(ds.Tables[0].Rows[i]["qtyn"].ToString());
double totalprice = price * qty;
dr["totalprice"] = totalprice;
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.FooterRow.Cells[5].Text = grandTotal().ToString();
Label2.Text = DateTime.Now.ToShortDateString();
}
}
public double grandTotal()
{
DataTable dt = new DataTable();
int nrow = dt.Rows.Count;
int i = 0;
double gtotal = 0;
while (i < nrow)
{
gtotal = gtotal + Convert.ToDouble(dt.Rows[i]["totalprice"].ToString());
i = i + 1;
}
return gtotal;
}
There are a couple of issues here:
You're not incrementing 'i' within your while loop.
You're binding your grid within the while loop which is generating your data.
I would suggest the following changes:
Extract a method that returns a DataTable and set that as the DataSource for your GridView
Wrap the code that is binding the data to the GridView in a !IsPostback check. This will help when it comes to acting on events in the GridView.
Example Code
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
GridView1.DataSource = GetData().DefaultView;
GridView1.DataBind();
GridView1.FooterRow.Cells[5].Text = grandTotal().ToString();
}
Label2.Text = DateTime.Now.ToShortDateString();
}
private DataTable GetData()
{
string uID = Session["uID"].ToString();
int userID = int.Parse(uID);
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("requestID");
dt.Columns.Add("request");
dt.Columns.Add("solution");
dt.Columns.Add("qtyn");
dt.Columns.Add("price");
dt.Columns.Add("totalprice");
sqlConn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["OHDConn"].ConnectionString);
sqlConn.Open();
string queryRequest = "select requestID,request,solution,qtyn,price from request where userID = '" + userID + "' and solution is not Null";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = queryRequest;
cmd.Connection = sqlConn;
da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
int totalrows = ds.Tables[0].Rows.Count;
int i = 0;
while (i < totalrows)
{
dr = dt.NewRow();
dr["requestID"] = ds.Tables[0].Rows[i]["requestID"].ToString();
dr["request"] = ds.Tables[0].Rows[i]["request"].ToString();
dr["solution"] = ds.Tables[0].Rows[i]["solution"].ToString();
dr["qtyn"] = ds.Tables[0].Rows[i]["qtyn"].ToString();
dr["price"] = ds.Tables[0].Rows[i]["price"].ToString();
double price = Convert.ToDouble(ds.Tables[0].Rows[i]["price"].ToString());
int qty = Convert.ToInt16(ds.Tables[0].Rows[i]["qtyn"].ToString());
double totalprice = price * qty;
dr["totalprice"] = totalprice;
dt.Rows.Add(dr);
i++;
}
return dt;
}
public double grandTotal()
{
DataTable dt = new DataTable();
int nrow = dt.Rows.Count;
int i = 0;
double gtotal = 0;
while (i < nrow)
{
gtotal = gtotal + Convert.ToDouble(dt.Rows[i]["totalprice"].ToString());
i = i + 1;
}
return gtotal;
}

Showing data in a form in .NET with Postgres

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();
}
}

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

Prevent duplicate entry in database

private void Save_Click(object sender, EventArgs e)
{
string strconn = #"Server=.\SQLEXPRESS;initial catalog=PharmacyV2;integrated security=true;";
SqlConnection conn = new SqlConnection(strconn);
//SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from Units",conn);
da.Fill(ds, "Units");
bool found = false;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < ds.Tables["Units"].Rows.Count; j++)
{
if (ds.Tables["Units"].Rows[j][0].ToString() == dataGridView1.Rows[i].Cells[0].Value.ToString())
{
found = true;
break;
}
}
if (found==false)
{
SqlCommand cmd;
cmd = new SqlCommand("insert into Units (Unit_name) values (#name)", conn);
cmd.Parameters.AddWithValue("#name", dataGridView1.Rows[i].Cells[0].Value.ToString());
cmd.ExecuteNonQuery();
MessageBox.Show("تمت الاضافه");
}
}
conn.Close();
}
my program compare the each element from datagridview with every element from Uint table from database to prevent duplicate in database
if element from datagridvoew is not Similar to element in uint table in database
implement insert statement
Why the program does not insert any data to database?
(Does not implement the insert statement )
initialise your found variable to false inside your first for loop :
found = false;
so that it will be set to initial state for every iteration. otherwise if once it is set to true always becomes true.thats why yor insert statement is not getting executed.
So your for loop should look like :
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
found = false;
for (int j = 0; j < ds.Tables["Units"].Rows.Count; j++)
{
if (ds.Tables["Units"].Rows[j][0].ToString() == dataGridView1.Rows[i].Cells[0].Value.ToString())
{
found = true;
break;
}
}
if (found==false)
{
SqlCommand cmd;
cmd = new SqlCommand("insert into Units (Unit_name) values (#name)", conn);
cmd.Parameters.AddWithValue("#name", dataGridView1.Rows[i].Cells[0].Value.ToString());
cmd.ExecuteNonQuery();
MessageBox.Show("تمت الاضافه");
}
}
How about you ask the database to check if the entry exists?
var unitName = dataGridView1.Rows[i].Cells[0].Value.ToString();
var command = new SqlCommand("SELECT COUNT(*) FROM Units WHERE Unit_name = #name", connection);
command.Parameters.AddWithValue("#name", unitName);
int result = (int)command.ExectureScalar();
if(result == 0) // no entry
{
//Insert.
}

Reading multiple devices together from single serial port in C# winforms

I am supposed to read tags from multiple devices but using single port.
I am able to do so, but while I read one device keeping tag in front of it another device does not read into string unless I remove the tag.
I need to read the tags from all devices simultaneously.
It works on hyperterminal so the problem is in code
My Code:
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//int bytes = serialPort1.BytesToRead;
////create a byte array to hold the awaiting data
//byte[] comBuffer = new byte[bytes];
////read the data and store it
//serialPort1.Read(comBuffer, 0, bytes);
//MessageBox.Show(comBuffer[bytes]);
////display the data to the user
////DisplayData(MessageType.Incoming, ByteToHex(comBuffer) + "\n");
//serialPort1.Dispose();
//serialPort1.Close();
//if (serialPort1.IsOpen)
//{
// serialPort1.ReadExisting();
// serialPort1.Close();
//}
string data = serialPort1.ReadLine();
data = data.Substring(2, 2);
if (data == "03")
{
//while (data == "03")
//{
string data1 = serialPort1.ReadLine();
data1 = data1.Substring(4, 10);
for (int b = 0; b < dataGridView3.Rows.Count; b++)
{
string floorno = dataGridView3.Rows[b].Cells[0].Value.ToString();
SqlConnection conn = new SqlConnection(dba.GetConnectionString());
SqlCommand cmd = new SqlCommand("Select Floor,RfidTag,DeviceId from LiftMonitor where Floor='" +
floorno + "'and DeviceId='03'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
ds = new DataSet();
SqlCommandBuilder commandBuilder1 = new SqlCommandBuilder(da);
da.Fill(ds, "LiftMonitor");
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
DataRow dr = ds.Tables[0].Rows[j];
string rfidtag = dr["RfidTag"].ToString();
if (rfidtag == data1)
{
dataGridView3.ClearSelection();
dataGridView3.Rows[b].Selected = true;
goto abc;
timer1.Start();
SqlConnection conn1 = new SqlConnection(dba.GetConnectionString());
SqlCommand cmd1 = new SqlCommand(" Select Timer from Setting ", conn1);
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da1);
da1.Fill(ds1, "Timer");
for (int k = 0; k < ds1.Tables[0].Rows.Count; k++)
{
DataRow dr1 = ds1.Tables[0].Rows[k];
string timer = dr1["Timer"].ToString();
int timer2 = Convert.ToInt32(timer);
timeConversion = timer2 * 1000;
if (timeConversion.Equals(timer1.Interval))
{
timer1.Tick += new System.EventHandler(timer1_Tick);
}
}
}
else
{
}
}
}
//}
}
if (data == "04")
{
//while (data == "04")
//{
string data1 = serialPort1.ReadLine();
//data1 = data1.Substring(1, 2);
data1 = data1.Substring(4, 10);
for (int b = 0; b < dataGridView4.Rows.Count; b++)
{
string floorno = dataGridView4.Rows[b].Cells[0].Value.ToString();
SqlConnection conn = new SqlConnection(dba.GetConnectionString());
SqlCommand cmd = new SqlCommand("Select Floor,RfidTag,DeviceId from LiftMonitor where Floor='" +
floorno + "' and DeviceId='04'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
ds = new DataSet();
SqlCommandBuilder commandBuilder1 = new SqlCommandBuilder(da);
da.Fill(ds, "LiftMonitor");
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
DataRow dr = ds.Tables[0].Rows[j];
string rfidtag = dr["RfidTag"].ToString();
if (rfidtag == data1)
{
dataGridView4.ClearSelection();
dataGridView4.Rows[b].Selected = true;
goto abc;
timer1.Start();
SqlConnection conn1 = new SqlConnection(dba.GetConnectionString());
SqlCommand cmd1 = new SqlCommand(" Select Timer from Setting ", conn1);
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da1);
da1.Fill(ds1, "Timer");
for (int k = 0; k < ds1.Tables[0].Rows.Count; k++)
{
DataRow dr1 = ds1.Tables[0].Rows[k];
string timer = dr1["Timer"].ToString();
int timer2 = Convert.ToInt32(timer);
timeConversion = timer2 * 1000;
if (timeConversion.Equals(timer1.Interval))
{
timer1.Tick += new System.EventHandler(timer1_Tick);
}
}
}
else
{
}
}
}
//}
}
if (data == "05")
{
//while (data == "05")
//{
string data1 = serialPort1.ReadLine();
data1 = data1.Substring(4, 10);
for (int b = 0; b < dataGridView5.Rows.Count; b++)
{
string floorno = dataGridView5.Rows[b].Cells[0].Value.ToString();
SqlConnection conn = new SqlConnection(dba.GetConnectionString());
SqlCommand cmd = new SqlCommand("Select Floor,RfidTag,DeviceId from LiftMonitor where Floor='" +
floorno + "'and DeviceId='05'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
ds = new DataSet();
SqlCommandBuilder commandBuilder1 = new SqlCommandBuilder(da);
da.Fill(ds, "LiftMonitor");
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
DataRow dr = ds.Tables[0].Rows[j];
string rfidtag = dr["RfidTag"].ToString();
if (rfidtag == data1)
{
dataGridView5.ClearSelection();
dataGridView5.Rows[b].Selected = true;
//break;
goto abc;
timer1.Start();
SqlConnection conn1 = new SqlConnection(dba.GetConnectionString());
SqlCommand cmd1 = new SqlCommand(" Select Timer from Setting ", conn1);
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da1);
da1.Fill(ds1, "Timer");
for (int k = 0; k < ds1.Tables[0].Rows.Count; k++)
{
DataRow dr1 = ds1.Tables[0].Rows[k];
string timer = dr1["Timer"].ToString();
int timer2 = Convert.ToInt32(timer);
timeConversion = timer2 * 1000;
if (timeConversion.Equals(timer1.Interval))
{
timer1.Tick += new System.EventHandler(timer1_Tick);
}
}
}
//else
//{
// break;
//}
}
}
}
}

Categories

Resources