c# search concatenated column using textbox - c#

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

Related

How to fix System.IndexOutOfRangeException: Cannot find table 0 ASP.NET

[WebMethod()]
public DataTable insert_data_to_db_from_local(string partnumber, string srctcode, string dockcode,int pack,string error,string chk,string user,DateTime day,string ekb,string kbid)
{
SqlConnection objConn = new SqlConnection();
SqlCommand objCmd = new SqlCommand();
SqlDataAdapter dtAdapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataTable dt = null;
string strConnString = null;
StringBuilder strSQL = new StringBuilder();
strConnString = "Server=localhost;UID=sa;PASSWORD=12345678;database=bds_pp_srct;Max Pool Size=400;Connect Timeout=600;";
strSQL.Append("INSERT INTO Hanheld (Part_Number,SRCT_Code,Dock_Code,Package,Error_Code,Chk_Type,LogUser,LogDate,ekb_order_no,Kanban_ID) VALUES ('" + partnumber + "','" + srctcode + "','" + dockcode + "','" + pack + "','" + error + "','" + chk + "','" + user + "','" + day + "','" + ekb + "','" + kbid + "') ");
//strSQL.Append(" WHERE [SRCT_Code] = '" + strCusID + "' ");
objConn.ConnectionString = strConnString;
var _with1 = objCmd;
_with1.Connection = objConn;
_with1.CommandText = strSQL.ToString();
_with1.CommandType = CommandType.Text;
dtAdapter.SelectCommand = objCmd;
dtAdapter.Fill(ds);
dt = ds.Tables[0];
dtAdapter = null;
objConn.Close();
objConn = null;
return dt;
}
This error :
System.IndexOutOfRangeException: Cannot find table 0.
at System.Data.DataTableCollection.get_Item(Int32 index)
Try this one
private DataTable dataTable = new DataTable();
string connString = #"query string here";
string query = "select table";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
conn.Close();
da.Dispose();
I think you are using DataSet in your code might be there would be a problem
so you first need to check where that DataSet contains datatable at 0 location
eg.
DataSet ds = new DataSet();
dtAdapter.Fill(ds);
if(ds != null && ds.Tables.Count > 0) {
//your logic
}
[WebMethod()]
public void insert_data_to_db_from_local(string partnumber, string srctcode, string dockcode)
{
using (SqlConnection conn = new SqlConnection("Server=localhost;UID=sa;PASSWORD=12345678;database=Test;Max Pool Size=400;Connect Timeout=600;"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"INSERT INTO Hanheld(Part_Number,SRCT_Code,Dock_Code) VALUES(#partnumber,#srctcode,#dockcode)";
cmd.Parameters.AddWithValue("#partnumber", partnumber);
cmd.Parameters.AddWithValue("#srctcode", srctcode);
cmd.Parameters.AddWithValue("#dockcode", dockcode);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
// MessgeBox.Show(e.Message.ToString(), "Error Message");
}
}
}
}
This my Be fixed

how to show only current date data in gridview?

