I am using DataAdapter("SDM_Tran_GenerateInvoice") inside DataSet("SDMDAL.xsd") in my project.
Below is the structure of DataAdapter along with the Stored Procedure names in it:
Below is the Table structure Im using for the same:
I am calling this DataAdapter inside Class file named as SDM.InvoiceBLL.cs:
using SDMDALTableAdapters;
public class SDM_Invoice
{
private SDM_Tran_GenerateInvoiceTableAdapter _GenerateInvoiceTableAdapter = null;
protected SDM_Tran_GenerateInvoiceTableAdapter Adapter
{
get
{
if (_GenerateInvoiceTableAdapter == null)
_GenerateInvoiceTableAdapter = new SDM_Tran_GenerateInvoiceTableAdapter();
return _GenerateInvoiceTableAdapter;
}
}
#region GET
//to show data in Invoice Grid
public SDMDAL.SDM_Tran_GenerateInvoiceDataTable SelectInvoice(string _SPID)
{
return Adapter.SelectInvoice(_SPID);
}
//to show data in 1st hidden Grid
public SDMDAL.SDM_Tran_GenerateInvoiceDataTable GetInvoiceBillingBySPID(string _SPID)
{
return Adapter.GetInvoiceBillingBySPID(_SPID);
}
//to fetch InvoiceID for unique key generation
public SDMDAL.SDM_Tran_GenerateInvoiceDataTable GetInvoiceID()
{
return Adapter.GetInvoiceID();
}
//to fetch InvoiceNumber for unique key generation
public SDMDAL.SDM_Tran_GenerateInvoiceDataTable GetInvoiceNumber()
{
return Adapter.GetInvoiceNumber();
}
#endregion
public string Insert(string InvoiceID, string SPfoID, string InvoiceLineNo, string InvoiceNo, string InvoiceType, string BillingIDfoID, string BusinessUnit, string DirectCost, string InvfoStatusID, string Status, DateTime Date, string AccountCode)
{
string query = Convert.ToString(Adapter.Insert1(InvoiceNo, SPfoID, InvoiceLineNo, InvoiceNo, InvoiceType, BillingIDfoID, BusinessUnit, DirectCost, InvfoStatusID, Status, Date, AccountCode));
return query;
}
public SDM_Invoice()
{
}
}
and then calling the "Insert" function of class file inside Default.aspx.cs page, to save records on button click:
protected void btnInvoice_Click(object sender, EventArgs e)
{
generateInvoiceId();
generateInvoiceNumber();
string InvType = rlbInvType.SelectedValue;
string Status = "Draft";
string BillingID;
string DirectCost;
string BusinessUnit;
string StatusID;
string AccCode;
foreach (GridDataItem itm in rgData.Items)
{
BillingID = itm["BillingID"].Text;
DirectCost = itm["DCIDescription"].Text;
BusinessUnit = itm["BUName"].Text;
StatusID = itm["BUfoStatusID"].Text;
Label lb = (Label)itm.FindControl("Label1");
string InvLineNo = lb.Text;
try
{
SDM.Invoice.Insert(lblInvId.Text, _SPID, InvLineNo, lblInvNo, InvType, BillingID, BusinessUnit, DirectCost, StatusID, Status, DateTime.Now, AccCode);
}
catch (Exception ex)
{
}
}
}
I rebuilt my project number of times and when I run my web page "Default.aspx.cs", always it gives me below error:
The best overloaded method match for 'SDM_Invoice.Insert(string, string, string, string, string, string, string, string, string, string, System.DateTime, string)' has some invalid arguments
I searched many articles related to my issue but couldn't find any solution for my problem.
This is the first time I am working with TableAdapter. Please help me what is wrong in my code ? What am I missing in it. Thanks in advance.
All the arguments except for the next to last need to be strings, but you seem to be passing some non-string values, for example lblInvNo, which seems to be a user interface element.
Check the type of each argument aside from the next to last, and make sure they are all strings.
Related
I am (trying to) using the sqlite-net-pcl package version 1.8.116, to create a user defined function in C#.
I tried to start simple by creating a function to reverse a string, like REVERSE
When i try the query: SELECT 1,'abc','def',
I am expecting the output to be: 1:abc:fed
But the output is: 0:abc:System.Char[], So I must have done something wrong...
Can anyone give a tip? because I am pretty clueless right now... 😉
My code:
SQLiteConnection db = new SQLiteConnection("test.db");
// https://sqlite.org/c3ref/create_function.html
sqlite3 dbhandle = db.Handle;
string function = "myReverse";
int narg = 1;
int eTextRep = SQLitePCL.raw.SQLITE_UTF8 | SQLitePCL.raw.SQLITE_DETERMINISTIC;
int ok = SQLitePCL.raw.sqlite3_create_function(dbhandle, function, narg, eTextRep, myReverse);
//Console.WriteLine($"OK:{ok}");
SQLiteCommand cmd = db.CreateCommand("SELECT 1 as id, 'abc' as t, myReverse('def') as revt");
var result = cmd.ExecuteQuery<Record>();
Console.WriteLine($"{result[0].id}:{result[0].t}:{result[0].revt}");
and:
static void myReverse(sqlite3_context ctx, object user_data, sqlite3_value[] args)
{
SQLitePCL.utf8z utf8z = raw.sqlite3_value_text(args[0]);
string input = utf8z.utf8_to_string();
//Console.WriteLine($"INPUT:{input}"); // This shows INPUT:def
char[] charArray = input.ToCharArray();
Array.Reverse(charArray);
//raw.sqlite3_result_text(ctx, utf8z.FromString(charArray.ToString())); // see: comments...
raw.sqlite3_result_text(ctx, utf8z.FromString(new string(charArray)));
}
Record:
public class Record
{
public int id { get; set; }
public string t { get; set; }
public string revt { get; set; }
}
Above was my first try, finally I would like to have an implementation of the function LIKE, like is mentioned in paragraph 5 "The infix LIKE operator is implemented by calling the application-defined SQL functions"
Currently returning a string is working, but I am looking for something like raw.sqlite3_result_boolean, or raw.sqlite3_result_logical, because the return value for the function LIKE is a boolean.
I am reading rows from a table in SQL Server using C# in SSIS. As I loop through each column I want to get the datatype of the field from the table. Here is my code:
string s = "";
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\Users\cassf\Documents\Tyler Tech\FL\ncc3\CM_Property.csv", true))
{
foreach (PropertyInfo inputColumn in Row.GetType().GetProperties())
{
if (!inputColumn.Name.EndsWith("IsNull"))
{
try
{
s += Convert.ToString(inputColumn.GetValue(Row,null).ToString());
}
catch
{
some code
}
}
}
}
}
First issue is when I do the Convert.ToString() on a Bit field from the database, it changes the value to either True or False. I want the actual value of 1 or 0.
So to try and fix this I want to check the field type for Boolean, it appears that the script is converting from a bit to boolean. Then I can manually put the 1 or 0 back. I would prefer to have the value directly from the database though.
Any help would be greatly appreciated.
Thanks,
Kent
I'd implement a helper function to make your own conversion, when needed, like this:
string s = "";
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\Users\cassf\Documents\Tyler Tech\FL\ncc3\CM_Property.csv", true))
{
foreach (PropertyInfo inputColumn in Row.GetType().GetProperties())
{
if (!inputColumn.Name.EndsWith("IsNull"))
{
try
{
s += ValueToString(inputColumn.GetValue(Row,null));
}
catch
{
some code
}
}
}
}
}
protected string ValueToString(object value)
{
if (value == null)
throw new ArgumentNullException("I don't know how to convert null to string, implement me!");
switch (Type.GetTypeCode(value.GetType()))
{
// Any kind of special treatment, you implement here...
case TypeCode.Boolean: return Convert.ToInt16(value).ToString();
default: return value.ToString(); // ...otherwise, just use the common conversion
}
}
For booleans, you just convert it to Int, and the int to string (you'll get 1 or 0 in string format).
Depending on what you're going to do with the s variable, you might want to surround string values with quotes, if so, you could do it inside ValueToString() method.
I have a dropdownlist on a web form that has an item name and a price associated with it (which is not visible to the user). I am using selecteditem.Text and selectedvalue to capture the item name and the price. To combat duplicate entries for the selectedvalue I am storing entries like so
Signed Cap 10.0
Signed Glove 10.1
Signed Shirt 10.2
Bat Shavings .50
Hat Brim .50
Then parsing it out by using the below
String[] str = dropdownlist1.SelectedValue.ToString().Split('.');
String itemprice = str[0].Trim();
My syntax works great, EXCEPT for the decimal values! On Bat Shavings and Hat Brim I need to retain the decimal value! What should I alter or how should I set up my syntax to allow duplicate selected values or to keep the decimals? I understand that using str[0] is what is causing me to loose the decimals, BUT how can I work around it for the 2 (possibly more in the future) scenarios where they need to be remain in tact?
Its hard to tell from your posting how your getting your data, but I would load my data from the database into a data object, then bind that object to the drop down list.
Here is the Inventory Class I used to store the data from the database:
public class Inventory
{
public int ProductID { get; set; }
public string ProductDescription { get; set; }
public decimal ProductPrice { get; set; }
public Inventory(int ID, string Description, decimal Price)
{
this.ProductID = ID;
this.ProductDescription = Description;
this.ProductPrice = Price;
}
public string DDLValue
{
get
{
return string.Format("{0}|{1}|{2}", ProductID, ProductDescription, ProductPrice);
}
}
public string DDLText
{
get
{
return string.Format("{0} [{1}]", ProductDescription, ProductPrice.ToString("C"));
}
}
}
Here is a sample of how to configure the page control:
<asp:DropDownList ID="ddlProducts" runat="server" DataValueField="DDLValue" DataTextField="DDLText" />
In the page code behind, load your data into the drop down:
protected void LoadProductsFromDatabase()
{
System.Collections.Generic.List<Inventory> My_DDL_Datasource = new System.Collections.Generic.List<Inventory>();
// write your code to pull database values
// populating list with sample data for stackoverflow
// make sure to use a replace statement to remove any delimiter characters that may be in the description
My_DDL_Datasource.Add(new Inventory(1, "Product 1".Replace("|", ""), 0.50m));
My_DDL_Datasource.Add(new Inventory(2, "Product 2".Replace("|", ""), 1.50m));
My_DDL_Datasource.Add(new Inventory(3, "Product 3".Replace("|", ""), 0.50m));
My_DDL_Datasource.Add(new Inventory(4, "Product 4".Replace("|", ""), 10.50m));
ddlProducts.DataSource = My_DDL_Datasource;
ddlProducts.DataBind();
}
In the page code behind, create a method to get your drop down list selected value:
protected Inventory GetSelectedProduct()
{
try
{
if (ddlProducts.Items.Count == 0)
{
// do nothing, fall thru will return null
}
else
{
string[] DDLValue = ddlProducts.SelectedValue.Split('|');
int ivalue = 0;
int.TryParse(DDLValue.GetValue(0).ToString(), out ivalue);
decimal dvalue = 0.00m;
decimal.TryParse(DDLValue.GetValue(2).ToString(), out dvalue);
// only return object if the productid and product price were successfully parsed.
// this logic assumes no products are free
if (ivalue > 0 && dvalue > 0.00m)
{
return new Inventory(ivalue, DDLValue.GetValue(1).ToString(), dvalue);
}
}
}
catch { }
return null;
}
In the page code behind, do something with your selected value:
protected void DoSomethingWithValue()
{
Inventory MyInventoryItem = GetSelectedProduct();
if (MyInventoryItem != null)
{
// selected item successfully parsed
// do something with it.
Response.Write(
string.Format("Your selected product:<br />{0}<br />UniqueID: {1}<br />Price: {2}",
Server.HtmlEncode(MyInventoryItem.ProductDescription),
MyInventoryItem.ProductID,
MyInventoryItem.ProductPrice.ToString("C")
));
}
else
{
// error parsing information stored in drop down list value
}
}
You can split on space, and always take the last entry using linq:
dropdownlist1.SelectedValue.ToString().Split(' ').Last();
Note you should be using a hidden ItemId as the selectedvalue, instead of item name and price, and use a lookup table of:
ItemId|Name|Price
1|Hat|.50
2|Bat Shavings|.50
...
When the selected id is submitted you can lookup the name and price more directly. Also, the price being hidden in a form doesn't prevent the user from manipulating the price.
You need to remove/replace all alpha characters from string and keep only numeric.
Regex rgx = new Regex("[^a-zA-Z]");
str = rgx.Replace(str, "").Trim();
decimal prc;
Decimal.TryParse(str, out prc);
I'm trying to loop through the DataGridView rows and then send the values for an update in my SQL-DB. I can make the update, but the program crashes when I come to the end of the rows, because then it read a null-value.
Exception: System.NullReferenceException, Additional information: Object reference not set to an instance of an object.
I have two questions:
Why can't I stop the method with return (see below) with my if
statement?
How can I let the loop insert null values in the strings? Some of
my columns it's OK to send null-values to. And some not, is there
any way to choose which?
private void editEmployeeDGV()
{
foreach (DataGridViewRow row in employeeDataGridView.Rows)
{
if (row.Cells["SocialSNColumn"].Value.ToString() == null)
{
return;
}
string SocialSN = row.Cells["SocialSNColumn"].Value.ToString();
string Name = row.Cells["nameColumn"].Value.ToString();
string Surname = row.Cells["SurnameColumn"].Value.ToString();
string Email = row.Cells["EmailColumn"].Value.ToString();
string TelNr = row.Cells["TelNrColumn"].Value.ToString();
string Gender = row.Cells["GenderColumn"].Value.ToString();
string ECName = row.Cells["ECNameColumn"].Value.ToString();
string ECNumber = row.Cells["ECNumberColumn"].Value.ToString();
cont.editEmployeeDGV(SocialSN, Name, Surname, Email, TelNr, Gender, ECName, ECNumber);
}
}
The reason for the exception is that you're trying to call the ToString() method on the Value property, but it's null.
if (row.Cells["SocialSNColumn"].Value.ToString() == null)
{
return;
}
There's no reason to cast to a string first; just test for null:
if (row.Cells["SocialSNColumn"].Value == null)
{
return;
}
Your other lines of code run the same risk of throwing an NRE if any of their Value properties are null. To avoid those, you may want to replace ToString() with the Convert.ToString() method, which replaces null with an empty string:
string SocialSN = Convert.ToString(row.Cells["SocialSNColumn"].Value);
string Name = Convert.ToString(row.Cells["nameColumn"].Value);
I have a C# application (WinForm) that gets some information into several DataSets. From the datasets I save the information to a few string and int variables. Sometimes the values are null.. SO I would like to make a function that checks for nulls before trying to store into variables so I won't get any errors.
So in short I would like to replace a code like this(presuming I already have 2 DataSets called "dataSet1" and "dataSet2"):
row1 = dataSet1.Tables[0].Rows[0];
if(row1.IsNull("Department")) {errorMsg}
else if(row1.IsNull("Name")) {errorMsg}
else
//run code
row2 = dataSet2.Tables[0].Rows[0];
if(row2.IsNull("Department")) {errorMsg}
else if(row2.IsNull("Name")) {errorMsg}
else
//run code
to something more automated like:
//the function
bool NullChecker(string datasetName, int rowNr, string fieldName)
{
if(datasetName.Tables[0].Rows[rowNr].IsNull(fieldName)) return false;
else return true;
}
//back in the code
string[] datasetNames; int[] rowNrs; string[] fieldNames;
for(int i=0; i<someLength; i++)
{ NullChecker(datasetNames[i], rowNrs[i], fieldNames[i]);}
Possible? Also do you think this might slow down my code?
You can create an extension method for null checking
public static class Extensions
{
public static bool IsNull(this DataSet dataSet, int rowNumber, string columnName)
{
return dataSet.Tables[0].Rows[rowNumber].IsNull(columnName);
}
}
Then you can use it like
dataSet1.IsNull(0, "column");
If you want to print error messages as well, just add a parameter string errorMsg and before you return from the method call, print a text passed through an argument, like as follows
public static bool IsNull(this DataSet dataSet, int rowNumber, string columnName, string errorMsg)
{
if(dataSet.Tables[0].Rows[rowNumber].IsNull(columnName))
{
// print an error message using Console or MessageBox, or whatever you use
return true;
}
return false;
}
and then you can use it like
dataSet1.IsNull(0, "column", "error");
Seems the code is good enough, with a small edit, need to replace the string array datasetName with a Database[] array.
if (dataSet1 != null && dataSet1.Tables.Count > 0)
----further do actions