SqlDataReader myReader1 = null;
SqlCommand myCommand1 = new SqlCommand("SELECT Standard_Note_Code, COUNT(Standard_Note_Code) as Count FROM [Excel_table] where Standard_Note_Creator_Name = '" + ddlrep.Text + "' and (Std_Note_Date_Entered >= '" + datefrom + "' and Std_Note_Date_Entered <= '" + dateto + "') group by Standard_Note_Code", myConnection);
myReader1 = myCommand1.ExecuteReader();
myReader1.Read();
gvsummary.Visible = true;
if (myReader1.HasRows)
{
gvsummary.DataSource = myReader1;
gvsummary.DataBind();
}
else
{
myReader1.Close();
//myConnection.Close();
//Label2.Text = "No Records Exist";
}
myReader1.Close();
Remove myReader1.Read();, after ExecuteReader. That line causes the grid to start reading from the 2nd position.
Everything looks correct to me, except I don't think you should be calling
myReader1.Read();
before you bind to the GridView. I think if you remove that line it will fix your problem.
Don't call myReader1.Read(); if you're binding as a data source.
Related
I'm trying to create session, using the following code:
SqlConnection conn = new SqlConnection("Data Source=THIRD-I;Initial Catalog=sessionlogin;Integrated Security=True;");
SqlDataAdapter sda = new SqlDataAdapter("Select (*) From logintable Where username='" + UserName.Text + "' and password='" + Password.Text + "'",conn);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString()== "1")
{
Session["user"] = UserName.Text;
Response.Redirect("welcome.aspx");
}
You need count of records from the data adapter. So the SQL query should be new SqlDataAdapter("Select count(*) From logintable Where username='" + UserName.Text + "' and password='" + Password.Text + "'",conn);
To fix an error:
Remove brackets from Select (*) or if you looking for total number add count
Must be select * or select count(*)
But your full code required big refactoring.
Disposing objects
Parameterize query
Assuming you take user input you should filter input
SqlConnection con = new SqlConnection(#"Data Source=shashi-PC\SQLEXPRESS;Initial Catalog=payroll;Integrated Security=True;Pooling=False");
SqlCommand com = new SqlCommand("insert into Leave_trans values(" + txtempid.Text + ",'" + ddlleavetype.SelectedValue + "'," + txtallowedays.Text + "," + txtpendingleave.Text + ",'" + txtleavefrom.Text + "','" + txtleaveto.Text + "'," + txttotalleaves.Text + ")");
com.Connection = con;
con.Open();
com.ExecuteNonQuery();
Response.Write("<script>alert('Leave data saved successfully')</script>");
con.Close();
This doesn't directly answer your question, but you should never take user-input and use string concatenation to build an SQL query (please take some time to read about SQL injection e.g. here or here).
Instead of concatenating the full query, you should use SqlParameter instances as placeholders for your values, e.g:
var com = new SqlCommand(
"insert into Leave_trans values(#empId, #leaveType, #allowedDays, ...)");
com.Parameters.Add(new SqlParameter("#empId", txtempid.Text));
com.Parameters.Add(new SqlParameter("#leaveType", ddlleavetype.SelectedValue));
com.Parameters.Add(new SqlParameter("#allowedDays", txtalloweddays.Text));
...
BTW: the cause for your problem is that you are not correctly single-quoting your inputs inside the query (e.g. txtempid.Text is not in single quotes). Using SqlParameters will also solve that problem for you.
I think the problem is in your query. You didn't provide us the data type of your database columns. But assuming from your query you are inserting some text from TextBox and one DropDownList selected item. From your TextBox text you will always get a string type value and for inserting string into your columns you should use single quotation '' before and after on it. But on your query you didn't use any quotation for some of your value parameter. I made an assumption and made a query for you. try this updated one.
SqlConnection con = new SqlConnection(#"Data Source=shashi-PC\SQLEXPRESS;Initial Catalog=payroll;Integrated Security=True;Pooling=False");
SqlCommand com = new SqlCommand("insert into Leave_trans values(" + "'" + txtempid.Text + "'", "'" + ddlleavetype.SelectedValue + "'","'" + txtallowedays.Text + "'","'" + txtpendingleave.Text + "'", "'" + txtleavefrom.Text + "'","'" + txtleaveto.Text + "'", "'" + txttotalleaves.Text + "')");
com.Connection = con;
con.Open();
com.ExecuteNonQuery();
Response.Write("<script>alert('Leave data saved successfully')</script>");
But i have some suggestion for you that is- you shouldn't use string as your table's primary key data type, it should be int type and another one is you should take int id of your selected item from your DropDownList not the text.
i have the problem, that i create a TextBox via vb.net Code while the programm ist running.
Private Sub GenerateTBSourcePath()
'Generiert eine neue leere Textbox
Dim tBox As System.Web.UI.WebControls.TextBox = New System.Web.UI.WebControls.TextBox()
tBox.Width = 400
Dim tbID As Integer = tbSourcePathID + 1
tBox.ID = "tbSourcePath_" + tbID.ToString()
pSourcePath.Controls.Add(tBox)
End Sub
When i try to search for the TextBox on pSourcePath i cant find any TextBox.
Have anyone an idea what do i wrong?
i add the TextBox in start of my programm. I can see the TextBox also in the Browser. When i want to save the Text i cant find the TextBox.
Private Sub SaveTBox()
'Für jede TBox den Eintrag in der DB aktualisieren oder einen neuen Eintrag anlegen
For Each PControl As System.Web.UI.Control In pSourcePath.Controls
Dim Controltype As String = PControl.GetType().FullName
Select Case Controltype
Case "System.Web.UI.WebControls.TextBox"
Dim tBox As WebControls.TextBox = CType(PControl, WebControls.TextBox)
If CheckExists(tBox.ID) = True
'Update
Administration_DataSource.UpdateCommand = "Update di_source set PATH = '" & tBox.Text & "' where TBID = '" & tBox.ID & "'"
Administration_DataSource.Update()
Else
'Insert
tbSourcePathID = tbSourcePathID + 1
Administration_DataSource.InsertCommand = "Insert Into di_source(ID, PATH, TBID) values('" & tbSourcePathID & "', '" & tBox.Text & "', '" & tBox.ID & "')"
Administration_DataSource.Insert()
End If
End Select
Next
End Sub
I tried this code
int tbSourcePathID = 0;
TextBox tBox = new TextBox();
PlaceHolder pSourcePath = new PlaceHolder();
tBox.Width = 400;
int tbID = tbSourcePathID + 1;
tBox.ID = "tbSourcePath_" + tbID.ToString();
pSourcePath.Controls.Add(tBox);
foreach (System.Web.UI.Control PControl in pSourcePath.Controls)
{
string Controltype = PControl.GetType().FullName;
switch (Controltype)
{
case "System.Web.UI.WebControls.TextBox":
bool here = true;
break;
}
}
and it works. Maybe the problem is in CheckExists(). Remember also the use of FindControl()
I am trying to insert a record into the database using the below method. I am calling this method in a button click event but for some reasons no record is being inserted.
There are four fields which need to be inserted: rpttemplateid - I am getting that field from another database table and all the other feilds are just static values.
What am i doing wrong below?
public void updatereporttemplate()
{
string cnn = WebConfigurationManager.ConnectionStrings["Underwriting"].ConnectionString;
SqlConnection cnn1 = new SqlConnection(cnn);
cnn1.Open();
string getrptdesc = "select max(rptdesc) + 1 from report_description where rptdesc < 999 and rptdesc is not null";
SqlCommand cmd = new SqlCommand(getrptdesc, cnn1);
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
int getcount = int.Parse(sdr[0].ToString());
sdr.Close();
string commandtext1 = "INSERT INTO report_template" + "(rpttemplateid,rpttemplatedescr,minsubs,minmebers) " +
" Values( " + getcount + "," + " " + " , " + 0 + "," + 0 + ")";
SqlCommand command1 = new SqlCommand
{
CommandText = commandtext1,
Connection = cnn1
};
You are missing command1.ExecuteNonQuery();
Also, have you considered using an IDENTITY column in your table instead of trying to manually set the count? What if that page is hit by multiple people at the same time?
You need to open the connection
cnn1.Open();
And then execute the command
command1.ExecuteNonQuery();
I have a DateTime field in my SQL database which I want to write a time to, but how do I do this?
I'm wanting to do it as a timestamp, so when the user clicks an "add" button it adds the data to the other fields, and a timestamp into the DateTime field, but I keep getting the following error
Conversion failed when converting date and/or time from character string.
This is my current code in the CS file
insertSQL = "INSERT INTO Posts (TopicID, PostBody, PostDate, UserID)"
+ "VALUES ('" + topic + "', '" + newPostText + "', '" + DateTime.Now.ToString() + "', '" + User_ID + "')";
Please note I'm wanting to display as much time info as I can. Eg 23/05/2012 10:58:00 a.m.
Your implementation is prone to SQL Injection. To resolve that, AND your DateTime issue, use parameters - http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
Something like this:
string commandText = "INSERT INTO Posts (TopicID, PostBody, PostDate, UserID)"
+ "VALUES (#Topic, #NewPostText, #PostDate, #UserID)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.AddWithValue("#Topic", "My Topic");
command.Parameters.AddWithValue("#NewPostText", "Post text goes here");
command.Parameters.AddWithValue("#PostDate", dateObject);
command.Parameters.AddWithValue("#UserID", "UserA");
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
}
catch (Exception)
{
// Handle Errors
}
}
Are you asking for strtotime() ?
<?php
$d = date('y-m-d');
echo date('d M Y',strtotime( $d ));
echo "<br>";
echo date('Y-m-d H:i:s'); ?>
sigh, my fault, it's for Php~