System.IndexOutOfRangeException: 'Cannot find column 2.' - c#

Can you help me. Im getting error from this where I get out of range exception. I've checked the Column name "fYearLevel" same as what I've put into the query and they also have the same data type.
sql = "SELECT fName, fCourse, fYearLevel, fMajor, fScholarship, fBirthdate, fEmailAddress, fAddress, fContactNo FROM tblstudents WHERE fIDno = #id";
List<MySqlParameter> paramList = new List<MySqlParameter>();
paramList.Add(new MySqlParameter("#id", txtIDNo.Text));
config.ParametersCommand(sql, paramList);
dtgStudents.DataSource = config.dt;
if (config.dt.Rows.Count > 0)
{
txtName.Text = config.dt.Rows[0].Field<string>(0);
cmbCourse.Text = config.dt.Rows[0].Field<string>(1);
cmbYearLevel.Text = config.dt.Rows[0].Field<int>(2).ToString();// error here
cmbMajor.Text = config.dt.Rows[0].Field<string>(3);
cmbScholarship.Text = config.dt.Rows[0].Field<string>(4);
dateTimeBirthdate.Text = config.dt.Rows[0].Field<DateTime>(5).ToString();
txtEmail.Text = config.dt.Rows[0].Field<string>(6);
txtAddress.Text = config.dt.Rows[0].Field<string>(7);
txtContactNo.Text = config.dt.Rows[0].Field<string>(8);
}
I also set my data source to my datagridview and its works fine. Only when it goes to setting where I got my error
It gets out of range exception and cannot find the column but if I remove Column "fCourse" it works fine.
sql = "SELECT fName, fCourse, fYearLevel, fMajor, fScholarship, fBirthdate, fEmailAddress, fAddress, fContactNo FROM tblstudents WHERE fIDno = #id";
List<MySqlParameter> paramList = new List<MySqlParameter>();
paramList.Add(new MySqlParameter("#id", txtIDNo.Text));
config.ParametersCommand(sql, paramList);
dtgStudents.DataSource = config.dt;
if (config.dt.Rows.Count > 0)
{
txtName.Text = config.dt.Rows[0].Field<string>(0);
//cmbCourse.Text = config.dt.Rows[0].Field<string>(1);
cmbYearLevel.Text = config.dt.Rows[0].Field<int>(2).ToString();// all data down will be set
cmbMajor.Text = config.dt.Rows[0].Field<string>(3);
cmbScholarship.Text = config.dt.Rows[0].Field<string>(4);
dateTimeBirthdate.Text = config.dt.Rows[0].Field<DateTime>(5).ToString();
txtEmail.Text = config.dt.Rows[0].Field<string>(6);
txtAddress.Text = config.dt.Rows[0].Field<string>(7);
txtContactNo.Text = config.dt.Rows[0].Field<string>(8);
}

Related

Select records for one day to 30 days C#

I want to get records for 1 day to 30 days the Query is working in SQL properly
SELECT * FROM Tbl_order WHERE date >= DATEADD(day, -1, GETDATE())
so what i did in C# i use combo box
int CmboDays;
for (CmboDays = -1; CmboDays >= -30; CmboDays--)
{
comboBox1.Items.Add(CmboDays);
}
private void orderBySearchDays()
{
string c = comboBox1.Text;
int x = Convert.ToInt32(c);
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select* from Tbl_order WHERE date >= DATEADD(day,'"+ x + "', GETDATE()) ; ", connection))
{
DataTable Tbl_order = new DataTable();
connection.Open(); //opens the connection
adapter.Fill(Tbl_order);
connection.Close(); //Closes the connection
lst_CustomerNo.DataSource = Tbl_order; //assigns a datasource
lst_CustomerNo.DisplayMember = "CustomerNo"; //assigns display
lst_CustomerNo.ValueMember = "CustomerNo";
lst_OrderName.DataSource = Tbl_order;
lst_OrderName.DisplayMember = "OrderName";
lst_OrderName.ValueMember = "OrderName";
lst_Quantity.DataSource = Tbl_order;
lst_Quantity.DisplayMember = "Quantity";
lst_Quantity.ValueMember = "Quantity";
lst_Price.DataSource = Tbl_order;
lst_Price.DisplayMember = "Price";
lst_Price.ValueMember = "Price";
lst_datetime.DataSource = Tbl_order;
lst_datetime.DisplayMember = "Date";
lst_datetime.ValueMember = "Date";
}
}
so all the data will be display in list box
i'm getting this Error
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Argument data type varchar is invalid for argument 2 of dateadd function.
Am I doing it that Wrong ?
How to fix the Error ?
could you chnage x with x.ToString() and remove '
using (SqlDataAdapter adapter = new SqlDataAdapter("select * from Tbl_order WHERE date >= DATEADD(day,"+ x.ToString() + ", GETDATE()) ; ", connection))

