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();
}
}
Related
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();
I have a combox box that i fill with the data my database , i call the FillCombos function in the constructor of the form.
//Variables of class
DataSet ds = new DataSet();
DataTools mytool = new DataTools();
private void FillCombos()
{
string cmd = "";
//Llena cmb Categoria
ds.Clear();
cmd = "select descripcion from Categoria";
ds = mytool.Execute(cmd);
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
this.cmbCategoria.Items.AddRange(new object[]
{
ds.Tables[0].Rows[i]["descripcion"].ToString()});
}
ds.Clear();
}
Then when the user select a category i want to display the subcategories. So i have this
method.
private void cmbCategoria_SelectedIndexChanged(object sender, EventArgs e)
{
//ds.Clear();
string cmd = "select Categoria.cod_cat from Categoria where Categoria.descripcion = '" + cmbCategoria.Text + "'";
ds = mytool.Execute(cmd);
//Keeps telling me that is out of range here is the problem
MessageBox.Show(ds.Tables[0].Rows[0][0].ToString());
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
MessageBox.Show(cmd);
MessageBox.Show(ds.Tables[0].Rows[0][0].ToString());
}
// codCat = Convert.ToInt32(ds.Tables[0].Rows[0]["cod_cat"].ToString());
ds.Clear();
cmd = "select descripcion from SubCategoria where cod_cat = " + codCat.ToString();
ds = mytool.Execute(cmd);
this.cmbSubCategoria.Items.Clear();
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
this.cmbSubCategoria.Items.AddRange(new object[]
{
ds.Tables[0].Rows[i]["descripcion"].ToString()});
}
ds.Clear();
}
My problem is that visual studio tells me that the dataset it out of range, but i try
the sentence in sql and it returns one id with one row and one column, so why the message that the index is out of range, why the sql statement is not executed correctly.
I have the same code in a adress form and it runs correctly.
I try changing the dataset, another datool class with another dataset, putting a static sql query but nothing seems to work.
The SELECT statement is very probably returning no results as cmbCategoria.Text is not containing the expected value. Please stop your pgm before executing the SELECT statement and have a look to the content of cmbCategoria.Text
Update: Try instead
string cmd =
"select Categoria.cod_cat from Categoria where Categoria.descripcion = '"
+ cmbCategoria.SelectedItem.ToString()
+ "'";
More info here: Combobox.Text Vs combobox.Selecteditem Vs combobox.selectValue?
i am doing a search from database. user will enter string. this string will be converted into array then this array indexed values will be checked from table to find the match.
I am using loop to traverse array query execution is in that loop, it searches fine but if there was more than one index to search it shows the last index searched values.
i know know that's not a proper way to search.
how can i do this.
SqlConnection conOpen;
string[] arrayList;
protected void Page_Load(object sender, EventArgs e)
{
DataLayer datalayer = new DataLayer();
conOpen = datalayer.connectionOpen();
string myString = Request.QueryString["searchText"].ToString();
char[] separator = new char[] { ' ' };
arrayList = myString.Split(separator);
for (int i = 0; i <= arrayList.GetUpperBound(0); i++)
{
Response.Write(arrayList[i]);
string asd = arrayList[i];
String arrayQuery = "Select * from tbl_products where product_name LIKE '%" + #asd + "%'";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(arrayQuery, conOpen);
da.Fill(ds, "tbl_products");
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
I'm too clear on what your final result is supposed to be but I'm going to guess. I think what you are asking is that you want the query to search for every instance of the search items (seperated by a space) the users put in the input element and return ALL of these findings to your GridView. Ok. So I would suggest you loop to "build" your sql statement and then run the sql and bind the data AFTER the loop (not during).
One more important element is that you should most definitely parametrize these values since it's coming from user input in order to prevent SQL-Injection. Please forgive any typos (it is late).
DataLayer datalayer = new DataLayer();
conOpen = datalayer.connectionOpen();
string myString = Request.QueryString["searchText"].ToString();
char[] separator = new char[] { ' ' };
arrayList = myString.Split(separator);
StringBuilder arrayQuery = new StringBuilder();
SqlCommand myCommand = new SqlCommand();
for (int i = 0; i < arrayList.Length; i++)
{
if (i==0)
{
arrayQuery.Append("Select * from tbl_products where product_name LIKE #asd" + i);
} else{
arrayQuery.Append(" OR product_name LIKE #asd" + i );
}
myCommand.Parameters.AddWithValue("#asd" + i, "%" + arrayList[i] + "%");
}
myCommand.CommandText = arrayQuery.ToString();
myCommand.Connection = conOpen;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(myCommand);
da.Fill(ds, "tbl_products");
GridView1.DataSource = ds;
GridView1.DataBind();
i m making add,edit delete module...For that i have the following code in the c#,
private void listOfCompany_Load(object sender, EventArgs e)
{
//MessageBox.Show(updID.ToString());
con.ConnectionString = #"PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany_1.mdb";
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
string sql = "SELECT * From tblCompany_1 WHERE ID="+updID;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
da.Fill(ds);
// dataGridView1.DataSource = ds.Tables[0];
DataRow dr = ds.Tables[0].Rows.Count;
textBox1.Text = dr.ItemArray.GetValue(0).ToString();
textBox4.Text = dr.ItemArray.GetValue(2).ToString();
/* int t = ds.Tables[0].Columns.Count;
for (int i = 0; i < cnt; i++)
{
dataGridView1.Rows[i].Cells[0].Value = dr.ItemArray.GetValue(0).ToString();
dataGridView1.Rows[i].Cells[1].Value = dr.ItemArray.GetValue(1).ToString();
dataGridView1.Rows[i].Cells[2].Value = dr.ItemArray.GetValue(2).ToString();
}*/
}
when i debug the application, then on add,edit and delete button, it gives me error at the "DataRow dr = ds.Tables[0].Rows[0];" that "IndexOutOf RangeException was handled" and the error is "There is no row at position 0."...How should i overcome from this?
Well that suggests there's no record with that ID. You should check for that before going ahead and trying to use it. You can use ds.Tables[0].Rows.Count to find out how many rows were returned.
You should also start using parameterized queries instead of including values directly within the SQL statement you're building, in order to avoid SQL injection attacks. If the ID is an integer then it probably isn't a problem here, but generally parameterized SQL queries are the way forward.
How about:
DataRow dr;
for(int i = 0; i<ds.Tables.Count; i++){
for(int j = 0; j<ds.Tables[i].Rows.Count; j++){
dr = ds.Tables[i].Rows[j];
//Do something with dr.
}
}
Note: It is possibly "Length" in stead of "Count". Can't remember right now:p
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;
}