I am looking to have live data on UI table, I want to get the data from a SQL Server stored procedure that uses a table valued function but I get an invalid subscription error when the dependency change is called.
SqlConnection co = new SqlConnection(_connectionStringTest);
var messages = new List<WorkToListHeaderModel>();
SqlDependency.Stop(_connectionStringTest);
SqlDependency.Start(_connectionStringTest);
using (var cmd = new SqlCommand(#"[DBO].[spTest]", co))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Notification = null;
SqlDataAdapter da = new SqlDataAdapter(cmd);
var dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
messages.Add(item: new WorkToListHeaderModel
{
SalesOrderNumber = ds.Tables[0].Rows[i][0].ToString(),
});
}
}
return messages;
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
MyHub.SendMessages();
}
}
The SQL
ALTER PROCEDURE [dbo].[spTest]
AS
BEGIN
SELECT SalesOrderNumber, Test
FROM dbo.[TableTest]('z')
END
Function
ALTER FUNCTION [dbo].[TableTest]
(#SalesOrderNumber NVARCHAR(100))
RETURNS
#Table TABLE
(
SalesOrderNumber NVARCHAR(100),
Test NVARCHAR(150)
)
AS
BEGIN
;WITH Selects AS
(
SELECT
AdamTest.SalesOrderNumber,
TEST AS CustomerName
FROM
[dbo].[Test]
LEFT JOIN
DBO.Test2 ON Test2.SALESORDERNUMBER = Test.SalesOrderNumber
)
INSERT INTO #Table
SELECT DISTINCT s.SalesOrderNumber, s.CustomerName
FROM Selects AS S
RETURN
I have an sql table that returns financial year start_date and end_date, so now i want to use that query to dropdownlist of months starting from april until march.
And based on the selected month i get the revenue for that month.So the query for calculating financial year only return 2018/04/01 as start_date and 2019/03/31 as end_date, so bare in mind it's not months, just a date .Of course i will be connected to a server and choose my database and table. see what i tried below.
public class Fyear
{
public string FiscalY_Start { get; set; }
public string FiscalY_End { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
//Data Source=cntrra02-sql-rs;Initial Catalog=Training_Database;Integrated Security=True
DateTime start_date;
DateTime end_date;
List<Fyear> list = new List<Fyear>();
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection(#"Data Source=serv_name;Initial Catalog=Database_name;Integrated Security=True");
SqlCommand cmd = new SqlCommand(#"SELECT [ST_FI], [END_FY] FROM [FiscalYear]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
start_date = Convert.ToDateTime(rdr["ST_FI"]);
end_date = Convert.ToDateTime(rdr["END_FY"]);
//DropDownList1.Items.Add(start_date.ToString());
//int count = 0;
while (start_date <= end_date)
{
//count++;
//list.Add(new Fyear{ FiscalY_Start = start_date.ToString("MMMM")});
start_date = start_date.AddMonths(1);
DropDownList1.Items.Add(start_date.ToString());
}
}
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
// DropDownList1.DataSource = dt;
// DropDownList1.DataBind();
}
I am trying to create add button in the gridview. I have 3 joining tables and 3 drop-down lists.
That is the error that I get:
Additional information: Invalid column name 'Quotation_Number'. Invalid column name 'Customer_Name'. Invalid column name 'Machine_Model'.
Can you help me? I think the problem is in the insert statement
Thanks
public void userSales()
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT SalesActivity.Activity_ID, SalesActivity.Date, SalesActivity.Quatation_Number, CUSTOMER.Customer_Name, PRODUCTS.Machine_Model, SalesActivity.Quantity, SalesActivity.valueGBR, SalesActivity.valueEUR, SalesActivity.Rate, SalesActivity.weightedValue, STATUS.Status, SalesActivity.estDecisionDate, SalesActivity.PromisedDeliveryDate FROM SalesActivity INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow()); // if record not found then returning a blank table structure
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex; //this open new index that is edit mode
userSales();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1; //after cancel button want go to one index back that's y -1
userSales();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtActivity = (TextBox)GridView1.FooterRow.FindControl("ftxtActivity");
TextBox ftxtDate = (TextBox)GridView1.FooterRow.FindControl("ftxtDate");
TextBox ftxtQno = (TextBox)GridView1.FooterRow.FindControl("ftxtQno");
DropDownList fddlCName = GridView1.FooterRow.FindControl("fddlCName") as DropDownList;
DropDownList fddlMmodel = GridView1.FooterRow.FindControl("fddlMmodel") as DropDownList;
TextBox ftxtQuantity = (TextBox)GridView1.FooterRow.FindControl("ftxtQuantity");
TextBox ftxtvalueGBR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueGBR");
TextBox ftxtvalueEUR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueEUR");
TextBox ftxtRate = (TextBox)GridView1.FooterRow.FindControl("ftxtRate");
TextBox ftxtweightedValue = (TextBox)GridView1.FooterRow.FindControl("ftxtweightedValue");
DropDownList fddlStatus = GridView1.FooterRow.FindControl("fddlStatus") as DropDownList;
TextBox ftxtestDecisionDate = (TextBox)GridView1.FooterRow.FindControl("ftxtestDecisionDate");
TextBox ftxtPromisedDeliveryDate = (TextBox)GridView1.FooterRow.FindControl("ftxtPromisedDeliveryDate");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Customer_Name, #Machine_Model, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #Status, #estDecisionDate, #PromisedDeliveryDate)", con);
cmd.Parameters.AddWithValue("#Activity_ID", txtActivity.Text.Trim());
cmd.Parameters.AddWithValue("#Date", ftxtDate.Text.Trim());
cmd.Parameters.AddWithValue("#Quotation_Number", ftxtQno.Text.Trim());
cmd.Parameters.AddWithValue("#Customer_Name", fddlCName.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Machine_Model", fddlMmodel.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Quantity", ftxtQuantity.Text.Trim());
cmd.Parameters.AddWithValue("#valueGBR", ftxtvalueGBR.Text.Trim());
cmd.Parameters.AddWithValue("#valueEUR", ftxtvalueEUR.Text.Trim());
cmd.Parameters.AddWithValue("#weightedValue",ftxtweightedValue.Text.Trim());
cmd.Parameters.AddWithValue("#Rate", ftxtRate.Text.Trim());
cmd.Parameters.AddWithValue("#Status", fddlStatus.SelectedItem.Text);
cmd.Parameters.AddWithValue("#estDecisionDate", ftxtestDecisionDate.Text.Trim());
cmd.Parameters.AddWithValue("#PromisedDeliveryDate", ftxtPromisedDeliveryDate.Text.Trim());
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
userSales();
Response.Write("<script language=javascript>alert('" + txtActivity.Text + "'+'Sale Details inserted successfully');</script>");
}
else
{
Response.Write("<script language=javascript>alert('" + txtActivity.Text + "'+' Sale Details not inserted');</script>");
}
}
}
Your Select Statement is executing this...
SELECT SalesActivity.Activity_ID
,SalesActivity.DATE
,SalesActivity.Quatation_Number
,CUSTOMER.Customer_Name
,PRODUCTS.Machine_Model
,SalesActivity.Quantity
,SalesActivity.valueGBR
,SalesActivity.valueEUR
,SalesActivity.Rate
,SalesActivity.weightedValue
,STATUS.STATUS
,SalesActivity.estDecisionDate
,SalesActivity.PromisedDeliveryDate
FROM SalesActivity
INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID
INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID
INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID
Machine_Model and Customer_Name do not belong to SalesActivity Table, they belong to Products and Customer respectively. And your issue with Quotation_Number is Quatation_Number in the select.
change this...
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Customer_Name, #Machine_Model, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #Status, #estDecisionDate, #PromisedDeliveryDate)", con);
to this...
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quatation_Number,Quantity, valueGBR, valueEUR, Rate, weightedValue, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #estDecisionDate, #PromisedDeliveryDate)", con);
and remove the following lines...
cmd.Parameters.AddWithValue("#Customer_Name", fddlCName.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Machine_Model", fddlMmodel.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Status", fddlStatus.SelectedItem.Text);
The insert should now work.
I am trying show some data from a database to a combobox based on another combobox selection with this code:
private void metroComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dt = new DataSet();
try
{
DateTime startDate = Convert.ToDateTime(metroLabel8.Text);
DateTime endDate = Convert.ToDateTime(metroLabel9.Text);
// Make sql readable
string sql =
#"Select [LedId],[LedName] from [Ledger] where Date >= #prmStartDate and Date <= #prmEndDate";
// wrap IDisposable (SqlCommand) into using
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#prmStartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#prmEndDate", SqlDbType.DateTime).Value = endDate;
con.Close();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
VoucherLedgerName_combo.DisplayMember = "LedName";
VoucherLedgerName_combo.ValueMember = "LedId";
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"];
}
}
catch(Exception exe)
{
MessageBox.Show(exe.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
But i am getting nothing in the second combobox, and I am sure that there is data in the database table Ledger. Can any one please help me to find the issue?
change your SQL statement as below(Date is reserved keyword)
string sql =
#"Select [LedId],[LedName] from [Ledger] where [Date] >= #prmStartDate and [Date] <= #prmEndDate";
You need to give table name when you fill dataset since you are using the name when you set data source
da.Fill(dt, "Ledger");
or set the data source as below
VoucherLedgerName_combo.DataSource = dt.Tables[0];
DataRow dr = dt.NewRow();
dr["Ledger"] = "--Select All--";
dt.Rows.InsertAt(dr, 0);
You can change from
da.Fill(dt);
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"];
to
da.Fill(dt, "Ledger");
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"].DefaultView;
else
VoucherLedgerName_combo.DataSource = dt.Tables[0].DefaultView;
or
VoucherLedgerName_combo.DataSource = dt;
I want to insert the (Day,Date,Time) from a Calendar and TimePicker a in my DB but I got this error
"SqlDateTime overflow"
Date access code:
public void InsertExam(SqlCommand cmd)
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "InsertExam";
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
con.Close();
}
Business
public void InsertExam_record()
{
cmd.Parameters.AddWithValue("#EWeekday", EWeekday);
cmd.Parameters.AddWithValue("#BegainTime", BegainTime);
cmd.Parameters.AddWithValue("#EndTime", EndTime);
cmd.Parameters.AddWithValue("#Duration", Duration);
cmd.Parameters.AddWithValue("#DateAD", DateAD);
cmd.Parameters.AddWithValue("#CourseID", CourseID);
cmd.Parameters.AddWithValue("#SemsterID", SemsterID);
dal.InsertExam(cmd);
}
CS
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DateTime dt = DateTime.Parse("08:30 AM");
MKB.TimePicker.TimeSelector.AmPmSpec am_pm;
if (dt.ToString("tt") == "AM")
{
am_pm = MKB.TimePicker.TimeSelector.AmPmSpec.AM;
}
else
{
am_pm = MKB.TimePicker.TimeSelector.AmPmSpec.PM;
}
TimeSelector1.SetTime(dt.Hour, dt.Minute, am_pm);
}
CourseGridView.DataBind();
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox1.Text = Calendar1.SelectedDate.ToString("ddd", new System.Globalization.CultureInfo("ar-SA"));
TextBox2.Text= Calendar1.SelectedDate.ToString("yyyy/MM/dd", new System.Globalization.CultureInfo("ar-SA"));
TextBox3.Text = Calendar1.SelectedDate.ToString("yyyy/MM/dd");
}
protected void Submit(object sender, EventArgs e)
{
DateTime start = DateTime.Parse(string.Format("{0}:{1}", TimeSelector1.Hour, TimeSelector1.Minute));
DateTime end = DateTime.Parse(string.Format("{0}:{1}", TimeSelector2.Hour, TimeSelector2.Minute));
TimeSpan du = end - start;
double r = du.TotalHours;
EndTime.Text = r.ToString();
b.EWeekday = TextBox1.Text;
b.BegainTime = Convert.ToDateTime(start);
b.EndTime = Convert.ToDateTime(end);
b.Duration = Convert.ToInt32(r);
b.DateAD = Convert.ToDateTime(TextBox3.Text);
b.CourseID = Convert.ToInt32(CourseGridView.SelectedValue);
b.SemsterID = Convert.ToInt32(SemsterList.SelectedValue);
b.InsertExam_record();
}
and this is my Stored Procedure
[dbo].[InsertExam]
-- Add the parameters for the stored procedure here
#EWeekday NVARCHAR (50),
#BegainTime Time,
#EndTime Time,
#Duration INT,
#DateAD Date,
#CourseID INT,
#SemsterID INT
AS
BEGIN
INSERT INTO Exam
( EWeekday, BegainTime, EndTime, Duration, DateAD, CourseID, SemsterID)
VALUES (#EWeekday,#BegainTime,#EndTime,#Duration,#DateAD,#CourseID,#SemsterID)
END