Capture CheckBox list input- and assign to text area- - mysql

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
}

Related

How to add "li" to "ul" tag with C#

i am trying to get some names from Sql database and append them as "li" in to pre-created "ul" with the code below. i am getting "System.Data.Common.DataRecordInternal" instead my datas in Sql what could be the problem?
also with this code i cannot take first item in SQL. i mean totaly i have 9 item in Sql however i get only 8 "System.Data.Common.DataRecordInternal".
the code:
HTML
<div class="modal-body" style="width: 1000px;">
<ul class="list-group" runat="server" id="A3List">
</ul>
</div>
C#
protected void loadEval_ServerClick(object sender, EventArgs e)
{
SqlCommand comd = new SqlCommand("select name from A3_Coaching", con.connection());
SqlDataReader dr = comd.ExecuteReader();
while (dr.Read())
{
foreach (var r in dr)
{
HtmlGenericControl li = new HtmlGenericControl("li");
A3List.Controls.Add(li);
li.InnerHtml = r.ToString();
}
}
}
You need to read the actual column name from the data reader not just do a .ToString which will print out the underlying type's name. You don't need the extra foreach also, the while on the DataReader is your loop. Try the below.
protected void loadEval_ServerClick(object sender, EventArgs e)
{
SqlCommand comd = new SqlCommand("select name from A3_Coaching", con.connection());
SqlDataReader dr = comd.ExecuteReader();
while (dr.Read())
{
HtmlGenericControl li = new HtmlGenericControl("li");
A3List.Controls.Add(li);
li.InnerHtml = dr["name"];
}
}

Getting Connection Error Connection Must Be Valid and Open

This is my Data access layer but i don't know why i am getting connection error when multi user using and when more than 1 user access the website i checked all thing but cant fix it i am posting my code. this is updated code. it again stuck and result same as last code. i dnt know why it happened when more than 1 user try to access it login but then its not working more after 1 to 2 mints
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
public class clsMySqlConnection
{
public MySqlConnection con = null;
protected MySqlConnection getConnection()
{
if (con == null || con.State != ConnectionState.Open)
{
con = new MySqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
con.Open();
}
return (con);
}
}
public class clsManagement : clsMySqlConnection
{
public DataTable getData(string MySql)
{
MySqlCommand cmd = new MySqlCommand();
MySqlDataAdapter da = new MySqlDataAdapter();
DataTable dt = new DataTable();
cmd.CommandText = MySql;
cmd.Connection = getConnection();
da.SelectCommand = cmd;
da.Fill(dt);
return (dt);
}
public MySqlDataReader ExecuteActionQuery(string MySql)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = MySql;
try
{
cmd.Connection = getConnection();
cmd.ExecuteNonQuery();
MySqlDataReader rdr = cmd.ExecuteReader();
return (rdr);
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
}
public int ExecuteDML(string MySql)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = MySql;
try
{
cmd.Connection = getConnection();
return cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
}
}
You can just create a new connection and return from getConnection() function.
protected MySqlConnection getConnection()
{
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
con.Open();
}
And use con variable in local scope.

Create panel for each row in database and style column elements differently

