I have to bind the datalist control as per the values inserted in the form of find frined.
here is my code:
protected void search_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mahi\Documents\Visual Studio 2010\Projects\fc 6-4\fc\App_Data\fc.mdf;Integrated Security=True;User Instance=True");
cn.Open();
string str = "select unm='" + funm_txt.Text + "' , university='" + DDLuni.SelectedItem + "', city='"+ DDLcity .SelectedItem +"' , yjoin='" + DDLyjoin.SelectedValue + "' ,yleave= '" + DDLycom.SelectedValue + "', ybatch='" + DDLbtch.SelectedValue + "' from profile";
SqlCommand cmd = new SqlCommand(str, cn);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(str, cn);
DataTable dt = new DataTable();
DataList1 .DataSource =dt;
DataList1.DataBind();
cn.Close();
}
There are few things I have noticed:
-First of all, you are highly vulnerable to sql-injection attacks as you are passing user entered values directly into the database. You can avoid this by using a parameterised query.
-Secondly, you need to filter the records in a WHERE clause. At the moment you are assigning user typed/selected values into a select query.
-And you need to use SelectedValue of dropdown list not SelectedItem
-Also you can use using() blocks to get SqlConnection and DataAdapter Disposed at the end.
Try this (Please replace col1, col2 as required and complete the query assigning all parameters):
DataTable dt = new DataTable();
using (SqlConnection cnn = new SqlConnection("your_conn_string"))
{
string str = "Select Col1, Col2,... From profile " +
"Where unm = #unm and university= #uni and " +
"..." +
"ybatch = #ybatch";
SqlCommand cmd = new SqlCommand(str, cnn);
cmd.Parameters.AddWithValue("#unm",funm_txt.Text);
cmd.Parameters.AddWithValue("#uni",DDLuni.SelectedValue);
...
cmd.Parameters.AddWithValue("#ybatch",DDLbtch.SelectedValue);
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = cmd;
cnn.Open();
adapter.Fill(dt);
}
}
DataList1.DataSource =dt;
DataList1.DataBind();
try this,
cn.Open();
string str = "select unm='" + funm_txt.Text + "' , university='" + DDLuni.SelectedItem + "', city='"+ DDLcity .SelectedItem +"' , yjoin='" + DDLyjoin.SelectedValue + "' ,yleave= '" + DDLycom.SelectedValue + "', ybatch='" + DDLbtch.SelectedValue + "' from profile";
SqlDataAdapter da = new SqlDataAdapter(str, cn);
DataTable dt = new DataTable();
da.fill(dt);
DataList1 .DataSource =dt;
DataList1.DataBind();
cn.Close();
Add following code:
Your SqlDataAdapter and SqlCommand is not communicating.
and you haven't filled Datatable with the result.
da.SelectCommand = cmd;
da.fill(dt);
Related
try
{
SqlConnection con = new SqlConnection("data source=DESKTOP-28VA3GI;database=EMPLOYEES;integrated security=true");
SqlCommand cmd = new SqlCommand("select * from emp where ename like '" + textBox1.Text + "%' or eno like '" + textBox1.Text + "%' or phone like '" + textBox1.Text + "%'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "e");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "e";
}
catch ( )
{
}
Are you trying to get multiple table at once? If yes then you can use dataset else you can use datatable.
In case you opt for dataset you can find the number of rows in tables you are getting by using ds.Tables(i).Rows.Count. (i --> index of the table which you want to check).
In case you opt for datatable (dt) you can find number of rows by dt.Rows.Count.
Based on the result you can show your message.
[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
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
'>
I'm using c# and this error is becoming headache for me. I do not know how to solve this error .
can anyone help me to solve this. Here is the code
try
{
string MyConnection2 = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\DELL\Documents\db1.mdb";
//Display query
string Query = "select riq_num , department, item_name , item_unit , no_of_stock_out , itemtype from outputdet1 where riq_num = " + textBox2.Text + " or department= '" + comboBox1.Text + " ' or item_name= '" + textBox4.Text + "' or item_unit= '" + comboBox2.Text + "' or no_of_stock_out = " + textBox6.Text + " or itemtype = '" + comboBox3.Text + "' ; ";
OleDbConnection MyConn2 = new OleDbConnection(MyConnection2);
OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
MyConn2.Open();
//For offline connection we will use MySqlDataAdapter class.
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
// here i have assign dTable object to the dataGridView1 object to display data.
dataGridView1.DataSource = dTable;
MyConn2.Close();
}
// OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I assumed that textBox2.Text & textBox6.Text return a string from textbox control, so that OleDbCommand will throwing exception when it contains empty value or any non-numeric string since it will form invalid SQL statement. Use parameterized query like this example:
string Query = #"select riq_num, department, item_name, item_unit, no_of_stock_out, itemtype
from outputdet1
where riq_num = #riq_num
or department= #department
or item_name= #item_name
or item_unit= #item_unit
or no_of_stock_out = #no_of_stock_out
or itemtype = #itemtype";
using (OleDbConnection MyConn2 = new OleDbConnection(MyConnection2))
{
using (OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2))
{
MyConn2.Open();
MyCommand2.Parameters.Add("#riq_num", textBox2.Text);
MyCommand2.Parameters.Add("#department", comboBox1.Text);
MyCommand2.Parameters.Add("#item_name", textBox4.Text);
MyCommand2.Parameters.Add("#item_unit", comboBox2.Text);
MyCommand2.Parameters.Add("#no_of_stock_out", textBox6.Text);
MyCommand2.Parameters.Add("#itemtype", comboBox3.Text);
// execute the query here
}
}
Remember that using statements used to dispose OLEDB connection immediately after it has closed so that GC can free up resources.
Additional note:
OleDbParameter works with parameter order instead of named parameters, hence ensure that the parameters are declared in their proper order from first to last.
Mabuhay!
What is the most efficient or more convenient way to do this.
I have a select query and put it on a datagridview base on my filter. It has 5 columns. I want to know if Column CA from that Datagridview already exist on Table 2 which is on Column 3?
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=db;User ID=sa;Password=pw");
// DateTime dt = new DateTime();
//dt = DateTime.Now.ToString();
SqlDataAdapter sda = new SqlDataAdapter("SELECT max(PurchaseOrder.POTitle) as Description,sum(PurchaseOrderEntry.Price *PurchaseOrderEntry.QuantityOrdered) as Amount, max(PurchaseOrder.PONumber)as PONumber, " +
" max(PurchaseOrderEntry.OrderNumber) as BoxCount, max(PurchaseOrderEntry.OrderNumber) as PLC,max(PurchaseOrderEntry.OrderNumber) as Branch, max(PurchaseOrderEntry.OrderNumber) as PreparedBy, max(PurchaseOrderEntry.OrderNumber) as CheckedBy " +
" FROM PurchaseOrder LEFT OUTER JOIN" +
" PurchaseOrderEntry ON PurchaseOrder.ID = PurchaseOrderEntry.PurchaseOrderID" +
" WHERE (PurchaseOrder.Remarks like '%" + tanggapan.Text + "%') AND (PurchaseOrder.DateCreated BETWEEN '" + dateTimePicker1.Text + "' AND '" + dateTimePicker2.Text + "' and PurchaseOrder.OtherStoreID = '" + branch.Text + "') Group By PurchaseOrder.PONumber", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
This show my query filter. Any tip on how to do if PurchaseOrderEntry.OrderNumber already exist on my records so I can manage which one repeats.
Thank you!
Chris
I added this code now on my works and it is working now.
DataTable dt = new DataTable();
dt.Clear();
dt.Reset();
con.Close();
adaptors1.SelectCommand = con.CreateCommand();
adaptors1.SelectCommand.CommandText = "Select TOP 1 [ponumber],[clref] from [ISSPandayan].[dbo].[" + branch.Text + "] where [ponumber] = '" + dr.Cells["ponumber"].Value + "' ORDER BY [clref] ASC";
adaptors1.Fill(dt);
// select query para malam kung existing ponumber
if (dt.Rows.Count == 1)
{
adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = dt.Rows[0][1].ToString();
}
else
{
adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = " ";
}
//adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = "";
//MessageBox.Show(Convert.ToString(dr.Cells["description"].Value));
con.Close();
con.Open();
adaptorss.InsertCommand.ExecuteNonQuery();
adaptorss.InsertCommand.Parameters.Clear();