ORA-01036: illegal variable name/number while updating gridview

I want to update a cell of the row in gridview. But I am getting error as
ORA-01036: illegal variable name/number
at cmd.ExecuteNonQuery()
Here is my code below:-
protected void SaveChanges(object sender, EventArgs e)
{
myConn.Open();
string excelData = Grid1ExcelData.Value;
string excelDeletedIds = Grid1ExcelDeletedIds.Value;
string[] rowSeparator = new string[] { "|*row*|" };
string[] cellSeparator = new string[] { "|*cell*|" };
string[] dataRows = excelData.Split(rowSeparator, StringSplitOptions.None);
for (int i = 0; i < dataRows.Length; i++)
{
string[] dataCells = dataRows[i].Split(cellSeparator, StringSplitOptions.None);
string mkey = dataCells[0];
string shipName = dataCells[1];
string shipCity = dataCells[2];
string shipAddress = dataCells[3];
string shipCountry = dataCells[4];
string orderDate = dataCells[5];
bool sent = dataCells[6] == "yes";
string insertUpdateQuery = "";
if (!string.IsNullOrEmpty(mkey))
{
insertUpdateQuery = "UPDATE B_Order_new SET ShipName = #ShipName, ShipCity = #ShipCity, ShipAddress = #ShipAddress, ShipCountry = #ShipCountry, OrderDate = #OrderDate, Sent = #Sent WHERE MKEY = #MKEY";
}
else
{
insertUpdateQuery = "INSERT INTO B_Order_new (ShipName, ShipCity, ShipAddress, ShipCountry, OrderDate, Sent) " +
"VALUES(#ShipName, #ShipCity, #ShipAddress, #ShipCountry, #OrderDate, #Sent)";
}
OracleCommand cmd = new OracleCommand(insertUpdateQuery, myConn);
var orderedOn = DateTime.ParseExact(orderDate, "dd/MM/yyyy", null);
cmd.Parameters.Add("#ShipName", OracleType.VarChar).Value = shipName;
cmd.Parameters.Add("#ShipCity", OracleType.VarChar).Value = shipCity;
cmd.Parameters.Add("#ShipAddress", OracleType.VarChar).Value = shipAddress;
cmd.Parameters.Add("#ShipCountry", OracleType.VarChar).Value = shipCountry;
cmd.Parameters.Add("#OrderDate", OracleType.DateTime).Value = orderedOn;
cmd.Parameters.Add("#Sent", OracleType.Char).Value = true;
if (!string.IsNullOrEmpty(mkey))
{
cmd.Parameters.Add("#MKEY", OracleType.Number).Value = mkey;
}
cmd.ExecuteNonQuery();
if (insertUpdateQuery != "")
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "CloseScript", "alert('Data Updated succesfully');", true);
}
}
if (!string.IsNullOrEmpty(excelDeletedIds))
{
OracleCommand deleteComm = new OracleCommand("DELETE FROM Orders WHERE OrderID IN (" + excelDeletedIds + ")", myConn);
deleteComm.ExecuteNonQuery();
}
myConn.Close();
Grid1.DataBind();
}
The problem is that you are using the wrong bind variable syntax (looks like you're using SQL Server parameter binding syntax). Oracle's ADO.NET provider expects you to use a : prefix rather than a #.
So try something like this instead:
insertUpdateQuery = "UPDATE B_Order_new SET ShipName = :ShipName, ShipCity = :ShipCity, ...
And then when setting the values, you don't need to prefix it:
cmd.Parameters.Add("ShipName", OracleType.VarChar).Value = shipName;
cmd.Parameters.Add("ShipCity", OracleType.VarChar).Value = shipCity;
...
EDIT
Also, if you are binding the parameters by name, make sure you set the OracleCommand.BindByName property to true. Otherwise, the binding will be done positionally.

Slow data Selection from MDB file to C# Desktop application

Although everything is correct, but data selection process is very slow in my Application, while retriving data from access .mdb file. Is there any idea that data can be accessed fast. Is there any mechanism??
This below code Runs when Button Clicked .
public class GetData {
OleDbConnection con = new OleDbConnection(DatabseConnection.ConnectionStringAccessDatabase);
public string lblPolicyNumber, lblInsuredName, lblIssuedDatePolicy, lblStatusPolicy,
lblModalPremium, lblDueDate, lblNextDueDate, lblAgentCode,
lblMode, lblType1, lblAmount1, lblDate1, lblPremAmt1,
lblDueDate1, lbPaidDate1, lblPremAmt2, lblDueDate2,
lblPaidDate2, lblPremAmt3, lbDueDate3, lblPadiDate3,
lblOwnersName, lblOwnersCode, lblAddress1, lblAddress2,
lblPlan, lblCoverageAmt, lblSex, lblBirthDate, lblAge,
lblAutomaticPrmloan, lblAPLCount, lblLoanType, lblLoanPrincipleamt,
lblLoanDate, lblRatedNotRated, lblUnderWritingApproved , LateFee,
TotalAmountDue, AmountInDeposit, NetPayableAmount, Overdueprem,
CurrentPremiumDue, lblPMFlastUpdated = null;
public void getData(string policyNumber)
{
try
{
con.Open();
}
catch { MessageBox.Show("Please Download the File From the Server, Or Contact IT Department"); }
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = "(Select capolnum, cainame, iss_dte, castatus, mod_prm, due_dte1, nxt_due, agent_code, cabmode, casustyp1, casusamt1, casusdate1, chbldpm1, pd_dte1, chbldpm2, due_dte2, pd_dte2, chbldpm3, due_dte3, pd_dte3 , caoname, ocode, Addr1, addr2, plan, cbcovamt, cbsex, birth_dte, cbissage, apl, as400_cl_aplcnt, as400_cl_lntype, as400_cl_lnprinc, apl_date, cstype, approved FROM agy_pmf where capolnum ='" + policyNumber + "' )";
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
SetData.lblPolicyNumber = lblPolicyNumber = dr.GetValue(0).ToString();
SetData.lblInsuredName = lblInsuredName = dr.GetValue(1).ToString();
lblIssuedDatePolicy = dr.GetValue(2).ToString();
lblStatusPolicy = dr.GetValue(3).ToString();
lblModalPremium = dr.GetValue(4).ToString();
lblDueDate = dr.GetValue(6).ToString();
lblNextDueDate = dr.GetValue(6).ToString();
lblAgentCode = dr.GetValue(7).ToString();
SetData.lblMode = lblMode = dr.GetValue(8).ToString();
lblType1 = dr.GetValue(9).ToString();
lblAmount1 = dr.GetValue(10).ToString();
lblDate1 = dr.GetValue(11).ToString();
lblPremAmt1 = dr.GetValue(12).ToString();
lblDueDate1 = dr.GetValue(5).ToString();
lbPaidDate1 = dr.GetValue(13).ToString();
lblPremAmt2 = dr.GetValue(14).ToString();
lblDueDate2 = dr.GetValue(15).ToString();
lblPaidDate2 = dr.GetValue(16).ToString();
lblPremAmt3 = dr.GetValue(17).ToString();
lbDueDate3 = dr.GetValue(18).ToString();
lblPadiDate3 = dr.GetValue(19).ToString();
lblOwnersName = dr.GetValue(20).ToString();
lblOwnersCode = dr.GetValue(21).ToString();
lblAddress1 = dr.GetValue(22).ToString();
lblAddress2 = dr.GetValue(23).ToString();
lblPlan = dr.GetValue(24).ToString();
lblCoverageAmt = dr.GetValue(25).ToString();
lblSex = dr.GetValue(26).ToString();
lblBirthDate = dr.GetValue(27).ToString();
lblAge = dr.GetValue(28).ToString();
lblAutomaticPrmloan = dr.GetValue(29).ToString();
lblAPLCount = dr.GetValue(30).ToString();
lblLoanType = dr.GetValue(31).ToString();
lblLoanPrincipleamt = dr.GetValue(32).ToString();
lblLoanDate = dr.GetValue(33).ToString();
lblRatedNotRated = dr.GetValue(34).ToString();
lblUnderWritingApproved = dr.GetValue(35).ToString();
con.Close();
}
}}