I'm building a website in ASP.NET and I'd like to show only current date data in a GridView.
This is my C# code.
public void GridBind()
{
SqlCommand cmd_std = new SqlCommand("SELECT * FROM StudentInfo WHERE GRNo = '" + GR_No + "' AND school_id = '" + a + "' ", dbcon);
SqlDataAdapter sda_std = new SqlDataAdapter(cmd_std);
DataSet ds_std = new DataSet();
sda_std.Fill(ds_std);
if (ddlSubject.SelectedItem.Text == "All")
{
SqlCommand cmd = new SqlCommand("select * from HomeWork where Date >= '" + txtdate.Text + "' AND school_id='" + a + "' AND Standard='" + ds_std.Tables[0].Rows[0]["CurrentStd"].ToString() + "'", dbcon);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
gvhw.DataSource = ds;
gvhw.DataBind();
}
else
{
SqlCommand cmd = new SqlCommand("select * from HomeWork where Date >= '" + txtdate.Text + "' AND Subject = '"+ddlSubject.SelectedItem.Text+"' AND school_id='" + a + "' AND Standard='" + ds_std.Tables[0].Rows[0]["CurrentStd"].ToString() + "'", dbcon);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
gvhw.DataSource = ds;
gvhw.DataBind();
}
}
I need to display the current date inserted data show in GridView by default, i.e., if we bind the Grid on the page load then all data show in which I need to the same process but only show the current date data.
The question is not clear so I made some assumptions:
Use below code which will load the current date's record (When the actual page load)
string TDate = string.Empty;
if(string.IsNullOrEmpty(txtdate.Text))
{
TDate = DateTime.Now.ToString("dd/MM/yyyy");
}
else
{
TDate = txtdate.Text;
}
SqlCommand cmd = new SqlCommand("select * from HomeWork where Date = '" + TDate + "' AND school_id='" + a + "' AND Standard='" + ds_std.Tables[0].Rows[0]["CurrentStd"].ToString() + "'", dbcon);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
gvhw.DataSource = ds;
gvhw.DataBind();
EDIT:
string NewDate = DateTime.Now.ToString("dd/MM/yyyy");
public void GridBind()
{
dbcon.Open();
SqlCommand cmd = new SqlCommand("select Id,FORMAT(Date,'dd/MM/yyyy') AS Date,Subject,Disc from NoticeBoard where school_id='" + a + "' and FORMAT(Date,'dd/MM/yyyy')= '" + NewDate + "' , dbcon);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
gvTeacher.DataSource = ds;
gvTeacher.DataBind();
dbcon.Close();
}
I dont quite understand what you asked. Could you provide some expected output please? But if you just wanna to show the current date :
DateTime tudey = DateTime.Now;
public void GridBind()
{
dbcon.Open();
SqlCommand cmd = new SqlCommand("select Id,FORMAT(Date,'yyyy/MM/dd')AS Date,Subject,Disc from NoticeBoard where school_id='" + a + "'", dbcon);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
gvTeacher.DataSource = ds;
gvTeacher.DataBind();
dbcon.Close();
}
protected void DownloadFile(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Name, Data, ContentType from tblFiles1 where Id=#Id ";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
fileName = sdr["Name"].ToString();
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
asp.net page code
'>

How to output results using OR in searching value database?

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);
...

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.

import xml to mdb

I'm trying to export a SQL-Server query to an XML file now and I want to import that file to Access. I don't understand how to do this.
Here is the code I use to generate the XML:
protected void Button1_Click(object sender, EventArgs e) {
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlSconn"].ConnectionString);
con.Open();
string strSQL = "select * from dbo.table_"+test.Text.ToString()+"";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
DataSet ds = new DataSet();
dt.Fill(ds, "" + test.Text.ToString() + "");
ds.WriteXml(Server.MapPath("temp.xml"));
}
This may be a start.
static void SaveToMDB(DataSet ds, string strMDBFile)
{
OleDbConnection cAccess = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strMDBFile);
cAccess.Open();
foreach (DataTable oTable in ds.Tables)
{
OleDbCommand oCommand = new OleDbCommand(
"DROP TABLE [" + oTable.TableName + "]", cAccess);
try
{
oCommand.ExecuteNonQuery();
}
catch (Exception) { }
string strCreateColumns = "";
string strColumnList = "";
string strQuestionList = "";
foreach (DataColumn oColumn in oTable.Columns)
{
strCreateColumns += "[" + oColumn.ColumnName + "] VarChar(255), ";
strColumnList += "[" + oColumn.ColumnName + "],";
strQuestionList += "?,";
}
strCreateColumns = strCreateColumns.Remove(strCreateColumns.Length - 2);
strColumnList = strColumnList.Remove(strColumnList.Length - 1);
strQuestionList = strQuestionList.Remove(strQuestionList.Length - 1);
oCommand = new OleDbCommand("CREATE TABLE [" + oTable.TableName
+ "] (" + strCreateColumns + ")", cAccess);
oCommand.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter(
"SELECT * FROM [" + oTable.TableName + "]", cAccess);
da.MissingSchemaAction = MissingSchemaAction.Add;
da.FillLoadOption = LoadOption.OverwriteChanges;
da.InsertCommand = new OleDbCommand(
"INSERT INTO [" + oTable.TableName + "] (" + strColumnList
+ ") VALUES (" + strQuestionList + ")", cAccess);
foreach (DataColumn oColumn in oTable.Columns)
{
da.InsertCommand.Parameters.Add(
oColumn.ColumnName,
OleDbType.VarChar,
255,
oColumn.ColumnName
);
}
foreach (DataRow oRow in oTable.Rows)
oRow.SetAdded();
da.Update(oTable);
}
}
This Data will work only with ID and Name, using the system :
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data.Sql;using System.Data.SqlClient;using System.Configuration;using System.Data;using System.IO;
using System.Xml.Linq;
//import SelectiveDatabaseBackup.xml to test9 table
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices3"].ConnectionString;
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
ds.ReadXml(XDocument.Load("c:/d/SelectiveDatabaseBackup.xml").CreateReader());
foreach (DataTable table in ds.Tables)
{
//Create table
foreach (DataRow row in table.Rows)
{
string name = row[1].ToString();
string id = row[0].ToString();
cmd.CommandText = "INSERT test9 VALUES ('"+ id +"','"+ name + "')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
//--------------------------

Categories

Resources