"There is no row at position 0 how to fix it" - c#

During find data between two days, getting error "there is no row at position 0"
MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["Demo"].ConnectionString.ToString());
string str = "select * from sample where name='" + Session["name"] + "' and date between '" + txtfirstdate.Text + "' and '" + txtenddate.Text + "'";
MySqlCommand cmd = new MySqlCommand(str, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataSet set = new DataSet();
connection.Open();
adapter.Fill(set);
connection.Close();
//var table = set.Tables[0];
if (set != null)
{
lblname.Text = set.Tables[0].Rows[0]["name"].ToString();
lbldate.Text = set.Tables[0].Rows[0]["date"].ToString();
}

Read the Error Message. Your result set table has no rows.
Replace u r if Condition.
if (set.Tables[0].Rows.Count > 0) {
lblname.Text = set.Tables[0].Rows[0]["name"].ToString();
lbldate.Text = set.Tables[0].Rows[0]["date"].ToString();
}

Related

syntax error (missing operator) in query expression

I'm using c# and this error is becoming headache for me. I do not know how to solve this error .
can anyone help me to solve this. Here is the code
try
{
string MyConnection2 = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\DELL\Documents\db1.mdb";
//Display query
string Query = "select riq_num , department, item_name , item_unit , no_of_stock_out , itemtype from outputdet1 where riq_num = " + textBox2.Text + " or department= '" + comboBox1.Text + " ' or item_name= '" + textBox4.Text + "' or item_unit= '" + comboBox2.Text + "' or no_of_stock_out = " + textBox6.Text + " or itemtype = '" + comboBox3.Text + "' ; ";
OleDbConnection MyConn2 = new OleDbConnection(MyConnection2);
OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
MyConn2.Open();
//For offline connection we will use MySqlDataAdapter class.
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
// here i have assign dTable object to the dataGridView1 object to display data.
dataGridView1.DataSource = dTable;
MyConn2.Close();
}
// OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I assumed that textBox2.Text & textBox6.Text return a string from textbox control, so that OleDbCommand will throwing exception when it contains empty value or any non-numeric string since it will form invalid SQL statement. Use parameterized query like this example:
string Query = #"select riq_num, department, item_name, item_unit, no_of_stock_out, itemtype
from outputdet1
where riq_num = #riq_num
or department= #department
or item_name= #item_name
or item_unit= #item_unit
or no_of_stock_out = #no_of_stock_out
or itemtype = #itemtype";
using (OleDbConnection MyConn2 = new OleDbConnection(MyConnection2))
{
using (OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2))
{
MyConn2.Open();
MyCommand2.Parameters.Add("#riq_num", textBox2.Text);
MyCommand2.Parameters.Add("#department", comboBox1.Text);
MyCommand2.Parameters.Add("#item_name", textBox4.Text);
MyCommand2.Parameters.Add("#item_unit", comboBox2.Text);
MyCommand2.Parameters.Add("#no_of_stock_out", textBox6.Text);
MyCommand2.Parameters.Add("#itemtype", comboBox3.Text);
// execute the query here
}
}
Remember that using statements used to dispose OLEDB connection immediately after it has closed so that GC can free up resources.
Additional note:
OleDbParameter works with parameter order instead of named parameters, hence ensure that the parameters are declared in their proper order from first to last.

How to add value of column A if it exist on Table 2 using Datagridview

