I can not get all the data - c#

I'm read the rows and using it is run sql query. Loop was correct but only one line is being processed. Please support me.
for (int i = 0; i < Excel_read.Rows.Count - 1; i++)
{
string readRow = Excel_read.Rows[i].Cells[0].Value.ToString();
//MessageBox.Show(xaxa);
//MessageBox.Show(readRow);
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT `Calling number`,`Call time` FROM test.tbltest WHERE `Calling number` = " + readRow + " GROUP BY `Calling number`", connection);
System.Data.DataTable test = new System.Data.DataTable();
adp.Fill(test);
Excel_read.DataSource = test;
adp.Dispose();
}
connection.Close();

Related

Can i get multiple data type records from sql to arraylist and get it in another form

I'd like to get any of my tables record in arraylist and get it in another form (no matter how much columns for loop will retrieve data in to arraylist)
Here my code:
public static ArrayList getrecord(String Table, String Column, Int32 id)
{
ArrayList asd = new ArrayList();
Form1.con.Close();
Form1.con.Open();
SqlCommand sq = new SqlCommand("Select * from " + Table + " where " + Column + " = " + id, Form1.con);
SqlDataReader sdr = sq.ExecuteReader();
if (sdr != null)
{
while (sdr.Read())
{
for(int i =0; i < sdr.FieldCount; i++)
{
asd.Add(sdr.GetValue(i).ToString());
}
}
}
return asd;
}
I suggest using DataTable instead of ArrayList. You can fill DataTable with all the records you need and use it in another form.
System.Data.SqlClient.SqlCommand sq = new System.Data.SqlClient.SqlCommand("your sql query", "your connection string");
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter(sq);
sda.Fill(dt);

Access value in OleDbDataApter

