Using Drop-down with Check-boxes in Asp.net - c#

I have 2 drop-down boxes and i want the first drop-down to filter the 2nd one like cascading so the first one has check-boxes and i want to pass the selected items from the first one to the 2nd but getting a "syntax error". I run it into debug mode and the output result looks like this
CommandText "select id, name FROM myTable where id in (''CKU019','CW5036'') "
and it seems there is extra apostrophe near CKU019. Here is my code
protected void bindDDL()
{
string selectedValues = string.Empty;
foreach (ListItem item in ddchkCountry.Items)
{
if (item.Selected)
selectedValues += "'" + item.Value + "',";
}
if (selectedValues != string.Empty)
selectedValues = selectedValues.Remove(selectedValues.Length - 1);
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand cmd = new SqlCommand("select id, name FROM myTable where id in ('" + selectedValues + "')", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
facDDL.DataSource = ds;
facDDL.DataTextField = "name";
facDDL.DataValueField = "id";
facDDL.DataBind();
}

Remove the extra ' wrapping your selected values...
SqlCommand cmd = new SqlCommand("select id, name FROM myTable where id in (" + selectedValues + ")", con);

Related

Add referenced name instead of ID from comobox

I have 2 tables. First has column (categoryID) that is foreign key for categoryID in second table.Second table has 2 columns (categoryID, categoryName). After bit struggling I've displayed in combobox categoryName instead of categoryID. But now when I want to choose from existing categoryName that is already created (displayed in dropdown in combobox), is not possible because I have to type there int not string format. I'm beginner in programming
con.Open();
string cmddt = "insert into wallettbl(sum, date, categoryID, type)
values ('" + textBox1.Text + "','" + textBox2.Text + "','" +
comboBox1.Text + "', '" + type + "')";
SqlCommand com = new SqlCommand(cmddt, con);
com.ExecuteNonQuery();
How to write code if I want to add string (from combobox) instead of int, but in first table will be added categoryID which is referenced to categoryName.
EDIT: added code for combobox
con.Open();
string cmddt = "select categoryNAME from categoryTbl";
SqlCommand com = new SqlCommand(cmddt, con);
SqlDataAdapter da = new SqlDataAdapter(cmddt, con);
DataSet ds = new DataSet();
da.Fill(ds);
com.ExecuteNonQuery();
con.Close();
change the query to load the categories as below:
string cmddt = "select categoryID, categoryNAME from categoryTbl";
Set the datasource for comboBox1 as below:
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "categoryNAME";
comboBox1.ValueMember = "categoryID";
and finally modify the code to insert data into the wallettbl as follows:
string cmddt=
#"INSERT INTO WALLETTBL(sum, date, categoryID, type)
VALUES (#Sum, #Date, #CategoryId, #Type);";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(insertQuery, conn))
{
cmd.Parameters.Add("#Sum", SqlDbType.Int).Value = textBox1.Text;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = textBox2.Text;
cmd.Parameters.Add("#CategoryId", SqlDbType.Int).Value = Convert.ToInt32(comboBox1.SelectedValue);
cmd.Parameters.Add("#Type", SqlDbType.Varchar).Value = type;
await conn.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}

How to make insert operation using MySqlDataAdapter in ASP.NET

I am able to perform insert using the code which I've made comments here. How to achieve the same using MySqlDataAdapter ? The code I've written isn't working.
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
MySqlDataAdapter da = new MySqlDataAdapter("insert into tblStudent (StudentId, StudentName) values ('" + sid.ToString() + "', '" + sname.ToString() + "')", con);
// con.Open();
// MySqlCommand cmd = con.CreateCommand();
// cmd.CommandType = CommandType.Text;
// cmd.CommandText = "insert into tblStudent (StudentId, StudentName) values('" + sid.ToString() + "', '" + sname.ToString() + "')";
// cmd.ExecuteNonQuery();
// con.Close();
Help with suggestions.
To insert a single record you could simply use the MySqlCommand instead of a MySqlDataAdapter. MySqlDataAdapter has many functionality and allows you to execute Insert, Update and Delete actions on your data but you first need to reach the server to fill a DataTable, then add a new record to the datatable and finally call Update. Not worth the effort if you just need to insert a single record
However if you really want to try to use an DataAdapter then you need this code
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
string selectText = "SELECT studentID, StudentName FROM tblStudent WHERE 1=0";
using(MySqlDataAdapter da = new MySqlDataAdapter(selectText, con))
{
MySqlCommandBuilder bd = new MySqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
// This is important, because Update will work only on rows
// present in the DataTable whose RowState is Added, Modified or Deleted
dt.Rows.Add(sid, sname);
da.Update(dt);
}

Selected Item in combobox to datagrid C# SQL

We have a combo box with different music genres. We want the selected genre, in the combo box, to show the songs in the database, of that genre, and then display it in the datagrid.
public DataSet sortGenreCBox()
{
conn.Open();
SqlCommand genreBox = new SqlCommand("Select Distinct Genre From Sang", conn);
SqlDataAdapter adapt = new SqlDataAdapter(genreBox);
DataSet ds = new DataSet();
adapt.Fill(ds);
conn.Close();
return ds;
}
The code shows how we are extracting the genres from our database.
public ChooseSong()
{
InitializeComponent();
_DBF = new DatabaseFacade();
DataSet dsGenreBox = _DBF.sortGenreCBox();
DataTable dtGenreBox = dsGenreBox.Tables[0];
sortByGenreCBox.DataContext = dtGenreBox;
sortByGenreCBox.DisplayMemberPath = dtGenreBox.Columns[0].ToString();
...
}
Hope you can help :)
public DataSet sortGenreCBox()
{
conn.Open();
SqlCommand genreBox = new SqlCommand("Select Distinct" + sortByGenreCBox.SelectedItem + "from Sang", conn);
SqlDataAdapter adapt = new SqlDataAdapter(genreBox);
DataSet ds = new DataSet();
adapt.Fill(ds);
conn.Close();
return ds;
}
When we write it in, it says that it doesn't exist in the current content?
You can get the name of the gerne from the combo box and put that gerne in the SQL Query.
Create the query like:
SqlCommand genreBox = new SqlCommand("SELECT DISTINCT " + sortByGenreCBox.selectedItem + " FROM Sang", conn);
And set the datagridview.DataSource to the DataSet ds.
yourDataGridView.DataSource = ds.tables[0];
EDIT:
You can do something like:
public ChooseSong()
{
string selectedGerne = sortByGerneCBox.selectedItem.text;
DataSet ds = DatasortGenreCBox(selectedGerne);
Then you can do:
public DataSet sortGenreCBox(string selectedGenre){
SqlCommand genreBox = new SqlCommand("SELECT DISTINCT " + selectedGenre + " FROM Sang", conn);
}

SQL Row Updating Not Working in C#

I can't figure out why the following code is not updating either my GridView nor my MySQL Database. Can anyone offer me some tips as to what I may be doing incorrectly?
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
connection();
GridViewRow row = GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
TextBox textName = (TextBox)row.Cells[3].Controls[0];
TextBox textadd = (TextBox)row.Cells[4].Controls[0];
TextBox textc = (TextBox)row.Cells[5].Controls[0];
String query = "update employeeDB set [First Name:]='" + textName.Text + "', [Last Name:]='" + textadd.Text + "', [Email:]='" + textc.Text + "' where id='" + lblID + 1 + "'";
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr;
dr = com.ExecuteReader();
GridView1.EditIndex = -1;
bind();
}
Here is my bind method as requested:
private void bind()
{
connection();
string query = "select * from employeeDB where [Last Name:] like'" + TextBox1.Text + "%'";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Replace
dr = com.ExecuteReader();
with
com.ExecuteNonQuery();
ExecuteReader is for SELECT queries.
Also, in real world application you should not build sql string like you do. Use SqlParameter instead to avoid sql injection and many other errors.
GridViewRow row = GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
TextBox textName = (TextBox)row.Cells[3].Controls[0];
TextBox textadd = (TextBox)row.Cells[4].Controls[0];
TextBox textc = (TextBox)row.Cells[5].Controls[0];
/*are you sure column names are like [First Name:],[Last Name:] and [Email:] in the table*/
/*Syntax for update command should be like this "UPDATE TableName SET ColumnName1=#Parameter1, ColumnName2=#Parameter2 ....
* WHERE ColumnName=#ParameterName"
*/
String query = "update employeeDB set [First Name:]=#FirstName, [Last Name:]=#LastName, [Email:]=#Email where id=#id";
SqlCommand com = new SqlCommand(query, con);
com.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = textName.Text;
com.Parameters.Add("#LastName", SqlDbType.VarChar).Value = textadd.Text;
com.Parameters.Add("#Email", SqlDbType.VarChar).Value = textc.Text;
com.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32(lblID.Text) + 1;
con.Open();
com.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
bind();
}
you should be doing something like this
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["TaskTable"];
//Update the values.
GridViewRow row = TaskGridView.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Id"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Description"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["IsComplete"] = ((CheckBox)(row.Cells[3].Controls[0])).Checked;
//Reset the edit index.
TaskGridView.EditIndex = -1;
//Bind data to the GridView control.
BindData();
What are you getting now? Exception or just no error and nothing is happening? Things to check are db connection string-make sure your connection string is pointing to the db you are targeting. And second i would like to point out that the query is open for sql injection attack (something you need to consider - if you are going to use it to production code).Third, what do you have in the bind method? What data source its trying to bind and with what control? From the sample code itself, it looks like no data is being returned from db.
Updated with:
And by the way, should the colon be there in your query? See for instance the colon after first name ([First Name:] ) String query = "update employeeDB set [First Name:]='" + textName.Text + "', [Last Name:]='" + textadd.Text + "', [Email:]='" + textc.Text + "' where id='" + lblID + 1 + "'";

How to display two different columns in one combobox

I want to display the two different columns in one particular combobox. When I run it the Customer ID will display. Here is my code.
void GetRecords2()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname
+ ',' + lastname FROM Customer";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Customer");
cboName.DataSource = ds;
cboName.DisplayMember = "Customer.firstname, Customer.lastname";
cboName.ValueMember = "Customer.CustomerID";
}
I see you already are creating a single result column containing the "combined" value. That's have the battle.
But, you need to give your column a name (notice the AS FullName alias):
cmd.CommandText = "SELECT CustomerID, firstname + ',' + lastname AS FullName " +
"FROM Customer";
So you can reference it later by name:
cboName.DisplayMember = "FullName";
This will work. I find that binding a Dictionary to a ComboBox has much more predictable results.
My approach omits the extra SQL syntax, DataSet, and SqlDataAdapter.
Instead I use the SqlDataReader to place the desired information into a Dictionary and then I bind that Dictionary as the DataSource of the Combobox.
void GetRecords2()
{
Dictionary <int, string> myDict = new Dictionary<int, string>();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname, lastname FROM Customer";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
myDict.Add(Convert.ToInt32(reader["CustomerID"]),
reader["firstname"].ToString() + " " + reader["lastname"].ToString());
}
if (myDict.Count > 0)
{
cboName.DataSource = new BindingSource(myDict, null);
cboName.DisplayMember = "Value";
cboName.ValueMember = "Key";
}
}
Check this:
void GetRecords2()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname
+ ',' + lastname FullName FROM Customer";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Customer");
cboName.DataSource = ds;
cboName.DisplayMember = "FullName";
cboName.ValueMember = "CustomerID";
}
To get selected value :
string customerid = cboName.SelectedValue.toString(); //CustomerID: 1
To get selected item
string fullname = cboName.SelectedItem.Text; //FullName : John Hawkins
Best Regards

Categories

Resources