Mabuhay!
What is the most efficient or more convenient way to do this.
I have a select query and put it on a datagridview base on my filter. It has 5 columns. I want to know if Column CA from that Datagridview already exist on Table 2 which is on Column 3?
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=db;User ID=sa;Password=pw");
// DateTime dt = new DateTime();
//dt = DateTime.Now.ToString();
SqlDataAdapter sda = new SqlDataAdapter("SELECT max(PurchaseOrder.POTitle) as Description,sum(PurchaseOrderEntry.Price *PurchaseOrderEntry.QuantityOrdered) as Amount, max(PurchaseOrder.PONumber)as PONumber, " +
" max(PurchaseOrderEntry.OrderNumber) as BoxCount, max(PurchaseOrderEntry.OrderNumber) as PLC,max(PurchaseOrderEntry.OrderNumber) as Branch, max(PurchaseOrderEntry.OrderNumber) as PreparedBy, max(PurchaseOrderEntry.OrderNumber) as CheckedBy " +
" FROM PurchaseOrder LEFT OUTER JOIN" +
" PurchaseOrderEntry ON PurchaseOrder.ID = PurchaseOrderEntry.PurchaseOrderID" +
" WHERE (PurchaseOrder.Remarks like '%" + tanggapan.Text + "%') AND (PurchaseOrder.DateCreated BETWEEN '" + dateTimePicker1.Text + "' AND '" + dateTimePicker2.Text + "' and PurchaseOrder.OtherStoreID = '" + branch.Text + "') Group By PurchaseOrder.PONumber", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
This show my query filter. Any tip on how to do if PurchaseOrderEntry.OrderNumber already exist on my records so I can manage which one repeats.
Thank you!
Chris
I added this code now on my works and it is working now.
DataTable dt = new DataTable();
dt.Clear();
dt.Reset();
con.Close();
adaptors1.SelectCommand = con.CreateCommand();
adaptors1.SelectCommand.CommandText = "Select TOP 1 [ponumber],[clref] from [ISSPandayan].[dbo].[" + branch.Text + "] where [ponumber] = '" + dr.Cells["ponumber"].Value + "' ORDER BY [clref] ASC";
adaptors1.Fill(dt);
// select query para malam kung existing ponumber
if (dt.Rows.Count == 1)
{
adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = dt.Rows[0][1].ToString();
}
else
{
adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = " ";
}
//adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = "";
//MessageBox.Show(Convert.ToString(dr.Cells["description"].Value));
con.Close();
con.Open();
adaptorss.InsertCommand.ExecuteNonQuery();
adaptorss.InsertCommand.Parameters.Clear();

OracleDataAdapter.Fill throws "SQL command not properly ended"

OracleDataAdapter.Fill throws an exception: "ORA-00933: SQL command not properly ended". Usual culprits according to many posts is that some spaces or semicolon at the end. I copied the statement and executed on Oracle "Sql Developer", and it works..
Here is my code (kind of)
var stmt = "SELECT fmly.fmly_id, fmly.fmly_key, fmly.fmly_db_view_nm, MI_DBUMS_UTIL.GET_BASELINE_TABLE_NAME(fmly.fmly_id) blTableName " +
"FROM mi_families AS fmly WHERE fmly.fmly_type_cd = 'ENFA' " +
"AND fmly.fmly_id not in (SELECT fmly_id from mi_exclude_families WHERE context_cd = 'REVERT') " +
"AND EXISTS " + "(SELECT 1 FROM mi_entities_bl AS enty_bl WHERE fmly.fmly_id = enty_bl.fmly_id);";
var conn = new OracleConnection("<connection string>");
var cmd = new OracleCommand(stmt, conn)
IDataAdapter adapter = new OracleDataAdapter(cmd);
DataSet ds = new DataSet();
conn.Open();
cmd.CommandTimeout = 0;
adapter.Fill(ds)
Can someone plz help me with the reason for the exception thrown?
Try this?
var stmt = "SELECT fmly.fmly_id, fmly.fmly_key, fmly.fmly_db_view_nm, MI_DBUMS_UTIL.GET_BASELINE_TABLE_NAME(fmly.fmly_id) blTableName " +
"FROM mi_families AS fmly WHERE fmly.fmly_type_cd = 'ENFA' " +
"AND fmly.fmly_id not in (SELECT fmly_id from mi_exclude_families WHERE context_cd = 'REVERT') " +
"AND EXISTS " + "(SELECT 1 FROM mi_entities_bl AS enty_bl WHERE fmly.fmly_id = enty_bl.fmly_id)";
var conn = new OracleConnection("<connection string>");
var cmd = new OracleCommand(stmt, conn);
IDataAdapter adapter = new OracleDataAdapter(cmd);
DataSet ds = new DataSet();
conn.Open();
cmd.CommandTimeout = 0;
adapter.Fill(ds);
Remove the semi-colon at the end of the SELECT statement and it should work.

DataGrid View Not Showing Newly Added Record using Access Database

I am new to C# and I want to do this ASAP as I've had this problem since past week. I have tried a few approaches and not yet gotten the correct output. Here is my code:
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
String itemcode = tbItemCode.Text.ToString();
String shade = tbShade.Text.ToString();
String rollnumber = tbRollNumber.Text.ToString();
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Eranga\Documents\Visual Studio 2010\Projects\RollAllocationModel\RollAllocationModel\Roll.mdb;Persist Security Info=True;Jet OLEDB:Database Password=admin");
String deletequery = "DELETE FROM TabRoll WHERE (ItemCode = '" + itemcode + "') AND (Shade = '" + shade + "') AND (RollNumber = '" + rollnumber + "')";
//String deletequery = "SELECT * FROM TabRoll";
//code by query builder ----> DELETE FROM TabRoll WHERE (ItemCode = '" + itemcode + "') AND (Shade = '" + shade + "') AND (RollNumber = '" + length + "');
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(deletequery, conn);
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bSource = new BindingSource();
bSource.DataSource = dt;
dataGridView1.EndEdit();
bSource.EndEdit();
da.Update(dt);
dataGridView1.DataSource = bSource;
conn.Close();
MessageBox.Show("Data deleted");
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
}
Why doesn't the DataGrid does not update with the new record.