Calculating columns in a listview

I am new to programming and I have a price list in a list view, I would like to have another column that calculates the last column and a textbox together, please point me in the right direction as I am getting method and format errors.. here is my code:
listView1.Items.Clear();
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:xxxx;Persist Security Info=False");
OleDbCommand command = connection.CreateCommand();
if (comboBox1.Text == "Brickcom")
{
ListViewItem li;
command.CommandText = "SELECT [PartNo], [Category], [Product], [Resolution], [IncludedAccessories], [Price] FROM [Brickcom] WHERE ([Manufacturer] Like '" + comboBox1.Text.ToString() + "')";
connection.Open();
OleDbDataReader reader = command.ExecuteReader(CommandBehavior.Default);
while (reader.Read())
{
listView1.Columns[0].Text = null;
listView1.Columns[1].Text = null;
listView1.Columns[2].Text = null;
listView1.Columns[3].Text = null;
listView1.Columns[4].Text = null;
listView1.Columns[5].Text = null;
listView1.Columns[6].Text = null;
listView1.Columns[7].Text = null;
listView1.Columns[8].Text = null;
listView1.Columns[0].Text = "Part Number";
listView1.Columns[1].Text = "Category";
listView1.Columns[2].Text = "Product";
listView1.Columns[3].Text = "Resolution";
listView1.Columns[4].Text = "Included Accessories";
listView1.Columns[5].Text = "Price";
li = listView1.Items.Add(reader[0].ToString());
li.SubItems.Add(reader[1].ToString());
li.SubItems.Add(reader[2].ToString());
li.SubItems.Add(reader[3].ToString());
li.SubItems.Add(reader[4].ToString());
li.SubItems.Add(reader[5].ToString());
foreach (ListViewItem item in listView1.Items)
{
li.SubItems.Add(items[6].ToString());
//listView1.Columns[6].Text = (Int32.Parse(textBox1.Text) * Int32.Parse(textBox2.Text)).ToString();
item.SubItems[6].Text = (Int32.Parse(textBox1.Text) * Int32.Parse(textBox2.Text)).ToString();
}
}
connection.Close();
}