I'm creating a website that'll contain a news section. The news will be uploaded to a database from which i will present the data to the users. The news table consists of the columns ID, Title, Data and Date.
Currently I've succeeded up to the point of showing the data in the columns Title and Data as they are the ones I'm interested in showing. But each row are to be presented by themselves as a header and information where the header has its own css style and the information another. And then i want the next row to show up next to it. With this code it just put the titles in one panel and the corresponding information in another. I want them to be their own panels with their own styles.
This is my code this far in Index.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
string constring = "----------------------";
SqlConnection con = new SqlConnection(constring);
SqlCommand query = new SqlCommand("SELECT * FROM News;", con);
con.Open();
SqlDataReader reader = query.ExecuteReader();
int i = 1;
while (reader.HasRows)
{
while (reader.Read())
{
Label lblTitle = new Label();
lblTitle.ID = "title" + i;
lblTitle.Text = reader.GetString(1);
Label lblData = new Label();
lblData.ID = "data" + i;
lblData.Text = reader.GetString(2);
panelTitle.Controls.Add(lblTitle);
panelTitle.Controls.Add(new LiteralControl("<br/>"));
panelData.Controls.Add(lblData);
panelData.Controls.Add(new LiteralControl("<br/>"));
i++;
}
reader.NextResult();
}
reader.Close();
con.Close();
}
also this piece of code in Index.aspx:
<div id="nTextHeader">
<asp:Panel ID="panelTitle" runat="server"></asp:Panel>
<div id="nTextCont">
<asp:Panel ID="panelData" runat="server"></asp:Panel>
</div>
</div>
As I said this just puts the data in two different panels which makes it easy to style them correctly. But it also puts all the data in the same place, which is wrong.
Thanks.
I would consider stop using windows UI controllers such as panels and stuff, and start using manual output options via Response.Write( <html data here> ); unless you're making forms, then a MVC structure might come in handy.
Here's something along the lines you need in index.aspx:
<div id="nTextHeader">
<asp:Panel ID="newsPanel" runat="server">
</asp:Panel>
</div>
And for your .NET code:
protected void Page_Load(object sender, EventArgs e)
{
string constring = "----------------------";
SqlConnection con = new SqlConnection(constring);
SqlCommand query = new SqlCommand("SELECT * FROM News;", con);
con.Open();
SqlDataReader reader = query.ExecuteReader();
int i = 1;
while (reader.HasRows)
{
while (reader.Read())
{
Panel pan = new Panel();
Label lblTitle = new Label();
lblTitle.ID = "title" + i;
lblTitle.Text = reader.GetString(1);
pan.Controls.add(lblTitle);
Label lblData = new Label();
lblData.ID = "data" + i;
lblData.Text = reader.GetString(2);
pan.Controls.add(lblData);
newsPanel.Controls.add(pan);
i++;
}
reader.NextResult();
}
reader.Close();
con.Close();
}
Using static HTML elements (a "better" solution)
A "better" solution would be to simply use static HTML objects (much as you tried to do with LiteralControl), since you don't really need any of the windows UI calls (unless you want to create custom MVC modules to list it to your liking) you're better off just outputting static HTML elements:
protected void Page_Load(object sender, EventArgs e)
{
string constring = "----------------------";
SqlConnection con = new SqlConnection(constring);
SqlCommand query = new SqlCommand("SELECT * FROM News;", con);
con.Open();
SqlDataReader reader = query.ExecuteReader();
int i = 1;
while (reader.HasRows)
{
while (reader.Read())
{
string newsArticle = "";
newsArticle += "<div class='newsBlock'>";
newsArticle += " <div class='newsTitle'>" + reader.GetString(1) + "</div>";
newsArticle += " <div class='newsData'>" + reader.GetString(2) + "</div>";
newsArticle += "</div>"
newsPanel.Controls.add(new LiteralControl(newsArticle));
i++;
}
reader.NextResult();
}
reader.Close();
con.Close();
}
You still need to modify your index.aspx to the above tho since the code relies heavily on the object newsPanel to be present for populating it with data.

How to refresh datagrid after using a filter to search

I tried some code but nothing.
Me.DataGridView1.Refresh()
Why?
My datagridview is automatically connected to database,not manualy using commands to make connection.
Try the below code... i think you except the code like below....
//Text box Change Event
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text != "")
GetData("select * from Sample where num =" + textBox1.Text);
else
GetData("select * from Sample");
}
//Data Bind Event by using BindingSource
private void GetData(string selectCommand)
{
try
{
String connectionString ="Your Connection String";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(selectCommand, connectionString);
OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
//BindingSource - Binding
sampleBindingSource.DataSource= table;
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCells );
}
catch (SqlException)
{
MessageBox.Show("Error Occured");
}
}

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();
}
}