Problem in using DataSet

I have first manually created a DataSet in my project name recvd.xsd having corresponding recvd.xss. On my button click event i have done the following coding.
try
{
DataSet recvd_REPORT = new DataSet();
DataTable REPORT = new DataTable();
String dd_webCofig = ConfigurationManager.ConnectionStrings["server2"].ConnectionString;
OdbcConnection ddlistconn = new OdbcConnection(dd_webCofig);
ddlistconn.Open();
REPORT = recvd_REPORT.Tables["REPORT"];
DataColumn myDataColumn = new DataColumn();
myDataColumn.DataType = typeof(System.Int32);
myDataColumn.ColumnName = "RECEIVED";
myDataColumn.ReadOnly = false;
myDataColumn.Unique = false;
// Add the Column to the DataColumnCollection.
REPORT.Columns.Add(myDataColumn);
string query = "SELECT case_no as \"RECEIVED\" from dcpanaji.Civil_t where dt_regis > '" + txtStartDate.Text + "' AND dt_regis < '" + txtEndDate.Text + "' AND court_no = " + DropDownList1.SelectedItem + "";
Response.Write(query);
OdbcCommand cmd = new OdbcCommand(query, ddlistconn);
OdbcDataReader loginMyReader = cmd.ExecuteReader();
OdbcDataAdapter adptr = new OdbcDataAdapter(query, ddlistconn);
adptr.Fill(REPORT);
ddlistconn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
I am getting the error as
Object reference not set to an instance of an object.
If i remove as \"RECEIVED\" from my SQL query and simply execute my SQL query than the result of my query is as follows (varies depending on user input)
200200000452011 ......, n numbers of 12 digit number.
Please help me to remove the error as to why am i not able to bind to DataTable.
I am getting the error before Response.Write(query); is executed, why is that problem?
I removed the try catch block and now i get the error as
try
SELECT case_no as `RECEIVED` ...
or just
SELECT case_no as RECEIVED ...
Anyway the correct DataSet filling code should look like this:
DataSet ds = new DataSet();
using (OdbcConnection connection = new OdbcConnection(connectionString))
using (OdbcCommand command = new OdbcCommand(sqlQuery, connection)
using (OdbcDataAdapter adapter = new OdbcDataAdapter(command)
{
adapter.Fill(ds);
}
In your SQL instead of \"RECIEVED\" have you tried just RECIEVED, no quotes?
You need not to use \"RECEIVED\" in the query, you can use like below.
query = "SELECT case_no as [RECIEVED] from dcpanaji.Civil_t where dt_regis > '" + txtStartDate.Text + "' AND dt_regis < '" + txtEndDate.Text + "' AND court_no = " + DropDownList1.SelectedItem + "";
you can write query as like
query = "SELECT case_no as RECIEVED from dcpanaji.Civil_t where dt_regis > '" + txtStartDate.Text + "' AND dt_regis < '" + txtEndDate.Text + "' AND court_no = " + DropDownList1.SelectedItem + "";
check like that....

Categories

Resources