Using OleDbDataAdapter SQL query to search for secific entry in access database.
OleDbDataAdapter adapter1 = new OleDbDataAdapter(#"SELECT Gallery_Number FROM Paintings WHERE Painting Number = '" + searchString + "'", myDB);
searchString = Convert.ToString( adapter);
searchString returns System.Data.OleDb.OleDbDataAdapter and not a Gallery number.
I would like to know how to get the value of this adapter and put it into a textbox.
First of all, I'd use a Scalar for this, since you only return a single value.
OleDbCommand command = new OleDbCommand(queryString, connection);
command.Connection.Open();
int galeryNumber = (int)command.ExecuteScalar();
But let's take a look at your code:
DataSet galNum = new DataSet();
oledbAdapter.Fill(galNum);
int galeryNumber = int.Parse(ds.Tables[0].Rows[0].ItemArray[0].ToString());
The best way to gain access to a OleDbDataAdapter is by converting the result set into a `DataSet. Then you can iterate through this set.
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
DataRow dr = ds.Tables[0].Rows[i]; //One result line in your set
//DataRow contains n columns
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
string someEntry = dr[i].ToString();
}
}

Updating data in listbox from datatable

I want to show data from data table on form_load using list box, and later update that data from list box on button click by Insert command. Function for that is fill_List(). This is my code:
OleDbConnection konekcija;
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
public Form2()
{
InitializeComponent();
string putanja = Environment.CurrentDirectory;
string[] putanjaBaze = putanja.Split(new string[] { "bin" }, StringSplitOptions.None);
AppDomain.CurrentDomain.SetData("DataDirectory", putanjaBaze[0]);
konekcija = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=|DataDirectory|\B31Autoplac.accdb");
}
void fill_List()
{
konekcija.Open();
OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija);
adapter.SelectCommand = komPrikaz;
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
konekcija.Close();
}
private void Form2_Load(object sender, EventArgs e)
{
fill_List();
}
private void btnUpisi_Click(object sender, EventArgs e)
{
string s1, s2, s3;
s1 = tbSifra.Text;
s2 = tbNaziv.Text;
s3 = tbOpis.Text;
string Upisi = "INSERT INTO GORIVO (GorivoID, Naziv, Opis) VALUES (#GorivoID, #Naziv, #Opis)";
OleDbCommand komUpisi = new OleDbCommand(Upisi, konekcija);
komUpisi.Parameters.AddWithValue("#GorivoID", s1);
komUpisi.Parameters.AddWithValue("#Naziv", s2);
komUpisi.Parameters.AddWithValue("#Opis", s3);
string Provera = "SELECT COUNT (*) FROM GORIVO WHERE GorivoID=#GorivoID";
OleDbCommand komProvera = new OleDbCommand(Provera, konekcija);
komProvera.Parameters.AddWithValue("#GorivoID", s1);
try
{
konekcija.Open();
int br = (int)komProvera.ExecuteScalar();
if(br==0)
{
komUpisi.ExecuteNonQuery();
MessageBox.Show("Podaci su uspesno upisani u tabelu i bazu.", "Obavestenje");
tbSifra.Text = tbNaziv.Text = tbOpis.Text = "";
}
else
{
MessageBox.Show("U bazi postoji podatak sa ID = " + tbSifra.Text + ".", "Obavestenje");
}
}
catch (Exception ex1)
{
MessageBox.Show("Greska prilikom upisa podataka. " + ex1.ToString(), "Obavestenje");
}
finally
{
konekcija.Close();
fill_List();
}
}
Instead of this
It shows me this (added duplicates with new data)
Is there a problem in my function or somewhere else?
Another bug caused by global variables.
You are keeping a global variable for the DataTable filled by the fill_list method. This datatable is never reset to empty when you call fill_list, so at every call you add another set of rows to the datatable and then transfer this data inside the listbox. Use a local variable.
But the same rule should be applied also to the OleDbConnection and OleDbCommand. There is no need to keep global instances of them. Creating an object is really fast and the convenience to avoid global variables is better than the little nuisance to create an instance of the connection or the command.
void fill_List()
{
using(OleDbConnection konekcija = new OleDbConnection(......))
using(OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija))
{
DataTable dt = new DataTable();
konekcija.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(komPrikaz);
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
}
}
Clear your DataTable before filling it again.
void fill_List()
{
konekcija.Open();
OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija);
adapter.SelectCommand = komPrikaz;
dt.Clear(); // clear here
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
konekcija.Close();
}

No value given for one or more required parameters with OleDBDataAdapter

Hey all I realise that this question has been asked before but even if I follow the answers I still cannot seem to get my code to work. The error occurs at "data_adapter.Fill(temp_table)" any help on what is going on would be appreciated.
string ConnStr = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = H:\\School Work\\Computing A Level\\Stock checker\\Program\\Morgan's Motors Database.mdb";
string Query = "SELECT * FROM [Car Info] WHERE #x ";
string FirstQuery = null;
int i = 0;
for (i = 0; i < ColumnName.Count - 1; i++)
{
FirstQuery += string.Format("{0} = {1} AND ", ColumnName[i], EnteredFields[i]);
}
FirstQuery += string.Format("{0} = {1}", ColumnName[i], EnteredFields[i]);
MessageBox.Show(Query);
OleDbConnection database_connection = new OleDbConnection(ConnStr);
OleDbCommand database_command = new OleDbCommand(Query, database_connection);
database_command.Parameters.AddWithValue("#x", FirstQuery);
OleDbDataAdapter database_adapter = new OleDbDataAdapter();
database_adapter.SelectCommand = new OleDbCommand(database_command.CommandText, database_connection);
DataTable temp_table = new DataTable();
database_adapter.Fill(temp_table);
BindingSource data_source = new BindingSource();
data_source.DataSource = temp_table;
dataGridView1.DataSource = data_source;
EDIT: I have made some progress in restructuring the code, now the problem is that the "?" isn't being replaced
string ConnStr = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = H:\School Work\Computing A Level\Stock checker\Program\Morgan's Motors Database.mdb;";
OleDbConnection conn_database = new OleDbConnection();
conn_database.ConnectionString = ConnStr;
OleDbCommand comm_database = new OleDbCommand();
comm_database.CommandText = "SELECT * FROM [Car Info] WHERE ? = ?";
comm_database.Connection = conn_database;
OleDbDataAdapter adap_database = new OleDbDataAdapter(comm_database);
DataTable data_database = new DataTable();
for (int i = 0; i < ColumnName.Count; i++)
{
comm_database.Parameters.AddWithValue("?", ColumnName[i].ToString());
comm_database.Parameters.AddWithValue("?", EnteredFields[i].ToString());
MessageBox.Show(adap_database.SelectCommand.CommandText);
adap_database.Fill(data_database);
}
BindingSource bind_database = new BindingSource();
bind_database.DataSource = data_database;
dataGridView1.DataSource = bind_database;
Did you try :
database_command.Parameters.AddWithValue("#x", EnteredFields[i]);
instead of :
database_command.Parameters.AddWithValue("#x", FirstQuery);
Usually when working with parameter you can just add the param name and its value and not have to add the columnName = to the value. Make sense?
One thing that you could try if wanted to leverage using parameters is code below. I don't know if it will solve your problem or not but at least it help protect you from SQL Injection attacks. Please let me know if you have any questions.
string Query = "SELECT * FROM [Car Info] WHERE {0} ";
for (i = 0; i < ColumnName.Count - 1; i++)
{
FirstQuery += string.Format("{0} = #{1} AND ", ColumnName[i], ColumnName[i]);
}
FirstQuery += string.Format("{0} = #{1}", ColumnName[i], ColumnName[i]);
Query = String.Format(Query, FirstQuery);
for (i = 0; i < ColumnName.Count - 1; i++)
{
database_command.Parameters.AddWithValue("#" + ColumnName[i], EnteredFields[i]);
}

Dropdownlist and Datareader

After trying many solutions listed on the internet I am very confused now. I have a C#/SQL web application for which I am simply trying to bind an ExecuteReader command to a Dropdownlist so the user can select a value. This is a VS2008 project on an XP OS.
How it works is after the user selects a table, I use this selection as an input parameter to a method from my Datamatch.aspx.cs file. Then this Datamatch.aspx.cs file calls a method from my ADONET.cs class file. Finally this method executes a SQL procedure to return the list of columns from that table. (These are all tables in Adventureworks DB). I know that this method returns successfully the list of columns if I execute this SP in SSMS. However, I'm not sure how to tell if it works in VS or not.
This should be simple. How can I do this? Here is some of my code. The T-sQL stored proc:
CREATE PROCEDURE [dbo].[getColumnNames]
#TableName VarChar(50) AS
BEGIN
SET NOCOUNT ON;
SELECT col.name 'COLUMN_NAME' FROM sysobjects obj
INNER JOIN syscolumns col ON obj.id = col.id
WHERE obj.name = #TableName
END
It gives me desired output when I execute following from SSMS: exec getColumnNames 'AddressType'
And the code from Datamatch.aspx.cs file currently is:
private void CreateDropDownLists()
{
SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable);
int NumControls = targettable.Length;
DropDownList ddl = new DropDownList();
DataTable dt = new DataTable();
dt.Load(dr2);
ddl.DataValueField = "id";
ddl.DataTextField = "text";
ddl.DataSource = dt;
ddl.DataBind();
for (int counter = 0; counter < NumberOfControls; counter++)
{
ddl.ID = "DropDownListID " + (counter + 1).ToString();
btnSubmit.Style.Add("top", "auto");
btnSubmit.Style.Add("left", "auto");
btnSubmit.Style.Add("position", "absolute");
if (counter < 7)
{
ddl.Style["top"] = 100 * counter + 80 + "px";
ddl.Style["left"] = 250 + "px";
int bSubmitPosition = NumberOfControls * 100 + 80;
btnSubmit.Style.Add("top", System.Convert.ToString(bSubmitPosition) + "px");
}
else if (counter >= 7)
{
ddl.Style["top"] = 100 * counter - 620 + "px";
ddl.Style["left"] = 550 + "px";
int bSubmitPosition = NumberOfControls * 100 - 620;
btnSubmit.Style.Add("top", System.Convert.ToString(bSubmitPosition) + "px");
}
ddl.SelectedIndexChanged += new EventHandler(SelectedIndexChanged);
ddl_ht.Add(counter, ddl.SelectedValue);
pnlDisplayData.Controls.Add(ddl);
pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>"));
pnlDisplayData.Visible = true;
pnlDisplayData.FindControl(ddl.ID);
// dr.Close();
}
}
private void CreateLabels()
{
for (int counter = 0; counter < NumberOfControls; counter++)
{
Label lbl = new Label();
lbl.ID = "Label" + counter.ToString();
lbl.Text = headers[counter];
lbl.Style["position"] = "absolute";
if (counter < 7)
{
lbl.Style["top"] = 100 * counter + 50 + "px";
lbl.Style["left"] = 250 + "px";
}
else if (counter >= 7)
{
lbl.Style["top"] = (100 * counter) - 650 + "px";
lbl.Style["left"] = 550 + "px";
}
pnlDisplayData.Controls.Add(lbl);
pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>"));
}
}
Where ADONET_methods.DisplayTableColumns(targettable) is:
public static SqlDataReader DisplayTableColumns(string tt)
{
SqlDataReader dr = null;
string TableName = tt;
string connString = "Server=(local);Database=AdventureWorks;Integrated Security = SSPI";
string errorMsg;
SqlConnection conn2 = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("getColumnNames"); //conn2.CreateCommand();
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn2;
SqlParameter parm = new SqlParameter("#TableName", SqlDbType.VarChar);
parm.Value = "Person." + TableName.Trim();
parm.Direction = ParameterDirection.Input;
cmd.Parameters.Add(parm);
conn2.Open();
dr = cmd.ExecuteReader();
}
catch (Exception ex)
{
errorMsg = ex.Message;
}
return dr;
}
The CreateLabels method above correctly shows me the labels. But the CreateDropDownLists method just shows me one dropdownlist with nothing in it. In other words, it is not selectable.
So how can I verify that the datareader is returning all 4 columns and inspect their values? I was able to find from datareader "COLUMN_NAME" but I don't know what properties to search to verify the column names.
It doesn't look like you're actually binding the dropdown anywhere in this code. You need to do something like this:
ddl.DataTextField = "COLUMN_NAME";
ddl.DataValueField = "COLUMN_NAME";
ddl.DataSource = dr.ExecuteReader();
ddl.DataBind();
Alternately, you can do this all in your page markup by using a SqlDataSource control.
<asp:SqlDataSource
id="SqlDataSource1"
runat="server"
DataSourceMode="DataSet"
ConnectionString="myConnString"
SelectCommand="myStoredProcedure"
>
</asp:SqlDataSource>
<asp:MyDropDownList id="ddl" runat="server" DataSource="SqlDataSource1"
DataTextField="COLUMN_NAME" DataValueField="COLUMN_NAME" />
In the ADONET_methods.DisplayTableColumns(targettable) method before returning dr, check if you get some value for dr.GetValue() using a breakpoint
string temp;
while(dr.Read())
{
temp = dr.GetValue(); //use a breakpoint here
}
Also instead of using dataReader and loading it to dataTable, you can better use a dataAdapter to fill the dataTable directly
public static DataTable DisplayTableColumns(string tt)
{
Datatable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
try
{
da.Fill(dt);
}
catch (Exception ex)
{
errorMsg = ex.Message;
}
string temp;
foreach(DataRow row in dt.Rows)
{
foreach(DataColumn column in dt.Columns)
{
temp = (row[column]); // use your breakpoint here
}
}
return dt;
}

Categories