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
'>
Related
[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
During find data between two days, getting error "there is no row at position 0"
MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["Demo"].ConnectionString.ToString());
string str = "select * from sample where name='" + Session["name"] + "' and date between '" + txtfirstdate.Text + "' and '" + txtenddate.Text + "'";
MySqlCommand cmd = new MySqlCommand(str, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataSet set = new DataSet();
connection.Open();
adapter.Fill(set);
connection.Close();
//var table = set.Tables[0];
if (set != null)
{
lblname.Text = set.Tables[0].Rows[0]["name"].ToString();
lbldate.Text = set.Tables[0].Rows[0]["date"].ToString();
}
Read the Error Message. Your result set table has no rows.
Replace u r if Condition.
if (set.Tables[0].Rows.Count > 0) {
lblname.Text = set.Tables[0].Rows[0]["name"].ToString();
lbldate.Text = set.Tables[0].Rows[0]["date"].ToString();
}
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();
}
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.
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);