Insert data from mysql to cli listbox - mysql

listbox is emptyI want to take data from my sql and insert it into my listbox form but i can't. By compiling listbox is empty. What do i wrong?
private: System::Void listBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e)
{
String^ SQLconnection = "Server = localehost; Uid = root; Password = pass123; Database = details";
MySqlConnection^ conn = gcnew MySqlConnection(SQLconnection);
MySqlCommand^ cmd = gcnew MySqlCommand("SELECT * FROM details.material;", conn);
MySqlDataReader^ reader;
try
{
conn->Open();
reader = cmd->ExecuteReader();
while (reader->Read())
{
listBox1->Text +=(reader->GetInt32(0));
}
}catch (Exception^ ex)
{
MessageBox::Show(ex->Message);
}
}

Related

How do I close mysql connection after if-statement if it is true?

I'm new to ASP.NET and I'm stuck on this problem. I get the error:
Error:System.InvalidOperationException: The connection was not closed. The connection's current state is open. at System.Data.ProviderBase.DbConnectionInternal.
Here is my code, the error points towards 'while' statement. I've tried number of things but nothing worked. I know that I need to close connection when if-statement is true but don't know how. Can anyone help me on this? Thanks.
protected void loadtour()
{
try
{
conn.Open();
string strSelect = "Select * From Agents where Agent_ID='" + AgID.Text + "'";
SqlCommand cmd = new SqlCommand(strSelect, conn);
SqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
if (myReader["Agent_Status"].ToString() == "On Tour")
{
Label1.Text = "Assigned Tour Details:";
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT PackageInfo.pkg_Name, PackageInfo.pkg_Type, PackageInfo.pkg_Status, Packages.pkg_Country, Packages.pkg_Start, Packages.pkg_End, PackageInfo.Agent_ID, PackageInfo.Agent_Name FROM PackageInfo INNER JOIN Packages ON PackageInfo.pkg_ID = Packages.pkg_ID WHERE(PackageInfo.Agent_ID = '" + AgID.Text + "')", conn);
DataTable ds = new DataTable();
da.Fill(ds);
gv1.DataSource = ds;
gv1.DataBind();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
conn.Close();
}
else
{
Label1.Text = "No Tour Assigned Yet!";
}
myReader.Close();
conn.Close();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
//Do stuff with the connection
}
Wrap your connection in a using block. This guarantees it always gets closed.

Capture CheckBox list input- and assign to text area-

I am developing a web application using asp.net and MySQL. in my app, users can add recipes. It is a record that will be inserted. I have to input the ingredients in to the database as well. I am trying to capture the input ingredients ( which are in the form of checkboxes. ) Please review the GetIngredientsInput() method. I am checking which check boxes are checked, and saving the TEXT of the item checked. I want to capture the input in form of list. ( list of strings. ) I used StringBuilder for this, and assign it to a textarea control. But the code doesn't seem in effect. Thanks in advance.
protected void AddRecipe(object sender, EventArgs e)
{
GetIngredientsInput();
MySqlConnection con = new MySqlConnection("Server=localhost;Database=FreedomKitchen;Uid=root;Password=;");
con.Open();
String strcmd = "insert into Recipes(Recipe_ID,Food_Category,Meal_Category,Recipe_Name,All_Ingredients,Recipe_Description,Recipe_Instructions) values(#Recipe_ID,#Food_Category,#Meal_Category,#Recipe_Name,#All_Ingredients,#Recipe_Description,#Recipe_Instructions)";
MySqlCommand cmd = new MySqlCommand(strcmd, con);
MySqlCommand cmd_two = new MySqlCommand("select * from Recipes", con);
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd_two;
DataSet ds = new DataSet();
da.Fill(ds, "Rows");
int row_count = ds.Tables["Rows"].Rows.Count;
r_id = row_count + 1;
cmd.Parameters.Add(new MySqlParameter("#Recipe_ID", r_id));
cmd.Parameters.Add(new MySqlParameter("#Food_Category", DropDownFoodCat.Text.ToString()));
cmd.Parameters.Add(new MySqlParameter("#Meal_Category", DropDownMealCat.Text));
cmd.Parameters.Add(new MySqlParameter("#Recipe_Name", txtRecipeName.Text));
cmd.Parameters.Add(new MySqlParameter("#All_Ingredients", txtAllIngredients.Text));
cmd.Parameters.Add(new MySqlParameter("#Recipe_Description", txtDescription.Text));
cmd.Parameters.Add(new MySqlParameter("#Recipe_Instructions", txtInstructions.Text));
cmd.ExecuteNonQuery();
con.Close();
}
public void GetIngredientsInput() {
foreach (ListItem li in CheckBoxListVeg.Items) {
if (li.Selected) {
String ing_name=li.Text.ToString();
str_ing_name.Append(ing_name);
str_ing_name.Append("\n");
txtAllIngredients.Text = ing_name = li.Text.ToString();
}
}
}
Try this :-
public string GetIngredientsInput()
{
StringBuilder str_ing_name = new StringBuilder();
foreach (ListItem li in CheckBoxListVeg.Items)
{
if (li.Selected)
{
String ing_name = li.Text.ToString();
str_ing_name.Append(ing_name);
str_ing_name.Append(",");
}
}
return str_ing_name.ToString();
}
protected void AddRecipe(object sender, EventArgs e)
{
txtAllIngredients.Text= GetIngredientsInput();
// Rest of code
}

How to get list of reports

How to list all the reports, that I have created in the report server? Later I would like to use this list to display them in my ReportViewer control.
Report server uses stored procedure called FindObjectsNonRecursive.
string cnxstr = "Data Source=server;Initial Catalog=ReportServer;Integrated Security=SSPI;"; //connection string
using (SqlConnection connection = new SqlConnection(cnxstr))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "FindObjectsNonRecursive";
command.Parameters.Add(new SqlParameter("#Path", "/folder_name"));
command.Parameters.Add(new SqlParameter("#AuthType", 1));
SqlDataReader reader = null;
try
{
reader = command.ExecuteReader();
while (reader.Read())
{
string path = reader["Path"].ToString();
//now you can display this path in your list, or do whatever
}
}
finally
{
if (reader != null)
reader.Close();
}
}

