Dataset not being filled - c#

the follwing functions gives me an error:
FillFields("select Housemcode,Name, HP,Rateperhour ,Resource_H_Code FROM House_Machinery where Housemcode like '" + sSearch + "'");
public void FillFields(string sSQL)
{
sCommands.setSqldbCommand(sVariables.sDataSet, sVariables.sSqlDbDataAdapter, sSQL, "House_Machinery");
DataRow sDataRow = sVariables.sDataSet.Tables["House_Machinery"].Rows[0];
txtItemName.Text = sDataRow["Name"].ToString();
txtrate.Text = sDataRow["HP"].ToString();
txtrate.Text = sDataRow["Rateperhour"].ToString();
Variables.StrResourceHeaderCode = sDataRow["Resource_H_Code"].ToString();
}
the error is:
There is no row at position 0.
can any one give an insight on this?

Your query is simply not returning any rows. Try running the SQL query directly in SQL Management Studio to confirm that data is returned.
Incidentally, you can check whether any data is returned at run-time by counting the rows returned:
sCommands.setSqldbCommand(sVariables.sDataSet, sVariables.sSqlDbDataAdapter, sSQL, "House_Machinery");
if(sVariables.sDataSet.Tables["House_Machinery"].Rows.Count == 0)
throw new Exception("No matching rows found");
DataRow sDataRow = sVariables.sDataSet.Tables["House_Machinery"].Rows[0];

