Actually commas are perfectly executed in the text box. 12345=12,345
However my submit button is not functioning well when i am declaring the javascrip with my textbox:
<asp:TextBox ID="txtProductPrice" runat="server" class="form-control" MaxLength ="6" onkeyup ="javascript:this.value=Comma(this.value);"></asp:TextBox>
here is my button code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (uploadProductPhoto.PostedFile != null)
{
SaveProductPhoto();
ShoppingCart k = new ShoppingCart()
{
ProductName = txtProductName.Text,
ProductImage = "~/ProductImages/" + uploadProductPhoto.FileName,
ProductPrice = txtProductPrice.Text,
ProductDescription = txtProductDescription.Text,
CategoryID = Convert.ToInt32(ddlCategory.SelectedValue),
TotalProducts = Convert.ToInt32(txtProductQuantity.Text)
};
k.AddNewProduct();
ClearText();
Label2.Text = "Product Added!";
//Response.Redirect("AddNewProduct.aspx?alert=success");
}
else
{
Response.Write("<script>alert('Please upload photo');</script>");
The code is finished ("Product Added" is showing up) however, the product is not actually added. its not in the database or anywhere. any tricks on this?
here is the k.AddNewProduct();
ALTER PROCEDURE [dbo].[SP_AddNewProduct]
(
#ProductName varchar(300),
#ProductPrice varchar(500),
#ProductImage varchar(500),
#ProductDescription varchar(1000),
#CategoryID int,
#ProductQuantity int
)
AS
BEGIN
BEGIN TRY
Insert into products
values
(#ProductName,
#ProductDescription,
#ProductPrice,
#ProductImage,
#CategoryID,
#ProductQuantity
)
END TRY
BEGIN CATCH
PRINT ('Error Occured')
END CATCH
END
I have js by using simplified regex
function Comma(Num) {
var parts = Num.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
if you also need support for numbers with decimals then use the below code
function numberWithCommas(n) {
var parts=n.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
Related
when i am trying to check if there is an image in that row for that particular it shows error when i set if the value == null, code works fine when image is found but i want to print no screenshot when there is no image. All this is done in gridview
protected void gvupdationsummary_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView dr = (DataRowView)e.Row.DataItem;
if(dr!=null)
{
//string src = Convert.DBNull(imageUrl);
string imageUrl="";
if (imageUrl!=null)
{
Convert.IsDBNull(imageUrl);
imageUrl = "data:image/jpg;base64," + Convert.ToBase64String((byte[])dr["imgdata"]);
(e.Row.FindControl("image1") as Image).ImageUrl = imageUrl;
}
else
{
Convert.IsDBNull(imageUrl);
imageUrl = null;
(e.Row.FindControl("image1") as Image).ImageUrl = imageUrl;
}
}
The exception occurred because dr["imgdata"] contains DBNull.Value, which cannot directly converted to byte array. You should put a check against DBNull.Value before using cast.
Take note that Convert.IsDbNull() returns bool value, use it to check inside if condition like example below:
if (!Convert.IsDbNull(dr["imgdata"]))
{
imageUrl = "data:image/jpg;base64," + Convert.ToBase64String((byte[])dr["imgdata"]);
// do other things
}
else
{
// do something else
}
Note:
Convert.IsDBNull(imageUrl) is unnecessary because empty string should be checked with string.IsNullOrEmpty() instead of Convert.IsDbNull().
Some assistance with sorting this error message would be gratefully appropriated. The error message is triggered when clicking on the submit button after populating the page.
AddNewProduct
public partial class AddNewProduct : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCategories();
}
}
private void GetCategories()
{
ShoppingCart k = new ShoppingCart();
DataTable dt = k.GetCategories();
if (dt.Rows.Count > 0)
{
ddlProductCategory.DataValueField = "CategoryID";
ddlProductCategory.DataValueField = "CategoryName";
ddlProductCategory.DataSource = dt;
ddlProductCategory.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (UploadProductPhoto.PostedFile != null)
{
SaveProductPhoto();
ShoppingCart k = new ShoppingCart()
{
ProductName = txtProductName.Text,
CategoryID = Convert.ToInt32(ddlProductCategory.SelectedValue),
ProductDescription = txtProductDescription.Text,
ProductPrice = txtProductPrice.Text,
ProductStock = txtProductStock.Text,
ProductImageUrl = string.Format("/ProductImages/{0}", UploadProductPhoto.FileName)
};
k.AddProduct();
ClearText();
Response.Redirect("~/Admin/AdminFillerPage.aspx");
}
}
private void ClearText()
{
txtProductName.Text = string.Empty;
txtProductDescription.Text = string.Empty;
txtProductPrice.Text = string.Empty;
txtProductStock.Text = string.Empty;
UploadProductPhoto = null;
}
private void SaveProductPhoto()
{
if (UploadProductPhoto.PostedFile != null)
{
string fileName = UploadProductPhoto.PostedFile.FileName.ToString();
string fileExtension = System.IO.Path.GetExtension(UploadProductPhoto.FileName);
//check file name legnth
if (fileName.Length > 96)
{
//Alert.Show("image name should not exceed 96 characters !");
}
//check filetype
else if (fileExtension != ".jpeg" && fileExtension != ".jpg" && fileExtension != ".png" && fileExtension != ".bmp")
{
//Alert.Show("Only jpeg,jpg,bmp & png imags are allowed!");
}
//check file size
else if (UploadProductPhoto.PostedFile.ContentLength > 4000000)
{
//Alert.Show("image size should not be greater than 4MB !");
}
//Save images into Images folder
else
{
UploadProductPhoto.SaveAs(System.IO.Path.Combine(Server.MapPath("~/ProductImages/"), fileName));
}
}
}
Shopping Cart
public class ShoppingCart
{
//Declaring Variables
public int CategoryID;
public string CategoryName;
public string ProductName;
public string ProductDescription;
public string ProductPrice;
public string ProductStock;
public string ProductImageUrl;
public void AddCategory()
{
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = DataAccess.AddParamater("#CategoryName", CategoryName, System.Data.SqlDbType.VarChar, 200);
DataTable dt = DataAccess.ExecuteDTByProcedure("mj350.AddCategory", parameters);
}
public void AddProduct()
{
SqlParameter[] parameters = new SqlParameter[6];
//Passing all the parameters that needed to be saved into the database
parameters[0] = DataLayer.DataAccess.AddParamater("#ProductName", ProductName, System.Data.SqlDbType.VarChar, 500);
parameters[1] = DataLayer.DataAccess.AddParamater("#CategoryID", CategoryID, System.Data.SqlDbType.Int, 100);
parameters[2] = DataLayer.DataAccess.AddParamater("#ProductDescription", ProductDescription, System.Data.SqlDbType.VarChar, 800);
parameters[3] = DataLayer.DataAccess.AddParamater("#ProductPrice", ProductPrice, System.Data.SqlDbType.VarChar, 500);
parameters[4] = DataLayer.DataAccess.AddParamater("#ProductStock", ProductStock, System.Data.SqlDbType.VarChar, 500);
parameters[5] = DataLayer.DataAccess.AddParamater("#ProductImage", ProductImageUrl, System.Data.SqlDbType.VarChar, 500);
//Executes the saved procedure that is saved in the database
DataTable dt = DataLayer.DataAccess.ExecuteDTByProcedure("mj350.AddProduct", parameters);
}
Stored Procedure - Add Product
CREATE PROCEDURE [AddProduct]
(
#ProductName varchar(500),
#CategoryID int,
#ProductDescription varchar(800),
#ProductPrice varchar(500),
#ProductStock varchar(500),
#ProductImage varchar(500)
)
AS
BEGIN
BEGIN TRY
INSERT INTO Product VALUES
(
#ProductName,
#CategoryID,
#ProductDescription,
#ProductPrice,
#ProductStock,
#ProductImage
)
END TRY
BEGIN CATCH
-- INSERT INTO dbo.ErrorLog
--VALUES(ERROR_MESSAGE(),'sp_GetAllData')
PRINT( 'Error occured' )
END CATCH
END
Stored Procedure - Get Categories
CREATE PROCEDURE [mj350].[ListCategories]
AS
BEGIN
BEGIN TRY
SELECT * FROM Category
END TRY
BEGIN CATCH
-- INSRET INTO dbo.ErrorLog
-- VALYES(ERROR_MESSAGE(), 'SP_GetAllData')
PRINT( 'Data Insert Error - Please review' )
END CATCH
END
Sorry if it's a silly mistake - coding skills not the best. All help gratefully received.
Thanks
Jack
Example of data form is populated with &
Where error message is triggered in code
You have this error because of the following code
private void GetCategories()
{
ShoppingCart k = new ShoppingCart();
DataTable dt = k.GetCategories();
if (dt.Rows.Count > 0)
{
ddlProductCategory.DataValueField = "CategoryID";
ddlProductCategory.DataValueField = "CategoryName"; // Here you overwrite the DataValueField.
ddlProductCategory.DataSource = dt;
ddlProductCategory.DataBind();
}
}
You overwrite the DataValueField with CategoryName property name. Then when you submit your form you are executing the following code :
ShoppingCart k = new ShoppingCart()
{
ProductName = txtProductName.Text,
CategoryID = Convert.ToInt32(ddlProductCategory.SelectedValue), // Here SelectedValue is in incorrect format.
ProductDescription = txtProductDescription.Text,
ProductPrice = txtProductPrice.Text,
ProductStock = txtProductStock.Text,
ProductImageUrl = string.Format("/ProductImages/{0}", UploadProductPhoto.FileName)
};
The exception is thrown because of this line CategoryID = Convert.ToInt32(ddlProductCategory.SelectedValue). The posted Selected value is not in correct format because you bind the value of your dropdown list with the name of the category.
To solve this you must replace this line ddlProductCategory.DataValueField = "CategoryName"; in your GetCategories by this line ddlProductCategory.DataTextField = "CategoryName";
How can I change the default sort direction when clicking a column in an ASP.NET GridView?
I would like it so that when a new column is clicked, it sorts in DESC order by default instead of ASC.
protected void OnGridViewSorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = RoomsGrid.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " +ConvertSortDirectionToSql(e.SortDirection);
RoomsGrid.DataSource = dataView;
RoomsGrid.DataBind();
}
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending: newSortDirection = "ASC"; break;
case SortDirection.Descending: newSortDirection = "DESC"; break;
}
return newSortDirection;
}
Here's an example of how it behaves now:
http://www.venuefinder.com/venues/national_motorcycle_museum/V4204/meeting-rooms/
You can't change the GridView's default sort direction but since you are using a function to get the sort direction, you can do it manually as mentioned in the following link - http://www.mikepope.com/blog/DisplayBlog.aspx?permalink=1418
With reference to the code above, you can do the following to accomplish what you are asking:
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending: newSortDirection = "DESC"; break;
case SortDirection.Descending: newSortDirection = "ASC"; break;
}
return newSortDirection;
}
Hope this helps!
There's a nice MSDN article on this -- the sample it provides returns ASC as the default, but you could easily change that to DESC. Here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx#Y576
I have a RadGrid that has a column, Loss Amount, which I would like to be able to sort. Currently it does sort, but only by string value. I have the column type as GridNumericColumn. How can I do it?
My code is listed below. I am also formatting the column text to show the currency. One thing I did notice is that I am returning a string value from the Format method. Could this be the reason?
Column:
<rad:GridNumericColumn DataField="Loss Amount"
UniqueName="Loss Amount"
HeaderText="Loss Amount"
SortExpression="Loss Amount" \>
<HeaderStyle Width="140">
<ItemStyle Width="140" HorizontalAlign="Right"ForeColor="Maroon" />
</rad:GridNumericColumn>`
NeedDataSource Event:
protected void grdCustomerAssignments_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
GetAssignments();
grdCustomerAssignments.DataSource = Assignments;
}
private void GetAssignments()
{
if (Assignments == null)
Assignments = new DataTable();
SPList list = SPContext.Current.Web.Lists["Listings"];
SPView view = GetCustomerView();
SPListItemCollection items = list.GetItems(view);
Assignments = items.GetDataTable();
foreach (DataColumn column in Assignments.Columns)
{
column.ColumnName = XmlConvert.DecodeName(column.ColumnName);
}
Assignments.AcceptChanges();
}
ItemDataBound Event:
protected void grdCustomerAssignments_ItemDataBound(object sender, GridItemEventArgs e)
{
FormatCurrency(item["Loss Amount"].Text);
}
protected string FormatCurrency(string text)
{
if (text.Length > 3)
{
string result = String.Empty;
char[] tmpArray = text.ToCharArray();
Array.Reverse(tmpArray);
string tmpString = new String(tmpArray);
while (tmpString.Length > 3)
{
string threeChars = tmpString.Substring(0, 3);
result = String.Concat(result, threeChars, ",");
tmpString = tmpString.Remove(0, 3);
}
result = String.Concat(result, tmpString);
tmpArray = result.ToCharArray();
Array.Reverse(tmpArray);
text = new String(tmpArray);
}
return String.Concat("$ ", text);
}
Also check that the source field is of a numeric data type, and it is not string. You can test that easily enabling editing - if you edit an item, an exception will be thrown if a string value is attempted to be assigned to the Telerik numeric editor.
UPDATE
I'm basically binding the query to a WinForms DataGridView. I want the column headers to be appropriate and have spaces when needed. For example, I would want a column header to be First Name instead of FirstName.
How do you create your own custom column names in LINQ?
For example:
Dim query = From u In db.Users _
Select u.FirstName AS 'First Name'
As CQ states, you can't have a space for the field name, you can return new columns however.
var query = from u in db.Users
select new
{
FirstName = u.FirstName,
LastName = u.LastName,
FullName = u.FirstName + " " + u.LastName
};
Then you can bind to the variable query from above or loop through it whatever....
foreach (var u in query)
{
// Full name will be available now
Debug.Print(u.FullName);
}
If you wanted to rename the columns, you could, but spaces wouldn't be allowed.
var query = from u in db.Users
select new
{
First = u.FirstName,
Last = u.LastName
};
Would rename the FirstName to First and LastName to Last.
I solved my own problem but all of your answers were very helpful and pointed me in the right direction.
In my LINQ query, if a column name had more than one word I would separate the words with an underscore:
Dim query = From u In Users _
Select First_Name = u.FirstName
Then, within the Paint method of the DataGridView, I replaced all underscores within the header with a space:
Private Sub DataGridView1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles DataGridView1.Paint
For Each c As DataGridViewColumn In DataGridView1.Columns
c.HeaderText = c.HeaderText.Replace("_", " ")
Next
End Sub
If you want to change the header text, you can set that in the GridView definition...
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
</Columns>
</asp:GridView>
In the code behind you can bind to the users and it will set the header to First Name.
protected void Page_Load(object sender, EventArgs e)
{
// initialize db datacontext
var query = from u in db.Users
select u;
GridView1.DataSource = query;
GridView1.DataBind();
}
You can also add an event handler to replace those underscores for you!
For those of you who love C#:
datagrid1.ItemDataBound +=
new DataGridItemEventHandler(datagrid1_HeaderItemDataBound);
And your handler should look like this:
private void datagrid1_HeaderItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
foreach(TableCell cell in e.Item.Cells)
cell.Text = cell.Text.Replace('_', ' ');
}
}
I would use:
var query = from u in db.Users
select new
{
FirstName = u.FirstName,
LastName = u.LastName,
FullName = u.FirstName + " " + u.LastName
};
(from Scott Nichols)
along with a function that reads a Camel Case string and inserts spaces before each new capital (you could add rules for ID etc.). I don't have the code for that function with me for now, but its fairly simple to write.
You can make your results have underscores in the column name and use a HeaderTemplate in a TemplateField to replace underscores with spaces. Or subclass the DataControlField for the GridView and override the HeaderText property:
namespace MyControls
{
public SpacedHeaderTextField : System.Web.UI.WebControls.BoundField
{ public override string HeaderText
{ get
{ string value = base.HeaderText;
return (value.Length > 0) ? value : DataField.Replace(" ","");
}
set
{ base.HeaderText = value;
}
}
}
}
ASPX:
<%#Register TagPrefix="my" Namespace="MyControls" %>
<asp:GridView DataSourceID="LinqDataSource1" runat='server'>
<Columns>
<my:SpacedHeaderTextField DataField="First_Name" />
</Columns>
</asp:GridView>
I dont see why you would have to do that, if you are trying to do that for a grid or something, why not just name the header in the HTML?
What you would actually be doing is setting a variable reference to the return, there is not a way to name a variable with a space. Is there an end result reason you are doing this, perhaps if we knew the ultimate goal we could help you come up with a solution that fits.
Using Linq Extension Method:
SomeDataSource.Select(i => new { NewColumnName = i.OldColumnName, NewColumnTwoName = i.OldColumnTwoName});
As others have already pointed out, if the header title etc is known at design time, turn off AutoGeneratedColumns and just set the title etc in the field definition instead of using auto generated columns. From your example it appears that the query is static and that the titles are known at design time so that is probably your best choice.
However [, although your question does not specify this requirement] - if the header text (and formatting etc) is not known at design time but will be determined at runtime and if you need to auto generate columns (using AutoGenerateColumns=
true") there are workarounds for that.
One way to do that is to create a new control class that inherits the gridview. You can then set header, formatting etc for the auto generated fields by overriding the gridview's "CreateAutoGeneratedColumn". Example:
//gridview with more formatting options
namespace GridViewCF
{
[ToolboxData("<{0}:GridViewCF runat=server></{0}:GridViewCF>")]
public class GridViewCF : GridView
{
//public Dictionary<string, UserReportField> _fieldProperties = null;
public GridViewCF()
{
}
public List<FieldProperties> FieldProperties
{
get
{
return (List<FieldProperties>)ViewState["FieldProperties"];
}
set
{
ViewState["FieldProperties"] = value;
}
}
protected override AutoGeneratedField CreateAutoGeneratedColumn(AutoGeneratedFieldProperties fieldProperties)
{
AutoGeneratedField field = base.CreateAutoGeneratedColumn(fieldProperties);
StateBag sb = (StateBag)field.GetType()
.InvokeMember("ViewState",
BindingFlags.GetProperty |
BindingFlags.NonPublic |
BindingFlags.Instance,
null, field, new object[] {});
if (FieldProperties != null)
{
FieldProperties fps = FieldProperties.Where(fp => fp.Name == fieldProperties.Name).Single();
if (fps.FormatString != null && fps.FormatString != "")
{
//formatting
sb["DataFormatString"] = "{0:" + fps.FormatString + "}";
field.HtmlEncode = false;
}
//header caption
field.HeaderText = fps.HeaderText;
//alignment
field.ItemStyle.HorizontalAlign = fps.HorizontalAlign;
}
return field;
}
}
[Serializable()]
public class FieldProperties
{
public FieldProperties()
{ }
public FieldProperties(string name, string formatString, string headerText, HorizontalAlign horizontalAlign)
{
Name = name;
FormatString = formatString;
HeaderText = headerText;
HorizontalAlign = horizontalAlign;
}
public string Name { get; set; }
public string FormatString { get; set; }
public string HeaderText { get; set; }
public HorizontalAlign HorizontalAlign { get; set; }
}
}
I believe this can be achieved using explicit name type
system.Name,
sysentity.Name
//change this to
entity = sysentity.Name
My VS2008 is busted right now, so I can't check. In C#, you would use "=" - How about
Dim query = From u In db.Users _
Select 'First Name' = u.FirstName