I need to show every record which equals the var modid and the current session's userid.
In .cs code this would be:
SELECT Mod_Naam
FROM Model
WHERE Mod_ID = " + modid + "
AND User_ID = '" + Session["status"].ToString() + "'
How can I import this query in a dropdownlist?
I may also need to use this on a gridview.
You can get the data from a DB via the DataTable and then bind that DataTable to the dropdownlist as follows:
using (SqlCommand cmd = new SqlCommand()
{
cmd.Connection = cnn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Mod_Naam FROM Model WHERE Mod_ID = " + modid + " AND User_ID = '" + Session["status"].ToString() + "' "";
//cmd.Parameters.Add(param);// You add parameter
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
Take a look here, on how to get Data in DataTable Retrieve a DataTable using a SQL Statement
DropDownList1.DataSourceID = dt;
DropDownList1.DataTextField= "Mod_Naam";
DropDownList1.DataValueField= "Mod_Naam";
DropDownList1.DataBind();
Related
The problem says:
Too few parameters. Expected 1.
Here's my database table:
CustomerOrder [CustomerOrder(OrderId, ProdName, ProdPrice, OrderQty, CatName, OrderDate]
Code:
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO CustomerOrder(OrderId, ProdName, ProdPrice, OrderQty, CatName, OrderDate)values('" + txtOrderCode.Text + "','" + txtProdName.Text + "', '" + txtProdPrice.Text + "', '" + txtOrderQty.Text + "', '" + txtCatName.Text + "', '" + txtOrderDate.Text + "')";
cmd.ExecuteNonQuery();
tabControl1.SelectedTab = tabPage1;
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
int ordercode, orderqty;
double price;
string prodname, catname;
ordercode = Convert.ToInt32(txtOrderCode.Text);
orderqty = Convert.ToInt32(txtOrderQty.Text);
price = Convert.ToDouble(txtProdPrice.Text);
prodname = Convert.ToString(txtProdName.Text);
I would recommend you use parametrised queries instead as it will prevent you from Sql Injection Attacks. Here is a small example of how it could work with your code
String SqlCommand = "insert into CUSTOMERORDER values (#OrderId, #ProdName,#ProdPrice,#OrderQty, #CatName,#OrderDate)";
SqlCommand cmd = new SqlCommand(SqlCommand , //ConnectionString);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.Parameters.AddWithValue("#OrderId", txtOrderCode.Text);
cmd.Parameters.AddWithValue("#ProdName", txtProdName.Text );
cmd.Parameters.AddWithValue("#ProdPrice", txtProdPrice.Text);
cmd.Parameters.AddWithValue("#OrderQty", txtOrderQty.Text);
cmd.Parameters.AddWithValue("#CatName", txtCatName.Text.Text);
cmd.Parameters.AddWithValue("#OrderDate", txtOrderDate.Text);
cmd.ExecuteNonQuery();
conn.Close();
Read up on Sql Injection attacks. Doing it this way is much easier, cleaner and most importantly, safer. Also when looking at your code you are setting the text box values after you have ran the Sql command
I have one column in SQL table. which name is Intime. Its data type is nvarchar. It stores both date and time. But I want date and time separately.
I have tried this query:
select AttendanceDate,
SUBSTRING(convert(varchar,intime,113),1,11)[Intime],
SUBSTRING(convert(varchar,intime,113),13,19)[InTime],
InDeviceId,
OutTime,
OutTime,
OutDeviceId,
dbo.MinutesToDuration(duration) as Duration,
Status
from dbo.AttendanceLogs
where EmployeeId=2938
order by AttendanceDate desc
but if I pass same SQL command in grid view its not working.
public void Bind()
{
SqlCommand cmd = new SqlCommand("select AttendanceDate,SUBSTRING(convert(varchar,intime,113),1,11) as [InTime],SUBSTRING(convert(varchar,InTime,113),13,19) as [Intime],InDeviceId,OutTime,OutTime,OutDeviceId, dbo.MinutesToDuration(duration) as Duration,Status from dbo.AttendanceLogs where EmployeeId='" + empIdtxt.Text + "' and year(AttendanceDate)=" + ddlYear.SelectedItem + " and month(AttendanceDate)=" + ddlmnt.SelectedValue + " order by AttendanceDate desc", con);
SqlDataAdapter da = new SqlDataAdapter();
cmd.Connection = con;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.ControlStyle.Font.Size = 10;
}
Where possibly could be the problem?
replace your code with this
public void Bind()
{
SqlCommand cmd = new SqlCommand(#"select AttendanceDate,SUBSTRING(convert(varchar,intime,113),1,11) as [InTimeD],SUBSTRING(convert(varchar,InTime,113),13,19) as [IntimeT],
InDeviceId,OutTime,OutTime,OutDeviceId, dbo.MinutesToDuration(duration) as Duration,Status from dbo.AttendanceLogs
where EmployeeId='" + empIdtxt.Text + "' and year(AttendanceDate)=" + ddlYear.SelectedItem.Value +
" and month(AttendanceDate)=" + ddlmnt.SelectedValue + " order by AttendanceDate desc", con);
SqlDataAdapter da = new SqlDataAdapter(cmd,con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.ControlStyle.Font.Size = 10;
}
this line not filter any year it return object of drop down list
year(AttendanceDate)=" + ddlYear.SelectedItem + "
I want to show emp leave balance in textbox1 based on leavetype and emp id.
I'm using below code but it's not showing total leave balance.
private void cbleavetype_SelectedIndexChanged()
{
conn = new SqlConnection(#"Data Source=........")
conn.Open();
SqlCommand command = new SqlCommand("select leave from leaveallotment where id='" + comboBox1.Text + "' && leavetype='" + cbleavetype.Text + "'",conn);
SqlDataAdapter adp = new SqlDataAdapter(command);
DataTable tbl = new DataTable();
adp.Fill(tbl);
// Show total leave in textBox1
textBox1.Text = cbleavetype.SelectedValue.ToString();
}
I think one thing that needs to happen is to change '&&' to 'and'
You can use this below code snipset,
connectionString.Open();
SqlCommand command =
new SqlCommand(
"select LeaveCount from leaveallotment where
id= '" + comboBox1.Text + "' and
leavetype='" + comboBox2.Text + "'",
connectionString);
SqlDataReader da = command.ExecuteReader();
if (da.Read()) {
textBox1.Text = da["LeaveCount"].ToString();
}
connectionString.Close();
i am coding for a commenting system in asp.net C# but i am stopped at delete command because of i am not using any type of serial numbers to comments posted, then how can i able to delete a specific comment, i am just using a username, date, time, and text in comment. Can anyone help me please that how to use a delete command in this condition??
here is my code for posting:
protected void pospost_Click(object sender, EventArgs e)
{
string login;
if (HttpContext.Current.Session["UserName"] != null)
{
login = HttpContext.Current.Session["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from mobiles_pos";
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
DataRow rw = ds.Tables[0].NewRow();
rw[0] = Model.Text.ToString();
rw[1] = titlepos.Text.ToString();
rw[2] = txtpos.Text.ToString();
rw[3] = DateTime.Today.Date.ToString();
rw[4] = DateTime.Now.TimeOfDay.ToString();
rw[5] = login.ToString();
ds.Tables[0].Rows.Add(rw);
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = con;
cmd1.CommandText = "insert into mobiles_pos values('" + Model.Text + "','" + titlepos.Text + "','" + txtpos.Text + "','" + DateTime.Today.Date + "','" + DateTime.Now.TimeOfDay + "','" + login + "')";
da.InsertCommand = cmd1;
da.Update(ds);
con.Close();
titlepos.Text = "";
txtpos.Text = "";
//DataList2.DataSource = ds;
//DataList2.DataBind();
BindDataList2();
}
}
Best - Add a Primary key to the "mobiles_pos" table since your using sql just use an identity field it will auto increment for you.
or
Quick - Use a combination of the User name and date comment was intered you must use the full date time or it will delete everything that user entered that day.
"Delete from mobiles_pos where username = #UserName and createdDate = #createdDate"
How to filter data in datagrid for example if you select the combo box in student number then input 1001 in the text field. All records in 1001 will appear in datagrid. I am using sql server
private void button2_Click(object sender, EventArgs e)
{
if (cbofilter.SelectedIndex == 0)
{
string sql;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server= " + Environment.MachineName.ToString() + #"\; Initial Catalog=TEST;Integrated Security = true";
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds1 = new DataSet();
ds1 = DBConn.getStudentDetails("sp_RetrieveSTUDNO");
sql = "Select * from Test where STUDNO like '" + txtvalue.Text + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(ds1);
dbgStudentDetails.DataSource = ds1;
dbgStudentDetails.DataMember = ds1.Tables[0].TableName;
dbgStudentDetails.Refresh();
}
else if (cbofilter.SelectedIndex == 1)
{
//string sql;
//SqlConnection conn = new SqlConnection();
//conn.ConnectionString = "Server= " + Environment.MachineName.ToString() + #"\; Initial Catalog=TEST;Integrated Security = true";
//SqlDataAdapter da = new SqlDataAdapter();
//DataSet ds1 = new DataSet();
//ds1 = DBConn.getStudentDetails("sp_RetrieveSTUDNO");
//sql = "Select * from Test where Name like '" + txtvalue.Text + "'";
//SqlCommand cmd = new SqlCommand(sql,conn);
//cmd.CommandType = CommandType.Text;
//da.SelectCommand = cmd;
//da.Fill(ds1);
// dbgStudentDetails.DataSource = ds1;
//dbgStudentDetails.DataMember = ds1.Tables[0].TableName;
//ds.Tables[0].DefaultView.RowFilter = "Studno = + txtvalue.text + ";
dbgStudentDetails.DataSource = ds.Tables[0];
dbgStudentDetails.Refresh();
}
}
It's difficult to answer pricisely to a vague question. I guess that you'll have to adapt your SQL query with a WHERE statement containing the user input.
If 'student number' is selected in the combo box, query like this (numbers starting with):
SELECT id, name, number FROM students WHERE number LIKE #search + '%'
If 'student name' is selected, use another query (names containing):
SELECT id, name, number FROM students WHERE name LIKE '%' + #search + '%'
Please explain in what sense C# is concerned.
You don't say what is wrong with the code you commented out. You also don't say what type the Studno column is.
Have you tried something like:
ds1.Tables[0].DefaultView.RowFilter = "Studno = '" + txtvalue.text + "'";