1.Just check with Breakpoints if it works well,
2.Does your Sql query working in sql server ? check that it may circle it out.
3.Check your wildcard "%like%",this may have issues.
void somewhereelse()
{
string qry = "select Housemcode,Name, HP,Rateperhour ,Resource_H_Code FROM House_Machinery where Housemcode like '" + sSearch + "'";
filldetails(qry);
}
protected void filldetails(string someqry)
{
Sqlconnection conn = new SqlConnection("Connectionstring");
Datatable dt = new Datatable();
try
{
conn.Open();
SqlDataAdapter dap = new SqlDataAdapter(someqry,conn);
dap.fill(dt);
if(dt.rows.count >0)
{
txtItemName.Text = dt.rows.[0]["Name"].ToString();
txtrate.Text = dt.rows.[0]["HP"].ToString();
txtrate.Text = dt.rows.[0]["Rateperhour"].ToString();
}
}
catch
{
throw;
}
finally
{
if(conn!= null)
{
conn.close();
}
}

Related

Datatable always retrieving first record of the table in c#

I am performing search operation based on id which is auto incremented when I enter id as 0 it is retrieving data which is having id 1.
This is the search method
public DataTable Search(int code=0)
{
SqlConnection con = sqlConnection;
String Query = "Select * from person" + (code > 0 ? " where code =" + code : "");
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(Query, con);
{
DataTable dataTable = new DataTable("Temp");
sqlDataAdapter.Fill(dataTable);
con.Close();
return dataTable;
}
}
This is search button code
private void btnSearch_Click(object sender, EventArgs e)
{
if(txtSearchCode.Text.Length>0)
{
DataTable dataTable = new SqlHelper().Search(int.Parse(txtSearchCode.Text));
if(dataTable.Rows.Count>0)
{
try
{
txtCode.Text = dataTable.Rows[0]["code"].ToString();
txtFirstname.Text = dataTable.Rows[0]["firstname"].ToString();
txtLastname.Text = dataTable.Rows[0]["lastname"].ToString();
var a = dataTable.Rows[0]["gender"].ToString() == "Male" ? rbnMale.Checked = true : rbnFemale.Checked = true;
txtMobile.Text = dataTable.Rows[0]["mobile"].ToString();
dtpDOB.Text = dataTable.Rows[0]["dob"].ToString();
txtAge.Text = dataTable.Rows[0]["age"].ToString();
chkStatus.Checked = dataTable.Rows[0]["status"].ToString() == "active"? true :false;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("No Data Found");
}
}
else
{
MessageBox.Show("Please Enter Code");
}
}
You are not sending a where class if your conditional expression code > 0 is not satisfied, which is why sql-server returns all rows from the table person. Then when you pick the first row from the datatable using dataTable.Rows[0] it picks the one with id 1.
A better and secure way is to use a parameterized query instead.
String Query = "Select * from person where code = #code";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(Query, con);
sqlDataAdapter.SelectCommand.Parameters.AddWithValue("#code",code);
When you use Code = 0; you actually are doing select * from table.
But in the btnSearch_Click handler you are always processing 0th Rows from the resultset.
txtCode.Text = dataTable.Rows[0]["code"].ToString(); <------ See this line you have [0] hardcoded
Possibly the record with id 1 is first record in your query Result Set.
Edit:
You need to Loop through dataTable.Rows[] array and capture/process each result.

Data gets duplicated in datagridview when query applied?

I am trying to perform CRUD operation on winform
This is for ASP.NET winform in which whenever I try to insert, update or delete the data to or from the database first of all rows and inside content gets duplicated
https://imgur.com/a/d5jgv6H
however, upon restarting the application data shows up correctly
private void button2_Click(object sender, EventArgs e)
{
//insert
try
{
con.Open();
//.text property gets/Sets text associated with this control
String name = textBox1.Text.ToString();
String address = textBox2.Text.ToString();
String number = textBox3.Text.ToString();
long pnumber = Int64.Parse(number);
String sem = textBox4.Text.ToString();
long semester = Int64.Parse(sem);
string branch = comboBox1.SelectedItem.ToString();
String query = "insert into student values('" + name + "','" + address + "'," + pnumber + "," + semester + ",'" + branch + "')";
SqlCommand sqlcom = new SqlCommand(query, con);
int i = sqlcom.ExecuteNonQuery();
if (i >= 1)
{
MessageBox.Show("Student has been Registered: " + name);
}
else
{
MessageBox.Show("Registration Failed ! ");
}
//clearing data
button1_Click(sender, e);
show();
con.Close();
}
catch (Exception exp)
{
MessageBox.Show("Error is : " + exp.ToString());
}
}
void show()
{
String query = "select * from student";
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
DataTable dataInTable = new DataTable();
adapter.Fill(dataInTable);
//DataRow represents row of data in DataTable
foreach (DataRow item in dataInTable.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[n].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[n].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[n].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[n].Cells[4].Value = item[4].ToString();
}
}
The query works fine but rows still get duplicated. What's the problem?
I can't find any bug, so I assume I am doing something incorrectly.
Your show method adds rows to the grid, but it never removes the rows which are already in the grid.
Normally one would use data binding to populate a DataGridView or other data-bound controls. I'm going to assume you have reasons for just adding rows directly (perhaps it's simpler for your needs) and not change that. Given that structure, probably the easiest thing to do is just to clear the grid before adding the new rows:
void show()
{
String query = "select * from student";
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
DataTable dataInTable = new DataTable();
adapter.Fill(dataInTable);
dataGridView1.Rows.Clear(); // <--- here
foreach (DataRow item in dataInTable.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[n].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[n].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[n].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[n].Cells[4].Value = item[4].ToString();
}
}
That way any time you are about to populate the grid with new data, you first clear the existing data from it.

C# datagrid not populating and no error

My first problem is that i have a method private void FillGeneralLedger(), i put the method in a button on click event to fill a datagridview dgvGeneralLedger my problem is when i run i am not getting an error and the dgv is remaining empty.
My Second problem is i would like to use the same connection but have 5 commands all the same just different account numbers eg in the example below the account below is '8200030' i would like to do the same for '8200031','8200032'
private void FillGeneralLedger()
{
SqlConnection conn = new SqlConnection(sConnectionString);
try
{
DataSet dataset = new DataSet();
SqlCommand command = new SqlCommand("Select Ddate as Date" +
", etype" +
", Refrence" +
", linkacc as ContraAcc" +
", Description" +
", sum(case when amount > 0 then amount else 0 end) as Debits" +
", sum(case when amount < 0 then amount else 0 end) as Credits" +
", sum(amount) as Cumulative" +
" FROM dbo.vw_LedgerTransactions " +
" WHERE accnumber = '8200030'" +
" AND DDate BETWEEN '2016-04-01 00:00:00' AND '2016-04-30 00:00:00'" +
" AND DataSource = 'PAS11CEDCRE17'" +
" group by Ddate, etype, Refrence, linkacc, Description, Amount", conn);
SqlDataAdapter adapter = new SqlDataAdapter(command);
conn.Open();
command.ExecuteNonQuery();
adapter.Fill(dataset);
if (dataset.Tables[0].Rows.Count != 0)
{
lstGeneralLedger = new List<ReportDataClasses.GeneralLedger>();
foreach (DataRow row in dataset.Tables[0].Rows)
{
ReportDataClasses.GeneralLedger newGeneralLedger = new ReportDataClasses.GeneralLedger();
newGeneralLedger.Ddate = row[0].ToString();
newGeneralLedger.etype = row[1].ToString();
newGeneralLedger.refrence = row[2].ToString();
newGeneralLedger.linkacc = row[3].ToString();
newGeneralLedger.Description = row[4].ToString();
newGeneralLedger.debit = decimal.Parse(row[5].ToString());
newGeneralLedger.credit = decimal.Parse(row[6].ToString());
newGeneralLedger.cumulative = decimal.Parse(row[7].ToString());
lstGeneralLedger.Add(newGeneralLedger);
}
dgvGeneralLedger.DataSource = dataset;
dgvGeneralLedger.Columns[0].Visible = false;
pdfCreator.AddGeneralLedgerPage(lstGeneralLedger, 1);
}
}
catch (Exception ex)
{
MessageBox.Show("Application Error. err:" + ex.ToString());
}
finally
{
conn.Close();
}
}
Why do you use a DataSet when you only need a single DataTable, this doesn't make any sense. Just use one DataTable:
DataTable dataTableSource = new DataTable();
adapter.Fill(dataTableSource);
// .. cotinue your code
dgvGeneralLedger.DataSource = dataTableSource;
Account Number issue:
You can use SqlParameter instead of hard-coding the value. Like this:
command.Parameters.AddWithValue("#acc", "8200030");
dataTableSource.Load(command.ExecuteReader())
// .. store results ..
// second account
command.Parameters["#acc"].Value = "8200031";
dataTableSource.Load(command.ExecuteReader())
// continue with the rest
But you need to change your query to be like this:
"... WHERE accnumber = #acc ...."

Date-picker using select statement oracle

I'm trying to implement date-picker functionality in my project, but I can't do it quite right. I'm trying to pass the date-picker value in my oracle string so that it will compare with my db column and return results on the date criteria...
Whenever I pass it to the select statement it won't generate errors particularly but on button click it doesn't perform anything except it shows "not connected".
str = "Select * from sania.doctor where APPOINTMENT_DATE = "+ datepicker1.value;
It is clear it is logical mistake but I'm new to this C# concepts I need someone to tell me how to pass it and then display the results as well.
private void button1_Click(object sender, EventArgs e)
try
{
OracleCommand com;
OracleDataAdapter oda;
string ConString = "Data Source=XE;User Id=system;Password=sania;";
OracleConnection con = new OracleConnection(ConString);
{
// string id = dateTimePicker1.Text.Trim();
con.Open();
// str = "Select * from sania.doctor where APPOINTMENT_DATE = " + dateTimePicker1.value;
str = "select * from sania.doctor where APPOINTMENT_DATE to_date('"+dateTimePicker1.Value.ToString("yyyyMMdd") + "', 'yyyymmdd')";
com = new OracleCommand(str);
oda = new OracleDataAdapter(com.CommandText, con);
dt = new DataTable();
oda.Fill(dt);
Rowcount = dt.Rows.Count;
//int val = 0;
for (int i = 0; i < Rowcount; i++)
{
dt.Rows[i]["APPOINTMENT_DATE"].ToString();
//if (id == dateTimePicker1.Value)// this LINE SHOWS ERROR--because it is a string and I am using date with it. Don't know conversion
// {
// val = 1;
//}
}
// if (val == 0)
// { MessageBox.Show("INVALID ID"); }
// else
// {
DataSet ds = new DataSet();
oda.Fill(ds);
if (ds.Tables.Count > 0)
{
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
else { MessageBox.Show("NO RECORDS FOUND"); }
}
}
//}
catch (Exception)
{ MessageBox.Show("not connected"); }
}
Do not put values into SQL directly, use bind variables/parametes instead. For Oracle:
// :prm_Appointment_Date bind variable declared within the query
String str =
#"select *
from sania.doctor
where Appointment_Date = :prm_Appointment_Date";
....
using(OracleCommand q = new OracleCommand(MyConnection)) {
q.CommandText = str;
// datepicker1.Value passed into :prm_Appointment_Date via parameter
q.Parameters.Add(":prm_Appointment_Date", datepicker1.Value);
...
}
Doing like that you can be safe from either SQL Injection or Format/Culture differences

Filling a DataTable in C# using MySQL

I'm attempting to fill a DataTable with results pulled from a MySQL database, however the DataTable, although it is initialised, doesn't populate. I wanted to use this DataTable to fill a ListView. Here's what I've got for the setting of the DataTable:
public DataTable SelectCharacters(string loginName)
{
this.Initialise();
string connection = "0.0.0.0";
string query = "SELECT * FROM characters WHERE _SteamName = '" + loginName + "'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query,connection);
DataTable dt = new DataTable("CharacterInfo");
returnVal.Fill(dt);
this.CloseConnection();
return dt;
}
else
{
this.CloseConnection();
DataTable dt = new DataTable("CharacterInfo");
return dt;
}
}
And for the filling of the ListView, I've got:
private void button1_Click(object sender, EventArgs e)
{
string searchCriteria = textBox1.Text;
dt = characterDatabase.SelectCharacters(searchCriteria);
MessageBox.Show(dt.ToString());
listView1.View = View.Details;
ListViewItem iItem;
foreach (DataRow row in dt.Rows)
{
iItem = new ListViewItem();
for (int i = 0; i < row.ItemArray.Length; i++)
{
if (i == 0)
iItem.Text = row.ItemArray[i].ToString();
else
iItem.SubItems.Add(row.ItemArray[i].ToString());
}
listView1.Items.Add(iItem);
}
}
Is there something I'm missing? The MessageBox was included so I could see if it has populated, to no luck.
Thanks for any help you can give.
Check your connection string and instead of using
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query,connection);
DataTable dt = new DataTable("CharacterInfo");
returnVal.Fill(dt);
this.CloseConnection();
return dt;
you can use this one
MySqlCommand cmd = new MySqlCommand(query, connection);
DataTable dt = new DataTable();
dt.load(cmd.ExecuteReader());
return dt;
Well, I ... can't figure out what you have done here so I'll paste you my code with which I'm filling datagridview:
1) Connection should look something like this(if localhost is your server, else, IP adress of server machine):
string connection = #"server=localhost;uid=root;password=*******;database=*******;port=3306;charset=utf8";
2) Query is ok(it will return you something), but you shouldn't build SQL statements like that.. use parameters instead. See SQL injection.
3) Code:
void SelectAllFrom(string query, DataGridView dgv)
{
_dataTable.Clear();
try
{
_conn = new MySqlConnection(connection);
_conn.Open();
_cmd = new MySqlCommand
{
Connection = _conn,
CommandText = query
};
_cmd.ExecuteNonQuery();
_da = new MySqlDataAdapter(_cmd);
_da.Fill(_dataTable);
_cb = new MySqlCommandBuilder(_da);
dgv.DataSource = _dataTable;
dgv.DataMember = _dataTable.TableName;
dgv.AutoResizeColumns();
_conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (_conn != null) _conn.Close();
}
}
So, every time I want to display some content of table in mysql database I call this method, pass query string and datagridview name to that method. and, that is it.
For your sake, compare this example with your and see what can you use from both of it. Maybe, listview is not the best thing for you, just saying ...
hope that this will help you a little bit.
Debug your application and see if your sql statement/ connection string is correct and returns some value, also verify if your application is not throwing any exception.
Your connection string is invalid.
Set it as follows:
connection = "Server=myServer;Database=myDataBase;Uid=myUser;Pwd=myPassword;";
Refer: mysql connection strings
Here the following why the codes would not work.
Connection
The connection of your mySQL is invalid
Query
I guess do you want to search in the table, try this query
string query = "SELECT * FROM characters WHERE _SteamName LIKE '" + loginName + "%'";
notice the LIKE and % this could help to list all the data. for more details String Comparison Functions

Categories

Resources