How to output results using OR in searching value database? - c#

I want to output the lastname or firstname using search but only lastname is only displaying when i search firstname it does not show values... I tried using OR but it doesn't work
private void search_Click(object sender, EventArgs e)
{
try
{
MySqlDataAdapter ada = new MySqlDataAdapter("select * from patient where firstname OR lastname = '" + txtSearch.Text + "'", con);
DataTable dt = new DataTable();
ada.Fill(dt);
dataGridView1.DataSource = dt;
label2.Text = dataGridView1.RowCount.ToString();
result.Visible = true;
result.Text ="Showing: "+ dataGridView1.RowCount.ToString()+ " results";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void search_Click(object sender, EventArgs e)
{
try
{
MySqlDataAdapter ada = new MySqlDataAdapter("select * from patient where firstname = '" + txtSearch.Text + "'" OR lastname = '" + txtSearch.Text + "'", con);
DataTable dt = new DataTable();
ada.Fill(dt);
dataGridView1.DataSource = dt;
label2.Text = dataGridView1.RowCount.ToString();
result.Visible = true;
result.Text ="Showing: "+ dataGridView1.RowCount.ToString()+ " results";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

You need to fully define both conditions such as:
...
MySqlDataAdapter ada = new MySqlDataAdapter("select * from patient where firstname = '" + txtSearch.Text + "' OR lastname = '" + txtSearch.Text + "'", con);
...

Related

c# search concatenated column using textbox

How can I search concatenated columns? I know how to do a single column search but what I want is to search concatenated column.. Please help me
public void searchenrolee()
{
MySqlCommand cmd = connection.CreateCommand();
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
try
{
connection.Open();
string value = "Fullname";
cmd.CommandText = String.Format(
#"Select EEid, CONCAT(Fname,' ', Mname,' ', Lname) AS Fullname, DateRegistered
from studenttbl
where {0} like #searchKey AND year(DateRegistered) = '" + cbStudYear.selectedValue.ToString() + "' AND Enrollingto = '" + cbSLGrade.selectedValue.ToString() + "' order by EEid desc", value);
cmd.Parameters.AddWithValue("#searchKey", '%' + tbsearchEnrolee.Text.ToString() + '%');
MySqlDataAdapter kuhain = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
dgvStudentList.DataSource = ds.Tables[0].DefaultView;
connection.Close();
}
catch
{
connection.Close();
}
}
private void tbsearchEnrolee_TextChanged(object sender, EventArgs e)
{
searchenrolee();
}
answer by Crowcoder
public void searchenrolee()
{
MySqlCommand cmd = connection.CreateCommand();
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
try
{
connection.Open();
string value = "Fullname";
cmd.CommandText = String.Format(
#"Select EEid, CONCAT(Fname,' ', Mname,' ', Lname) AS Fullname, DateRegistered
from studenttbl
where CONCAT(Fname,' ', Mname,' ', Lname) like #searchKey AND year(DateRegistered) = '" + cbStudYear.selectedValue.ToString() + "' AND Enrollingto = '" + cbSLGrade.selectedValue.ToString() + "' order by EEid desc", value);
cmd.Parameters.AddWithValue("#searchKey", '%' + tbsearchEnrolee.Text.ToString() + '%');
MySqlDataAdapter kuhain = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
dgvStudentList.DataSource = ds.Tables[0].DefaultView;
connection.Close();
}
catch
{
connection.Close();
}
}
private void tbsearchEnrolee_TextChanged(object sender, EventArgs e)
{
searchenrolee();
}

CheckBox Not Sending Checked Value to Access Database C# Asp

This is my C# code and my issue as the title says is my checkbox values are not going into my access database, or at least not changing them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
Label1.Text = (string)Session["sesionicontrol"];
}
protected void txtPass_TextChanged(object sender, EventArgs e)
{
}
protected void check1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
//Declare Variables
string username = txtEmailLogin.Text;
string password = txtPasswordLogin.Text;
username = username.Trim().ToLower();
password = password.Trim().ToLower();
//Handle null or empty fields
if ((string.IsNullOrEmpty(username)) || (string.IsNullOrEmpty(password)))
{
lblError.Text = "Please Enter a vaild Username or Password";
}
else if (((username.Contains("#mu.edu") || (username.Contains("#marquette.edu")))))
{
//Run select query and populate a table, then check to see if the user and pass are in that table
OleDbConnection conn = null;
DataTable dt = new DataTable();
try
{
string connString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "Select Count(*) From Team Member Where Email = ? AND Pass = ?";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
catch (Exception ex)
{
// handle error here
}
finally
{
conn.Close();
}
//checking if there is a result in the virtual table, if there is they successfully logged in
if (dt.Rows.Count >= 0)
{
lblError.Text = "Welcome!";
/// Take to Homepage
CommonClass.txtEmail = txtEmailLogin.Text;
Server.Transfer("HomePage.aspx", true);
}
else
{
lblError.Text = "Incorrect Username or Password";
}
}
}
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
DataTable gridTable = new DataTable();
try
{
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "INSERT INTO [Team Member] (FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major) VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" + txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "')";
string query1 = "INSERT INTO [Team Member] (Soccer, Basketball, Football, Softball) VALUES('" + c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
lblError1.Text = ("Registered Successfully");
}
catch (Exception ex)
{
lblError1.Text = ("Error occurred: " + ex.Message);
}
finally
{
conn.Close();
}
}
protected void btnReg_Click(object sender, EventArgs e)
{
txtFirst.Visible = !txtFirst.Visible;
txtLast.Visible = !txtLast.Visible;
txtEmail.Visible = !txtEmail.Visible;
txtPass.Visible = !txtPass.Visible;
txtPassConfirm.Visible = !txtPassConfirm.Visible;
btnRegister.Visible = !btnRegister.Visible;
btnReg.Visible = !btnReg.Visible;
c1.Visible = !c1.Visible;
c2.Visible = !c2.Visible;
c3.Visible = !c3.Visible;
c4.Visible = !c4.Visible;
txtAge.Visible = !txtAge.Visible;
txtHobbies.Visible = !txtHobbies.Visible;
txtFavorite.Visible = !txtFavorite.Visible;
txtMajor.Visible = !txtMajor.Visible;
lbl1.Text = "Sports you want to play";
lbl2.Text = "Age";
lbl3.Text = "Hobbies";
lbl4.Text = "Favorite Color";
lbl5.Text = "Major";
}
protected void c2_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void c1_CheckedChanged(object sender, EventArgs e)
{
}
}
My database looks like this
If you are appending to Access Yes/No fields then I would try removing the single quotes (') from the second INSERT INTO line:
string query1 = "INSERT INTO [Team Member]
(Soccer, Basketball, Football, Softball)
VALUES(" + c1.Checked.ToString() + ", "
+ c2.Checked.ToString() + ", "
+ c3.Checked.ToString() + ", "
+ c4.Checked.ToString() + ")";
First, The reason your check box values never get inserted is because your OleDbCommand is defined like this:
OleDbCommand cmd = new OleDbCommand(query, conn);
Using query as the command.text. query1 is never referenced to this and thus never executes.
Second (more important), you need to have the insert statement as one statement, not 2. Calling 2 Insert statements would cause 2 rows to added to the table. One containing values from query, and one containing the checkbox value from query1. You should define your query in one string like this
string query = "INSERT INTO [Team Member] " +
"(FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major, Soccer, Basketball, Football, Softball) " +
"VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" +
txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "','" +
c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";

I am getting {collection was modified after the enumerator was instantiated} this exception while closing the Form

my code is like this:
public partial class TimeTableForm : Form
{
string text;
string t;
string day;
public TimeTableForm(string str, string element,string d)
{
InitializeComponent();
text = str;
t = element;
day = d;
}
private void TimeTableForm_FormClosing(object sender, FormClosingEventArgs e)
{
//timetableData.Dispose();
//this.Visible = false;
this.Dispose();
Application.Exit();
//SelectElementForm ob = new SelectElementForm();
//ob.Show();
//this.Close();
}
//to generate the time table
public void GenerateTimeTable()
{
if(t == "Classes")
{
LogFile file = new LogFile();
file.LoggingInfo("Class selected: "+text+" and day selected: "+day);
SqlConnection conn = new SqlConnection("Data Source=WONDERBIZ;Initial Catalog=School_TimeTable;Integrated Security=True");
conn.Open();
string query = "select p.periodTime,s.subjectName,tc.teacherName,cr.classRomId from tbl_timetable t"
+" join tbl_Days d on d.dayId = t.dayId"
+" join tbl_Periods p on p.periodId = t.periodId"
+" join tbl_Subjects s on s.subjectId = t.subjectId"
+" join tbl_teachers tc on tc.teacherId = t.teacherId"
+" join tbl_classes cl on cl.classId = t.classId"
+" join tbl_classrooms cr on cr.classRomId = t.classroomId"
+" where cl.className = '"+text+"'"
+" and d.dayName = '"+day+"'"
+" order by p.periodId asc;";
SqlCommand cmd = new SqlCommand(query, conn);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//filling up the dataset
da.Fill(ds, "timetable data");
//showing the data
timetableData.DataSource = ds;
timetableData.DataMember = "timetable data";
conn.Close();
//ds.Clear();
}
catch(SqlException ex)
{
file.LoggingError(t + " timetable:" + ex.Message);
}
catch(Exception ex)
{
file.LoggingError(t+" timetable:" + ex);
}
ElementLabel.Text = "Class:";
SelectedElementLabel.Text = text;
dayLabel.Text = day;
}
if (t == "Teachers")
{
LogFile file = new LogFile();
file.LoggingInfo("Teacher selected: " + text + " and day selected: " + day);
SqlConnection conn = new SqlConnection("Data Source=WONDERBIZ;Initial Catalog=School_TimeTable;Integrated Security=True");
conn.Open();
string query = "select cl.className,p.periodTime,s.subjectName,cr.classRomId from tbl_timetable t"
+ " join tbl_Days d on d.dayId = t.dayId"
+ " join tbl_Periods p on p.periodId = t.periodId"
+ " join tbl_Subjects s on s.subjectId = t.subjectId"
+ " join tbl_teachers tc on tc.teacherId = t.teacherId"
+ " join tbl_classes cl on cl.classId = t.classId"
+ " join tbl_classrooms cr on cr.classRomId = t.classroomId"
+ " where tc.teacherName = '" + text + "'"
+ " and d.dayName = '" + day + "'"
+ " order by p.periodId asc;";
SqlCommand cmd = new SqlCommand(query, conn);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//filling up the dataset
da.Fill(ds, "timetable data");
//showing the data
timetableData.DataSource = ds;
timetableData.DataMember = "timetable data";
conn.Close();
}
catch (SqlException ex)
{
file.LoggingError(t + " timetable:" + ex.Message);
}
catch (Exception ex)
{
file.LoggingError(t + " timetable:" + ex);
}
ElementLabel.Text = "Teacher:";
SelectedElementLabel.Text = text;
dayLabel.Text = day;
}
if (t == "Classrooms")
{
LogFile file = new LogFile();
file.LoggingInfo("Classroom selected: " + text + " and day selected: " + day);
SqlConnection conn = new SqlConnection("Data Source=WONDERBIZ;Initial Catalog=School_TimeTable;Integrated Security=True");
conn.Open();
string query = "select cl.className,p.periodTime,s.subjectName,tc.teacherName from tbl_timetable t"
+ " join tbl_Days d on d.dayId = t.dayId"
+ " join tbl_Periods p on p.periodId = t.periodId"
+ " join tbl_Subjects s on s.subjectId = t.subjectId"
+ " join tbl_teachers tc on tc.teacherId = t.teacherId"
+ " join tbl_classes cl on cl.classId = t.classId"
+ " join tbl_classrooms cr on cr.classRomId = t.classroomId"
+ " where cr.classRomId = '" + text + "'"
+ " and d.dayName = '" + day + "'"
+ " order by p.periodId asc;";
SqlCommand cmd = new SqlCommand(query, conn);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//filling up the dataset
da.Fill(ds, "timetable data");
//showing the data
timetableData.DataSource = ds;
timetableData.DataMember = "timetable data";
conn.Close();
}
catch (SqlException ex)
{
file.LoggingError(t + " timetable:" + ex.Message);
}
catch (Exception ex)
{
file.LoggingError(t + " timetable:" + ex);
}
ElementLabel.Text = "Classroom:";
SelectedElementLabel.Text = text;
dayLabel.Text = day;
}
}
private void TimeTableForm_Load(object sender, EventArgs e)
{
GenerateTimeTable();
}

DataGrid View Not Showing Newly Added Record using Access Database

I am new to C# and I want to do this ASAP as I've had this problem since past week. I have tried a few approaches and not yet gotten the correct output. Here is my code:
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
String itemcode = tbItemCode.Text.ToString();
String shade = tbShade.Text.ToString();
String rollnumber = tbRollNumber.Text.ToString();
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Eranga\Documents\Visual Studio 2010\Projects\RollAllocationModel\RollAllocationModel\Roll.mdb;Persist Security Info=True;Jet OLEDB:Database Password=admin");
String deletequery = "DELETE FROM TabRoll WHERE (ItemCode = '" + itemcode + "') AND (Shade = '" + shade + "') AND (RollNumber = '" + rollnumber + "')";
//String deletequery = "SELECT * FROM TabRoll";
//code by query builder ----> DELETE FROM TabRoll WHERE (ItemCode = '" + itemcode + "') AND (Shade = '" + shade + "') AND (RollNumber = '" + length + "');
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(deletequery, conn);
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bSource = new BindingSource();
bSource.DataSource = dt;
dataGridView1.EndEdit();
bSource.EndEdit();
da.Update(dt);
dataGridView1.DataSource = bSource;
conn.Close();
MessageBox.Show("Data deleted");
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
}
Why doesn't the DataGrid does not update with the new record.

Update dynamically created textbox

I have created this update function but I am gettng "SelectCommand.Connection property has not been initialized" error.Can anyone help me for this.My code is:
public void Update_Click(object sender, EventArgs e)
{
Button b = sender as Button;
b.ForeColor = Color.Blue;
b.Font.Bold = true;
string strTableName = Request.QueryString["table"];
DataTable dt = new DataTable();
DataTable dtColumn=new DataTable();
MySqlConnection sQLcONN = new MySqlConnection("connection");
sQLcONN.Open();
// MySqlCommand sqlcolum=new MySqlCommand("SELECT *FROM information_schema.columns WHERE table_name ="+strTableName);
// MySqlDataAdapter sqlDa1=new MySqlDataAdapter(sqlcolum);
// sqlDa1.Fill(dtColumn);
// MySqlCommand sqlCmd = new MySqlCommand("update " + strTableName + "set " + dtColumn.Rows[introws]["column_name"] + "='" + "txtTextbox" + dt.Rows[introws][0].ToString() + "' where " + dtColumn.Rows[introws]["column_name"] + "=" + dt.Rows[introws][0], sQLcONN);
MySqlCommand sqlCmd = new MySqlCommand("update " + strTableName + "set " + dtColumn.Rows[introws]["column_name"] + "=#value1 where " + dtColumn.Rows[introws]["column_name"] + "=#value2", sQLcONN);
sqlCmd.Parameters.AddWithValue("#value1", "txtTextBox + dt.Rows[introws][0].ToString()");
sqlCmd.Parameters.AddWithValue("#value2",dt.Rows[introws][0]);
MySqlDataAdapter sqlDa = new MySqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Write("Succesfully updated");
}
else
{
Response.Write("Error");
}
}
}

Categories

Resources