The index outside of the range Exception

I'm trying to fill my list on Visual Studio side with help of stored procedure.
I'm using the following stored procedure:
CREATE PROCEDURE [dbo].[GetColletcion]
AS
BEGIN
select CollectionType.Name ,GlassesCollection.Name
from GlassesCollection
inner join CollectionType
on GlassesCollection.CollectionType=CollectionType.CollTypeID
END
Here's the code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
List<GlassesCollection> list = new List<GlassesCollection>();
using (SqlConnection conn = new SqlConnection("Server=(local);DataBase=ISeeOptic;Integrated Security=SSPI"))
{
GlassesCollection gln = new GlassesCollection();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetColletcion";
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
gln.Name = (string)reader["CollectionType.Name"];
gln.CollectionType = (string)reader["GlassesCollection.Name"];
list.Add(gln);
}
reader.Close();
conn.Close();
}
}
But when it comes to this row:
gln.Name = (string)reader["CollectionType.Name"];
I get this Exception:
Exception Details: System.IndexOutOfRangeException: CollectionType.Name
The index outside of the range, although in database more than one record.
How can I solve my problem?
It would be best to use column aliases and refer to the columns by those instead.
CREATE PROCEDURE [dbo].[GetColletcion]
AS
BEGIN
select CollectionType.Name As TypeName ,GlassesCollection.Name As GlassesName
from GlassesCollection
inner join CollectionType
on GlassesCollection.CollectionType=CollectionType.CollTypeID
END
Then use
(string)reader["TypeName"];
(string)reader["GlassesName"];
If you cannot change your stored procedure, then you can use the oridinal position:
(string)reader[0]; //CollectionType.Name
(string)reader[1]; //GlassesCollection.Name
I corrected your typo, too. (GetCollection)
CREATE PROCEDURE [dbo].[GetCollection]
AS
BEGIN
select CollectionType.Name AS CollectionType_Name, GlassesCollection.Name AS GlassesCollection_Name
from GlassesCollection
inner join CollectionType
on GlassesCollection.CollectionType=CollectionType.CollTypeID
END
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
List<GlassesCollection> list = new List<GlassesCollection>();
using (SqlConnection conn = new SqlConnection("Server=(local);DataBase=ISeeOptic;Integrated Security=SSPI"))
{
GlassesCollection gln = new GlassesCollection();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetCollection";
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
gln.Name = (string)reader["GlassesCollection_Name"];
gln.CollectionType = (string)reader["CollectionType_Name"];
list.Add(gln);
}
reader.Close();
conn.Close();
}
}

MySql Connector C# select query string=string

I have a query
SELECT * FROM db_tabel WHERE someStringField=\'#someStringValue\'
and i know that #someStringValue exists in tabel
but MySqlDataReader object told me than query returns nothing
where is mistake?
C# code:
const string command = "SELECT * FROM `db_tabel` WHERE `varcharvalue`=\'#varcharvalue\'";
var connection = new MySqlConnection(_connectionString);
try
{
connection.Open();
}
catch (Exception ex)
{
Log.Error(ex.ToString());
return null;
}
var cmd = new MySqlCommand(command, connection);
cmd.Parameters.AddWithValue("#varcharvalue",val );
MySqlDataReader reader;
try
{
reader = cmd.ExecuteReader();
}
catch (Exception ex)
{
connection.Close();
Log.Error(ex.ToString());
return null;
}
reader.Read();
if (reader.HasRows)
{
var cl = GetInstanse(reader);
reader.Close();
connection.Close();
return cl;
}
reader.Close();
connection.Close();
return null;