ASP .NET Forms and Submit - asp.net

I am new to ASP .Net Web Forms. Tried creating a Web Page going through Youtube Tutorials and now I'm stuck on this step where I have created a form with inputs and select using Bootstrap. Here is what my Frontend looks like which is in Default.aspx ---->
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="jumbotron">
<center class="form-group-lg">
<form method="post" action="btnShow_Click">
<label>Token Number</label>
<input type="text" name="txtCommand" id="txtCommand" class="text-center form-control" value="" runat="server" />
<div class="row form-group">
<div class="col-md-4">
<label>Room Number</label>
<select class="form-control" name="CounterID" id="CounterID" runat="server">
<option value="0">Select Room Number</option>
<option value="1">Room Number 01</option>
<option value="2">Room Number 02</option>
<option value="3">Room Number 03</option>
<option value="4">Room Number 04</option>
<option value="5">Room Number 05</option>
<option value="6">Room Number 06</option>
<option value="7">Room Number 07</option>
<option value="8">Room Number 08</option>
<option value="9">Room Number 09</option>
<option value="10">Room Number 10</option>
</select>
</div>
<div class="col-md-4">
<label>Department</label>
<select class="form-control" id="CounterName" name="CounterName" runat="server">
</select>
</div>
<div class="col-md-4">
<label>Terminal</label>
<input type="text" class="form-control" name="TerminalID" id="TerminalID" runat="server" value="000" />
</div>
</div>
<div class="row">
<div class="col-md-6">
<p>Waiting Patients: <span id="label2">100</span></p>
<!-- <input type="text" readonly name="" id="label2" class="form-control" runat="server" value=""/> -->
</div>
<div class="col-md-6">
<p>Total Patients: <span id="label1">100</span></p>
<!-- <input type="text" readonly name="label1" id="label1" class="form-control" runat="server" value=""/> -->
</div>
</div>
<div class="form-group" style="margin-top:15px;">
<asp:Button ID="btnShow" type="submit" runat="server" Text="Next" Width="56px"/>
</div>
</form>
</center>
</div>
</asp:Content>
and my Default.aspx.cs looks like --->>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication2
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string conn = ConfigurationManager.ConnectionStrings["GIMS_HIMS"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(conn);
string depart = "select DeptCode, DepartmentName from Que_Master_Department where Active = 1";
SqlDataAdapter sda = new SqlDataAdapter(depart, sqlconn);
sqlconn.Open();
DataTable dt = new DataTable();
sda.Fill(dt);
CounterName.DataSource = dt;
CounterName.DataTextField = "DepartmentName";
CounterName.DataValueField = "DepartmentName";
CounterName.DataBind();
sqlconn.Close();
btnShow.Click += btnShow_Click;
}
//Recall Button Commands Start Here
private void Recall_Click(object sender, EventArgs e)
{
CalcPatientRemain();
string conn = ConfigurationManager.ConnectionStrings["GIMS_HIMS"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(conn);
string query = " DELETE FROM Que_Delegation WHERE Token = '" + txtCommand.Value + "'";
SqlCommand scom = new SqlCommand(query, sqlconn);
sqlconn.Open();
scom.ExecuteNonQuery();
query = " INSERT INTO Que_Delegation (Token, TerminalID, CounterID, CounterName, Dispatch) VALUES ('" + txtCommand.Value + "','" + TerminalID + "','" + CounterID + "','" + CounterName + "','False')";
SqlCommand scom1 = new SqlCommand(query, sqlconn);
scom1.ExecuteNonQuery();
sqlconn.Close();
}
//Recall Button Commands Ended
//Next Button Commands Starts
protected void Next_Click(object Sender, EventArgs e)
{
GetToken();
CalcPatientRemain();
MainScreenDisplay();
}
public void GetToken()
{
try
{
string conn = ConfigurationManager.ConnectionStrings["GIMS_HIMS"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(conn);
String userqry = "SELECT TOP(1) Token, ID FROM Que_Management2 Where Department = '" + CounterName + "' AND Flag = 'False' ORDER BY ID ASC";
sqlconn.Open();
SqlCommand cmd = new SqlCommand(userqry, sqlconn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
while (dr.Read())
{
txtCommand.Value = dr[0].ToString();
}
}
else
{
txtCommand.Value = string.Empty;
}
dr.Close();
string query = "Update Que_Management2 SET Flag = 'True' WHERE Token = '" + txtCommand.Value + "'";
SqlCommand scom2 = new SqlCommand(query, sqlconn);
scom2.ExecuteNonQuery();
if (txtCommand.Value != "")
{
query = " DELETE FROM Que_Delegation";
SqlCommand scom3 = new SqlCommand(query, sqlconn);
scom3.ExecuteNonQuery();
query = " INSERT INTO Que_Delegation (Token, TerminalID, CounterID, CounterName, Dispatch) VALUES ('" + txtCommand.Value + "','" + TerminalID + "','" + CounterID + "','" + CounterName + "','False')";
SqlCommand scom4 = new SqlCommand(query, sqlconn);
scom4.ExecuteNonQuery();
}
sqlconn.Close();
}
catch (Exception ex)
{
string abc = ex.Message;
}
}
public void CalcPatientRemain()
{
try
{
string conn = ConfigurationManager.ConnectionStrings["GIMS_HIMS"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(conn);
sqlconn.Open();
DateTime Date1 = DateTime.Today;
DateTime Date2 = DateTime.Today.AddDays(1);
SqlDataReader dr;
SqlCommand cmd;
cmd = new SqlCommand("usp_GetPatientRemain", sqlconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Date1", SqlDbType.DateTime).Value = Date1;
cmd.Parameters.Add("#Date2", SqlDbType.DateTime).Value = Date2;
cmd.Parameters.Add("#Department", SqlDbType.NVarChar).Value = CounterName;
dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
while (dr.Read())
{
label2.Value = (dr[0].ToString());
}
}
dr.Close();
cmd = new SqlCommand("usp_GetPatientTotal", sqlconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Date1", SqlDbType.DateTime).Value = Date1;
cmd.Parameters.Add("#Date2", SqlDbType.DateTime).Value = Date2;
cmd.Parameters.Add("#Department", SqlDbType.NVarChar).Value = CounterName;
dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
while (dr.Read())
{
label1.Value = (dr[0].ToString());
}
}
dr.Close();
sqlconn.Close();
}
catch (Exception ex)
{
string abc = ex.Message;
}
}
public void MainScreenDisplay()
{
string conn = ConfigurationManager.ConnectionStrings["GIMS_HIMS"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(conn);
sqlconn.Open();
string Date = DateTime.Now.ToString("MM/dd/yyyy");
string query = "";
if (txtCommand.Value == "" || txtCommand.Value == null)
{
txtCommand.Value = "----";
}
if (CounterID.Value == "1")
{
query = "Update Que_MainScreenDelegate2 SET T1 = '" + txtCommand.Value + "', C1 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom5 = new SqlCommand(query, sqlconn);
scom5.ExecuteNonQuery();
}
else if (CounterID.Value == "2")
{
query = "Update Que_MainScreenDelegate2 SET T2 = '" + txtCommand.Value + "', C2 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom6 = new SqlCommand(query, sqlconn);
scom6.ExecuteNonQuery();
}
else if (CounterID.Value == "3")
{
query = "Update Que_MainScreenDelegate2 SET T3 = '" + txtCommand.Value + "', C3 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom7 = new SqlCommand(query, sqlconn);
scom7.ExecuteNonQuery();
}
else if (CounterID.Value == "4")
{
query = "Update Que_MainScreenDelegate2 SET T4 = '" + txtCommand.Value + "', C4 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom8 = new SqlCommand(query, sqlconn);
scom8.ExecuteNonQuery();
}
else if (CounterID.Value == "5")
{
query = "Update Que_MainScreenDelegate2 SET T5 = '" + txtCommand.Value + "', C5 = '" + CounterID + "' , CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom9 = new SqlCommand(query, sqlconn);
scom9.ExecuteNonQuery();
}
else if (CounterID.Value == "6")
{
query = "Update Que_MainScreenDelegate2 SET T6 = '" + txtCommand.Value + "', C6 = '" + CounterID + "' , CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom10 = new SqlCommand(query, sqlconn);
scom10.ExecuteNonQuery();
}
else if (CounterID.Value == "7")
{
query = "Update Que_MainScreenDelegate2 SET T7 = '" + txtCommand.Value + "', C7 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom11 = new SqlCommand(query, sqlconn);
scom11.ExecuteNonQuery();
}
else if (CounterID.Value == "8")
{
query = "Update Que_MainScreenDelegate2 SET T8 = '" + txtCommand.Value + "', C8 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom12 = new SqlCommand(query, sqlconn);
scom12.ExecuteNonQuery();
}
else if (CounterID.Value == "9")
{
query = "Update Que_MainScreenDelegate2 SET T9 = '" + txtCommand.Value + "', C9 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom13 = new SqlCommand(query, sqlconn);
scom13.ExecuteNonQuery();
}
else if (CounterID.Value == "10")
{
query = "Update Que_MainScreenDelegate2 SET T10 = '" + txtCommand.Value + "', C10 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom14 = new SqlCommand(query, sqlconn);
scom14.ExecuteNonQuery();
}
}
//Next Button Commands Ended
protected void btnShow_Click(object Sender, EventArgs e)
{
// Page.ClientScript.RegisterStartupScript(
//Page.GetType(),
//"MessageBox",
//"<script language='javascript'>alert('Hello');</script>"
//);
GetToken();
CalcPatientRemain();
MainScreenDisplay();
}
}
}
The problem I'm facing is its doing nothing. No changes are visible and the database also shows no updates. The button works when I trigger OnClick event on it as show in the commented function where I was showing a message on button click but same when I try my functions its not working. Can someone please help what I'm doing wrong.

Dump this tutorial immediately. It teaches you an outdated framework (WebForms is not maintained anymore and won't run on .NET 5), and worse, it has giant SQL injection vulnerabilities (despite using parameterized queries - sometimes). Seriously, tutorials like this should be pulled.
If you want to create a .NET web application in 2021, use ASP.NET Core MVC or Razor Pages.
As for your error, you don't bind the Recall_Click handler to any button.

Related

How to declare scalar variable?

I get this error:
System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#refSlips".'
Code:
SqlConnection con = new SqlConnection(connectionString);
SqlCommand aaa = new SqlCommand("INSERT INTO ConsultationTB VALUES('" + consultationTb.Text + "','" + dateTb.Text + "','" + bodytempTb.Text + "','" + paccodeTb.Text + "', #refSlips ", con);
string RadButt = string.Empty;
if (ForAdmission.Checked)
{
RadButt = "For Admission";
}
else if (ForLabTest.Checked)
{
RadButt = "For Laboratory Test";
}
else if (BothRb.Checked)
{
RadButt = "Both";
}
else if (NotAppRb.Checked)
{
RadButt = "Not Applicable";
}
con.Open();
aaa.ExecuteNonQuery();
con.Close();
getCONNO();
ForAdmission.Checked = false;
ForLabTest.Checked = false;
BothRb.Checked = false;
NotAppRb.Checked = false;
[ + "', #refSlips)" , con);] the problem was the parenthesis after refslips.

i hava 1 error when i do web login by asp.net

my ideas: i select id(max) in table users to write table Userlogin. I get error:
'Conversion failed when converting the varchar value to data type int.'
SELECT idUser
FROM Users
WHERE idUser = (SELECT MAX(idUser) FROM Users)
how to fix error? thank you.
img error: Mycode, Myerror
mycode:
`` `using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace Web_tintuc2
{
public partial class DangKi : System.Web.UI.Page
{
private string connectString = #"Data Source=DESKTOP-
RT3QMVS; Initial Catalog =web_tintuc; Integrated Security=True;";
SqlConnection sql_connect;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_thoat_Click(object sender, EventArgs
e)
{
Response.Redirect("Trangchu.aspx");
//Response.Write("<script>alert('Hello');</script>");
}
protected void btn_dangki_Click(object sender, EventArgs
e)
{
sql_connect = new SqlConnection(connectString);
sql_connect.Open();
string username = txt_username.Text;
string phone = txt_Phone.Text;
string password = txt_password.Text;
string name = txt_name.Text;
string ngaysinh = txt_brithday.Text;
string diachi = txt_diachi.Text;
string email = txt_Email.Text;
DateTime aDateTime = DateTime.Now;
string ngaydangki = aDateTime.ToString("yyyy-MM-dd HH:mm:ss"); // fomat kiểu ngày thánh trong sql server
string active = "Actived";
string IdGruop = "2";
string gioitinh1 = "Nam";
String gioitinh2 = "Nữ";
string sql_check = "select Username from Userlogin
where Username='" + username + "' ";
SqlCommand sql1 = new SqlCommand(sql_check,
sql_connect);
SqlDataReader read = sql1.ExecuteReader();
if (read.Read() == true)
Lb_thongbao.Text = "Username đã tồn tại";
read.Close();
if (Radio_nam.Checked == true)
{
string sql_insert_toUser = " insert into Users(HoTen,Diachi,Email,Dienthoai,gioitinh,ngaysinh,idGroup,ngaydangki,active ) values('" + name + "','" + diachi + "','" + diachi + "','" + email + "','" + phone + "','" + gioitinh1 + "','" + ngaysinh + "','" + IdGruop + "','" + ngaydangki + "','" + active + "')";
SqlCommand sqlcommand1 = new
SqlCommand(sql_insert_toUser, sql_connect);
sqlcommand1.ExecuteNonQuery();
string sql_id_users = "Select top 1 idUser from
Users order by idUser desc";
string sql_insert_to_UserLogin = "insert into
Userlogin(Username,Password,idUser) values('" + username + "','" +
password + "','" + sql_id_users + "') ";
SqlCommand sqlCommand2 = new
SqlCommand(sql_insert_to_UserLogin, sql_connect);
sqlCommand2.ExecuteNonQuery();
}
else if (Radio_nu.Checked == true)
{
string sql_insert_toUser = " insert into Users(HoTen,Diachi,Email,Dienthoai,gioitinh,ngaysinh,idGroup,ngaydangki,active )values('" + name + "','" + diachi + "','" + email + "','" + phone + "','" + gioitinh2 + "','" + ngaysinh + "','" + IdGruop + "','" + ngaydangki + "','" + active + "')";
SqlCommand sqlcommand1 = new SqlCommand(sql_insert_toUser, sql_connect);
sqlcommand1.ExecuteNonQuery();
string sql_id_users = " SELECT idUser FROM Users
WHERE idUser = (SELECT MAX(idUser) FROM Users) ";
string sql_insert_to_UserLogin = "insert into
Userlogin(Username,Password,idUser) values('" + username + "','" +
password + "','"+sql_id_users+"') ";
SqlCommand sqlCommand_2 = new
SqlCommand(sql_insert_to_UserLogin, sql_connect);
sqlCommand_2.ExecuteNonQuery();
}
}
}
}'' '
Your error is coming from your insert statement (line 62). You have single quotes around the variable sql_id_users. Remove the single quotes. It's treating the value as varchar since you have it enclosed in single quotes but it expects an integer.
Suggestion: When you post, please post your code as text and not an image.

Get checkbx values selected from database

I have users form in which they can select some values from checkbox list & values selected in that stores in database in li form. Now I want when users wants to update their form they should be able to see the values checked they have selected earlier.
here is my code.
Insert Form
Private Sub PopulateServices()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from services"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("serviceName").ToString()
item.Value = sdr("serviceName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
servicesList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
Dim selectedServices As String = String.Empty
For Each chk As ListItem In servicesList.Items
If chk.Selected = True Then
selectedServices &= "<li>" + chk.Text + "</li>"
End If
Next
Try
Dim str1 As String = "INSERT INTO hospitals (`hospitalID`,`username`, `password`) values ('" + ID + "', '"selectedServices.ToString + "', '" + mobileNumber + "', '" + membersAutoPassword.Text + "')"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
con.Open()
str2 = command.ExecuteReader
con.Close()
Response.Redirect("business-added.aspx")
Catch ex As Exception
Response.Write(ex)
End Try
On User Profile page after login they should be able to see what options they have selected. Hence there is a option for users to update their details again
UPDATED
User Profile Page
Private Sub list_business_hospital_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Try
Dim str As String = "SELECT * FROM hospitals WHERE username='" + Server.HtmlEncode(Request.Cookies("chkusername").Value) + "';"
con.Open()
Dim cmd As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
Dim lblservice As New Label
For Each chk As ListItem In servicesList.Items
If chk.Selected = True Then
lblservice.Text = String.Concat(lblservice.Text + ",", chk.Value)
End If
Next
da.Fill(dt)
con.Close()
TextId.Text = dt.Rows(0)("hospitalID").ToString
Catch ex As Exception
Response.Write(ex)
End Try
Private Sub PopulateServices()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from services"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("serviceName").ToString()
item.Value = sdr("serviceName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
servicesList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
Private Sub updateInfo_Click(sender As Object, e As EventArgs) Handles updateInfo.Click
Try
Dim con As New MySqlConnection
Dim query As New MySqlCommand
con.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
query.Connection = con
con.Open()
Dim selectedServices As String = String.Empty
For Each chk As ListItem In servicesList.Items
If selectedServices.Contains("<li>" & chk.Text & "</li>") Then
'display item as selected
chk.Selected = True
End If
Next
query.CommandText = "UPDATE hospitals SET name = '" + businessName.Text + "', contactPerson = '" + contactPerson.Text + "', websiteName = '" + websiteName.Text + "', email = '" + emailName.Text + "', phone1 = '" + phone1.Text + "', phone2 = '" + phone2.Text + "', mobileNumber = '" + mobile.Text + "', buildingName = '" + buildingName.Text + "', streetName = '" + address.Text + "', landmark = '" + landmark.Text + "', areaName = '" + areaName.Text + "', city = '" + suburb.Text + "', state = '" + state.Text + "', zipCode = '" + zip.Text + "', overview = '" + overview.Text + "', registration = '" + regNo.Text + "', establishment = '" + foundation.Text + "', founder = '" + founderName.Text + "', generalBed = '" + GeneralBeds.Text + "', icuBed = '" + ICU.Text + "', consultancyFees = '" + consultinfees.Text + "', mondayFrom = '" + mondayFrom.Text + "', mondayTo = '" + mondayTo.Text + "', tuesdayFrom = '" + tuesdayFrom.Text + "', tuesdayTo = '" + tuesdayTo.Text + "', wednesdayFrom = '" + wedFrom.Text + "', wednesdayTo = '" + wedTo.Text + "', thursdayFrom = '" + thursdayFrom.Text + "', thursdayTo = '" + thursdayTo.Text + "', fridayFrom = '" + fridayFrom.Text + "', fridayTo = '" + fridayTo.Text + "', saturdayFrom = '" + saturdayFrom.Text + "', saturdayTo = '" + saturdayTo.Text + "', sundayFrom = '" + sundayFrom.Text + "', sundayTo = '" + sundayTo.Text + "', visitFrom = '" + visitFrom.Text + "', visitTo = '" + visitTo.Text + "', bestKnownFor = '" + bestknowFor.Text + "' WHERE hospitalID = '" + TextId.Text + "'"
query.ExecuteNonQuery()
con.Close()
Response.Write("<script language='javascript'>alert('Information updated successfully.');</script>")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Please check below,
'Here I assume that, you will call PopulateServices to populate servicesList checkbox list
PopulateServices()
'You didn't mention fieldName, so I assume that field in database is :
'savedServices - This will be li tags like, <li>item 1</li><li>item 2</li>
'Now loop through all items within checkbox list
For Each chk As ListItem In servicesList.Items
'You need to check whether this item saved in database or not?
'If item already saved in database, display as selected
If savedServices.Contains("<li>" & chk.Text & "</li>") Then
'display item as selected
chk.selected = true
End If
Next

Query has some issues

When I m writing this query in the code on button click to insert the mkey in the xxacl_pn_new_cha_part_h table
it gives me error as
"ORA-00904: "A": invalid identifier"
Here is my code:-
try
{
conn.Open();
OracleDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
cmd.CommandText = "insert into xxacl_pn_new_cha_part_h select sysdate, a.* from xxacl_pn_new_cha_part where mkey= " + sdr[0].ToString(); // this query gives error
cmd.ExecuteNonQuery();
strQuery = "UPDATE xxacl_pn_new_cha_part set Rating='" + sdr[2].ToString() + "', RATING_UPDATE_DATE=convert(datetime,'" + System.DateTime.Now.ToString() + "',103) WHERE mkey = " + sdr[0].ToString();
cmd.CommandText = strQuery;
cmd.ExecuteNonQuery();
}
ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", "alert('Broker rating updated succesfully');", true);
}
I am using Oracle
UPDATE
protected void btnUpdate_Click(object sender, EventArgs e)
{
OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["OracleConn"].ConnectionString);
string strQuery = "SELECT distinct ab.mkey, ab.broker_id,CASE WHEN SYSDATE - la.creation_date <= 180 THEN 'A' WHEN SYSDATE - cef_dt <= 30 THEN " +
"'B' ELSE 'C'END rating FROM xxacl_pn_new_cha_part ab,xxacl_pn_lease_det ld,xxacl_pn_leases_all la, " +
"xxcus.xxacl_pn_customer_enquiry_v ce WHERE ab.broker_id = ld.broker_id(+) AND ld.booking_no = la.booking_no(+) " +
" AND ab.broker_id = ce.broker_id(+)";
OracleCommand cmd = new OracleCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = conn;
try
{
conn.Open();
OracleDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
cmd.CommandText = "insert into xxacl_pn_new_cha_part_h select sysdate, a.* from xxacl_pn_new_cha_part a where a.mkey= " + sdr[0].ToString();
cmd.ExecuteNonQuery();
strQuery = "UPDATE xxacl_pn_new_cha_part set Rating='" + sdr[2].ToString() + "', RATING_UPDATE_DATE=convert(datetime,'" + DateTime.Now.ToString() + "',103) WHERE mkey = " + sdr[0].ToString();
cmd.CommandText = strQuery;
cmd.ExecuteNonQuery();
}
ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", "alert('Broker rating updated succesfully');", true);
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
conn.Dispose();
}
}
You are missing the alias name here, try this one
cmd.CommandText = "insert into xxacl_pn_new_cha_part_h select sysdate, a.* from xxacl_pn_new_cha_part a where a.mkey= " + sdr[0].ToString();
UPDATE:
protected void btnUpdate_Click(object sender, EventArgs e)
{
OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["OracleConn"].ConnectionString);
string strQuery = "SELECT distinct ab.mkey, ab.broker_id,CASE WHEN SYSDATE - la.creation_date <= 180 THEN 'A' WHEN SYSDATE - cef_dt <= 30 THEN " +
"'B' ELSE 'C'END rating FROM xxacl_pn_new_cha_part ab,xxacl_pn_lease_det ld,xxacl_pn_leases_all la, " +
"xxcus.xxacl_pn_customer_enquiry_v ce WHERE ab.broker_id = ld.broker_id(+) AND ld.booking_no = la.booking_no(+) " +
" AND ab.broker_id = ce.broker_id(+)";
OracleCommand cmd = new OracleCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = conn;
try
{
conn.Open();
OracleDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
cmd.CommandText = "insert into xxacl_pn_new_cha_part_h select 0, sysdate, a.* from xxacl_pn_new_cha_part a where a.mkey= " + sdr[0].ToString();
cmd.ExecuteNonQuery();
strQuery = "UPDATE xxacl_pn_new_cha_part set Rating='" + sdr[2].ToString() + "', RATING_UPDATE_DATE=to_date('" + DateTime.Now.ToString() + "','dd-mm-yyyy hh:mi:ss am') WHERE mkey = " + sdr[0].ToString();
cmd.CommandText = strQuery;
cmd.ExecuteNonQuery();
}
ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", "alert('Broker rating updated succesfully');", true);
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
conn.Dispose();
}
}
You missed the alias name of a table
"insert into xxacl_pn_new_cha_part_h select sysdate, a.* from xxacl_pn_new_cha_part a where a.mkey= " + sdr[0].ToString();

datagrid view is not showing data

I try this code for showing some info from sql database. but I can not see the datas in gridview..How can I solve?? Also, I have no error.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection("Server=CAN-PC; Database=SMS; UID=SA; PWD=delidana1963");
string sql = "";
sql = #"select Orginator,RecordDate, (select COUNT(TurkcellID) from SmsStore ";
// txttarih.Text = Calendar1.SelectedDate.ToString();
var tarih1 = String.Format("{0:yyyy-MM-dd hh:mm}", Calendar1.SelectedDate.Date);
var tarih2 = String.Format("{0:yyyy-MM-dd hh:mm}", Calendar2.SelectedDate.Date);
if (Calendar1.SelectedDate != null && Calendar2.SelectedDate != null)
sql += "where RecordDate between '" +tarih1 + "' and '" + tarih2 + "'";
else if (Calendar1.SelectedDate != null && Calendar2.SelectedDate == null)
sql += "where RecordDate between '" + tarih1 + "' and '" + DateTime.Now + "'";
sql += ") as toplammsj,";
sql += "(select COUNT(TurkcellID) from SmsStore where TurkcellID=1 ";
if (Calendar1.SelectedDate != null && Calendar2.SelectedDate != null)
sql += "and RecordDate between '" + tarih1 + "' and '" + tarih2+ "'";
else if (Calendar1.SelectedDate != null && Calendar2.SelectedDate == null)
sql += "and RecordDate between '" + tarih1 + "' and '" + DateTime.Now + "'";
sql += ") as giden,";
sql += " (select COUNT(TurkcellID) from SmsStore where TurkcellID=0 ";
if (Calendar1.SelectedDate != null && Calendar2.SelectedDate != null)
sql += "and RecordDate between '" + tarih1 + "' and '" + tarih2 + "'";
else if (Calendar1.SelectedDate != null && Calendar2.SelectedDate == null)
sql += "and RecordDate between '" + tarih1 + "' and '" + DateTime.Now + "'";
sql += ") as gitmeyen from SmsStore ";
if (Calendar1.SelectedDate != null && Calendar2.SelectedDate != null)
sql += "where RecordDate between '" + tarih1+ "' and '" + tarih2 + "'";
else if (Calendar1.SelectedDate != null && Calendar2.SelectedDate == null)
sql += "where RecordDate between '" + tarih1 + "' and '" + DateTime.Now + "'";
SqlDataAdapter adp = new SqlDataAdapter(sql, cnn);
DataTable dt = new DataTable();
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.DataMember = "dt";
}
please help me about this problem.
thanks for all.
Is this a WPF GridView or a Windows Forms DataGridView? The WPF GridView does not have a DataSource property or DataBind() method. And for a DataGridView, you do not need to use DataBind() or set the DataMember property if the DataSource is a DataTable, as you have done.
Also, for debugging purposes put a breakpoint after the line adp.Fill(dt). Put your cursor over dt and examine the properties to determine if Rows.Count is greater than 0. If your SQL is messed up, you might not be getting any data from the database in the first place.

Resources