Trouble updating my datagrid in WPF

As the title indicates, I'm having trouble updating a datagrid in WPF. Basically what I'm trying to accomplish is a datagrid, that is connected to a SQL Server database, that updates automatically once a user enters information into a few textboxes and clicks a submit button. You'll notice that I have a command that joins two tables. The data from the Quote_Data table will be inserted by a different user at a later time. For now my only concern is getting the information from the textboxes and into the General_Info table, and from there into my datagrid. The code, which I'll include below compiles fine, but when I hit the submit button, nothing happens. This is the first application I've ever built working with a SQL Database so many of these concepts are new to me, which is why you'll probably look at my code and wonder what is he thinking.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public DataSet mds; // main data set (mds)
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
try
{
string connectionString = Sqtm.Properties.Settings.Default.SqtmDbConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//Merging tables General_Info and Quote_Data
SqlCommand cmd = new SqlCommand("SELECT General_Info.Quote_ID, General_Info.Open_Quote, General_Info.Customer_Name,"
+ "General_Info.OEM_Name, General_Info.Qty, General_Info.Quote_Num, General_Info.Fab_Drawing_Num, "
+ "General_Info.Rfq_Num, General_Info.Rev_Num, Quote_Data.MOA, Quote_Data.MOQ, "
+ "Quote_Data.Markup, Quote_Data.FOB, Quote_Data.Shipping_Method, Quote_Data.Freight, "
+ "Quote_Data.Vendor_Price, Unit_Price, Quote_Data.Difference, Quote_Data.Vendor_NRE_ET, "
+ "Quote_Data.NRE, Quote_Data.ET, Quote_Data.STI_NET, Quote_Data.Mfg_Time, Quote_Data.Delivery_Time, "
+ "Quote_Data.Mfg_Name, Quote_Data.Mfg_Location "
+ "FROM General_Info INNER JOIN dbo.Quote_Data ON General_Info.Quote_ID = Quote_Data.Quote_ID",
connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
MainGrid.ItemsSource = dt.DefaultView;
mds = new DataSet();
da.Fill(mds, "General_Info");
MainGrid.DataContext = mds.Tables["General_Info"];
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// renaming column names from the database so they are easier to read in the datagrid
MainGrid.Columns[0].Header = "#";
MainGrid.Columns[1].Header = "Date";
MainGrid.Columns[2].Header = "Customer";
MainGrid.Columns[3].Header = "OEM";
MainGrid.Columns[4].Header = "Qty";
MainGrid.Columns[5].Header = "Quote Number";
MainGrid.Columns[6].Header = "Fab Drawing Num";
MainGrid.Columns[7].Header = "RFQ Number";
MainGrid.Columns[8].Header = "Rev Number";
MainGrid.Columns[9].Header = "MOA";
MainGrid.Columns[10].Header = "MOQ";
MainGrid.Columns[11].Header = "Markup";
MainGrid.Columns[12].Header = "FOB";
MainGrid.Columns[13].Header = "Shipping";
MainGrid.Columns[14].Header = "Freight";
MainGrid.Columns[15].Header = "Vendor Price";
MainGrid.Columns[16].Header = "Unit Price";
MainGrid.Columns[17].Header = "Difference";
MainGrid.Columns[18].Header = "Vendor NRE/ET";
MainGrid.Columns[19].Header = "NRE";
MainGrid.Columns[20].Header = "ET";
MainGrid.Columns[21].Header = "STINET";
MainGrid.Columns[22].Header = "Mfg. Time";
MainGrid.Columns[23].Header = "Delivery Time";
MainGrid.Columns[24].Header = "Manufacturer";
MainGrid.Columns[25].Header = "Mfg. Location";
}
private void submitQuotebtn_Click(object sender, RoutedEventArgs e)
{
CustomerData newQuote = new CustomerData();
int quantity;
quantity = Convert.ToInt32(quantityTxt.Text);
string theDate = System.DateTime.Today.Date.ToString("d");
newQuote.OpenQuote = theDate;
newQuote.CustomerName = customerNameTxt.Text;
newQuote.OEMName = oemNameTxt.Text;
newQuote.Qty = quantity;
newQuote.QuoteNumber = quoteNumberTxt.Text;
newQuote.FdNumber = fabDrawingNumberTxt.Text;
newQuote.RfqNumber = rfqNumberTxt.Text;
newQuote.RevNumber = revNumberTxt.Text;
try
{
string insertConString = Sqtm.Properties.Settings.Default.SqtmDbConnectionString;
using (SqlConnection insertConnection = new SqlConnection(insertConString))
{
insertConnection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(Sqtm.Properties.Settings.Default.SqtmDbConnectionString, insertConnection);
SqlCommand updateCmd = new SqlCommand("UPDATE General_Info " + "Quote_ID = #Quote_ID, "
+ "Open_Quote = #Open_Quote, " + "OEM_Name = #OEM_Name, " + "Qty = #Qty, "
+ "Quote_Num = #Quote_Num, " + "Fab_Drawing_Num = #Fab_Drawing_Num, "
+ "Rfq_Num = #Rfq_Num, " + "Rev_Num = #Rev_Num "
+ "WHERE Quote_ID = #Quote_ID");
updateCmd.Connection = insertConnection;
System.Data.SqlClient.SqlParameterCollection param = updateCmd.Parameters;
//
// Add new SqlParameters to the command.
//
param.AddWithValue("Open_Quote", newQuote.OpenQuote);
param.AddWithValue("Customer_Name", newQuote.CustomerName);
param.AddWithValue("OEM_Name", newQuote.OEMName);
param.AddWithValue("Qty", newQuote.Qty);
param.AddWithValue("Quote_Num", newQuote.QuoteNumber);
param.AddWithValue("Fab_Drawing_Num", newQuote.FdNumber);
param.AddWithValue("Rfq_Num", newQuote.RfqNumber);
param.AddWithValue("Rev_Num", newQuote.RevNumber);
adapter.UpdateCommand = updateCmd;
adapter.Update(mds.Tables[0]);
mds.AcceptChanges();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks in advance to anyone who can help, I really appreciate it,
Andrew
You are not setting the Quote_ID parameter. So your update it likely running WHERE Quote_ID = null so nothing updates.
using LINQ I was able to resolve the issue. Here's the code:
var sqtmDC = new SqtmLinqDataContext();
var mainTable = from generalInfo in sqtmDC.GetTable<General_Info>()
//join quoteData in sqtmDataContext.GetTable<Quote_Data>() on generalInfo.Quote_ID equals quoteData.Quote_ID
select generalInfo;
myGrid.ItemsSource = mainTable;
}
private void submitBtn_Click(object sender, RoutedEventArgs e)
{
var sqtmDC = new SqtmLinqDataContext();
// string theDate = System.DateTime.Today.Date.ToString("d");
int quantity = Convert.ToInt32(quantityTxt.Text);
General_Info insert = new General_Info();
insert.Open_Quote = DateTime.UtcNow;
insert.Customer_Name = customerNameTxt.Text;
insert.OEM_Name = oemNameTxt.Text;
insert.Qty = quantity;
insert.Quote_Num = quoteNumberTxt.Text;
insert.Fab_Drawing_Num = fabDrawingNumTxt.Text;
insert.Rfq_Num = rfqNumberTxt.Text;
insert.Rev_Num = revNumberTxt.Text;
sqtmDC.General_Infos.InsertOnSubmit(insert);
sqtmDC.SubmitChanges();
int quoteID = insert.Quote_ID;
var mainTable = from generalInfo in sqtmDC.GetTable<General_Info>()
select generalInfo;
myGrid.ItemsSource = mainTable;
Are you trying to update an existing row or insert a new row?
Cause if you need to insert then the proper command is insert (not update).
To get the Identity value of the inserted row you use Scope_Identity().
And you can only insert into one table at a time.
Scope_Identity() is NOT a param
Do not try and use it as a param
See example below
INSERT INTO Sales.Customer ([TerritoryID],[PersonID]) VALUES (8,NULL);
GO
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];
There are lots of examples on MSDN.Microsoft.com

Categories

Resources