Textboxes inside gridview validation - sql

I have a gridview in which I have 100 rows of Textboxes. All textboxes have same id 'TxtEmpcode'. User enters data in some rows of gridview. How do I validate textboxes such that one Employee code is entered only once in textboxes. This is to avoid duplicate entry of data. Suppose a user enters Employee code '1234', this should not allowed in other rows of textboxes. If they enter, a message should appear as 'Employee Code has already been entered'.
Can anyone tell how to achieve this?
<asp:GridView ID="GridView2" runat="server" style="margin-left: 23px; margin-top: 11px;" Width="420px" CellPadding="4" AutoGenerateColumns="False" ForeColor="#333333" GridLines="None" Height="213px" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Employee Code">
<ItemTemplate>
<asp:TextBox ID="TxtEmpcode" runat="server" OnTextChanged="TxtId_TextChanged" AutoPostBack ="true" ></asp:TextBox>
</ItemTemplate>

You can use logic of it as per your requirement.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<script>
function IsValidTest(Control) {
name = Control.name;
var list = document.getElementById("TxtEmpcode");
var contents = $("[id=TxtEmpcode]");
var TextboxId = name;
var Txtbox = document.getElementsByName(name);
var TextboxValue = Txtbox[0].value;
for (i = 0; i < contents.length; i++)
{
var currenttextboxName=contents[i].name;
var currenttextboxValue=contents[i].value;
//Compare currently changed value with existing values in other textboxes
if (name != currenttextboxName && currenttextboxValue == TextboxValue)
{
alert('Employee Code has already been entered');
Txtbox[0].value = '';
return false;
}
}
return true;
}
</script>
<div>
<asp:GridView ID="GridView2" runat="server" Style="margin-left: 23px; margin-top: 11px;"
Width="420px" CellPadding="4" AutoGenerateColumns="False" ForeColor="#333333"
GridLines="None" Height="213px">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Employee Code">
<ItemTemplate>
<asp:TextBox ID="TxtEmpcode" runat="server" AutoPostBack="true" ClientIDMode="Static" onchange="javascript: return IsValidTest(this);"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</asp:Content>

Related

Changing a columns contents in a GridView from VB code

I am displaying a grid of data which includes a users name and profile pic etc.
If they haven’t uploaded a profile picture I have set the code below to set imgPic.ImageUrl = "~/files/images/blankProfilePic.png"
However, this works only for the 1st page of 6 pages of data displayed.. As soon as you switch to the 2nd page I get the missing picture icon as the code below is only working for the initial page displayed.
I need to change this code to work on every page as it is only called when the page loads.
VB CODE
Protected Sub Page_LoadComplete(sender As Object, e As System.EventArgs) Handles Me.LoadComplete
Dim acc As New accounts(Membership.GetUser.ProviderUserKey)
If acc.region = "North East" Then
For Each r As GridViewRow in gdvNorthEast.Rows
If r.RowType = DataControlRowType.DataRow Then
Dim imgPic As Image
imgPic = r.Cells(4).FindControl("imgProfilePic")
If imgPic.ImageUrl = "~/catalog/images/"
imgPic.ImageUrl = "~/files/images/blankProfilePic.png"
End If
End If
Next r
End If
ASP.NET
<asp:SqlDataSource
ID="DSLeaderboardNorthEast"
runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT tblAccounts.contactName, tblAccounts.profilePic, tblAccounts.minAge, tblAccounts.maxAge, tblAccounts.AccountID, tblAccounts.region
FROM tblAccounts
WHERE tblAccounts.region='North East'
ORDER BY tblAccounts.contactName ">
</asp:SqlDataSource>
<asp:GridView ID="gdvNorthEast" width="100%" runat="server" AllowPaging="True" AutoGenerateColumns="False" CssClass="mGrid" DataKeyNames="accountID" DataSourceID="DSLeaderboardNorthEast" PageSize="20" AllowSorting="True">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Image ID="imgProfilePic" AlternateText="Players profile picture" runat="server" width="100px" height="100px" ImageUrl='<%# "~/catalog/images/" & Eval("ProfilePic").ToString %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="contactName" HeaderText="Player Name" />
<asp:BoundField DataField="minAge" HeaderText="Won" />
<asp:BoundField DataField="maxAge" HeaderText="Lost" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:HyperLink ID="hypMessage" runat="server" CssClass="nyroModalMsg" NavigateUrl='<%# "~/sendLeaderboardMessage.aspx?" & "&aID=" & Eval("accountID").ToString %>'>Msg</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Your foreach loop for assigning default image should be reusable method.
Use PageIndexChanged event handler to call the same reusable method.
Update:
Since the above option is not helping, follow this post
//RowDataBound Event
protected void gdvNorthEast_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Checking the RowType of the Row
if(e.Row.RowType==DataControlRowType.DataRow)
{
//your logic goes here without foreach loop
}
}
Use the Gridview_RowDataBound event to make the function of substitution instead use a for instruction

ASP.NET Gridview

I formed the table shown below picture 1 with GridView but there is a something which I want and I explain that picture 2 (İ didn't use GridView there).
When the data come from database to column of Durum, if it is Aktif, it shows Aktif Button or if it is Pasif, it shows Pasif Button.
How can do this?
You can do pretty much whatever you want assuming you don't use default column binding but rather you define your own.
<asp:GridView ... AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
this is where your template can do
pretty much anything including conditionals
<asp:Button runat="server"
ForeColor="<%# Bind("column")=="value" ? "Red" ? "Blue" %> />
Note that dynamic binding can be applied to any property. You could have two different buttons then and dynamically bind their Visible property so that they are visible or hidden depending on a value of one of dataset columns.
More on dynamic templates in multiple tutorials, e.g.
https://msdn.microsoft.com/en-us/library/bb288032.aspx
Add this TemplateField Code in your GridView:
<asp:TemplateField HeaderText="Durum">
<ItemTemplate>
// Bind your durum column from database in Eval
<asp:Label ID="lblDurum" Visible="false" runat="server" Text='<% #Eval("durum") %>'></asp:Label>
<asp:Button ID="btnAktif" Visible="false" runat="server" Text="Aktif" />
<asp:Button ID="btnPasif" Visible="false" runat="server" Text="Pasif" />
</ItemTemplate>
</asp:TemplateField>
Code Behind
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button Aktif = e.Row.FindControl("btnAktif") as Button;
Button Pasif = e.Row.FindControl("btnPasif") as Button;
string Durum = ((Label)e.Row.FindControl("lblDurum")).Text;
if (Durum=="Aktif")
Aktif.Visible = true;
else
Pasif.Visible = true;
}
}
Note: Don't forget to add OnRowDataBound in GrindView <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" >

get Sum of values in column from sqlDataSource

I have a SqlDataSource dsDetails that selects from the DB table.
<asp:SqlDataSource ID="dsDetails" runat="server" SelectCommand="spGetDetails"
OnSelected="dsDetails_Selected" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:QueryStringParameter Name="mode" QueryStringField="mode" Type="String" DefaultValue="NULL" />
</SelectParameters>
</asp:SqlDataSource>
The result is bound to gridview in the aspx page
<asp:GridView CssClass="content" ID="gridDetails" runat="server" DataSourceID="dsDetails" AllowSorting="True" AllowPaging="True" PagerSettings-Position ="TopAndBottom" DataKeyNames="ID" AutoGenerateColumns="False" >
<PagerSettings Position="TopAndBottom" Mode="NumericFirstLast" />
<EmptyDataTemplate>
<b>There are no records to display.</b>
</EmptyDataTemplate>
<Columns>
<asp:BoundField DataField="empNum" HeaderText="Employee Number" SortExpression="empnum" ApplyFormatInEditMode="True" HtmlEncode="False" ReadOnly="True" />
<asp:BoundField DataField="empName" HeaderText="Emplopyee Name" SortExpression="empname" ApplyFormatInEditMode="True" HtmlEncode="False" ReadOnly="True" />
<asp:BoundField DataField="empDoj" HeaderText="Emplopyee Date of joining" SortExpression="empdoj" ApplyFormatInEditMode="True" HtmlEncode="False" ReadOnly="True" />
<asp:TemplateField HeaderText="Salary" SortExpression="sal">
<EditItemTemplate>
<asp:TextBox ID="txtSal" runat="server" Text='<%# Eval("sal", "{0:F}") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("sal", "{0:C2}") %>'></asp:Label>--%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<EditItemTemplate>
<asp:Button ID="btnSave" runat="server" CausesValidation="True" CommandName="cmdSave"
Text="Save" />
<asp:Button ID="btnCancel" runat="server" CausesValidation="False" CommandName="cmdCancel"
Text="Cancel" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btnApprove" runat="server" CausesValidation="False" CommandName="cmdApprove"
Text="Approve" />
<asp:Button ID="btnEdit" runat="server" CausesValidation="False" CommandName="cmdEdit"
Text="Edit" />
<asp:Button ID="btnDelete" runat="server" CausesValidation="false" CommandName="cmdDelete"
Text="Delete" />
<ajaxToolkit:ConfirmButtonExtender ID="cbeDelete" runat="server"
TargetControlID="btnDelete"
ConfirmText="Are you sure?" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now what i have to achieve is Find the Sum of the Salary Column of the grid view. How to achieve this using the Data Source in the page load method? I have to get the sum of Salary for the entire result set (avg records returned 60-80)
Iterating through the rows and computing the sum in gridDetails_RowDataBound wont be effective since the rows.count will be max of 10 since the page size is 10. When the result set has more than 10 records say 55, It will compute the sum for the current gridview page alone (first 10 records). I have to get the sum for all 55 records and display it in a label in the pageload method.
Please provide suggestion..
The SQLDataSource provides a Selected event that fires after data retrieval has finished. See SqlDataSource.Selected Event. You should be able to do a sum on the rows in the grid in this event.
This worked for me
In PageLoad method add
dvSql = DirectCast(dsDetails.Select(DataSourceSelectArguments.Empty), DataView)
For Each drvSql As DataRowView In dvSql
amtSum += CDbl(drvSql("sal"))
Next
lblTotalAmt.Text = CStr(recoveryAmtSum)
In dsDetails_Selected method add this line
e.Command.Parameters("#approvaltype").Value = mode

Filtering data on load in a RadGrid FilterTemplate

I have a RadGrid which has a FilterTemplate using a RadComboBox. When I load the data in RadGrid, I want to show the user filtered data. Here is my column:
<telerik:GridTemplateColumn FilterControlAltText="Filter tclmArrangement column"
HeaderText="Arrangement" UniqueName="tclmArrangement" DefaultInsertValue="-"
DataField="IsDemoAssigned">
<HeaderStyle Width="2%" />
<ItemTemplate>
<asp:Repeater ID="rptchkarrangement" runat="server"
DataSource='<%# IIf(DataBinder.Eval(Container, "DataItem.IsDEmoAssigned") = 0,
DataBinder.Eval(Container, "DataItem.Employees"), Nothing)%> '>
<ItemTemplate>
<table>
<tr class="clsParent">
<input type="checkbox" class="clsEmployee" id="cbSelect"
checked='<%# DataBinder.Eval(Container, "DataItem.IsAssigned")%>'
runat="server" />
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
<FilterTemplate>
<telerik:RadComboBox ID="RadComboBoxAssignmentStatus" Height="80px" Width="80px"
AppendDataBoundItems="true" runat="server"
OnClientSelectedIndexChanged="AssignmentStatusIndexChanged">
</telerik:RadComboBox>
<telerik:RadScriptBlock ID="rsbAssignmentStatus" runat="server">
<script type="text/javascript">
function AssignmentStatusIndexChanged(sender, args) {
var tableView = $find("<%# TryCast(Container,GridItem)
.OwnerTableView.ClientID %>");
var selectedValue = sender.get_value();
if (selectedValue) {
if (parseInt(selectedValue) < 0) {
tableView.filter("tclmArrangement", selectedValue, "NoFilter");
}
else {
tableView.filter("tclmArrangement", selectedValue, "EqualTo");
}
}
}
</script>
</telerik:RadScriptBlock>
</FilterTemplate>
</telerik:GridTemplateColumn>
The filter works fine when the complete data is displayed initially using All option. Filter has values (All, Assigned and UnAssigned). How do I show data in the RadGrid which falls under UnAssigned category?
Not sure is this what you want but I filter through the GridTemplateColumn DataFields. I have removed the repeater.
I hope this help you
.aspx
<telerik:RadGrid ID="rg" runat="server" AutoGenerateColumns="false"
OnNeedDataSource="rg_NeedDataSource" AllowFilteringByColumn="true">
<MasterTableView>
<Columns>
<telerik:GridTemplateColumn DataField="IsAssigned" DefaultInsertValue="-"
UniqueName="tclmArrangement">
<HeaderStyle Width="2%" />
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server"
Checked='<%# Eval("IsAssigned") %>' />
<asp:Label ID="lbl" runat="server" Text='<%# Eval("EmployeeName") %>'>
</asp:Label>
</ItemTemplate>
<FilterTemplate>
<telerik:RadComboBox ID="rcbAssignmentStatus" Height="80px" Width="80px"
runat="server"
OnClientSelectedIndexChanged="AssignmentStatusIndexChanged"
SelectedValue='<%# ((GridItem)Container)
.OwnerTableView
.GetColumn("tclmArrangement").CurrentFilterValue %>'>
<Items>
<telerik:RadComboBoxItem Text="All" Value="" />
<telerik:RadComboBoxItem Text="All Assigned" Value="true" />
<telerik:RadComboBoxItem Text="Unassigned" Value="false" />
</Items>
</telerik:RadComboBox>
<telerik:RadCodeBlock ID="rcb" runat="server">
<script type="text/javascript">
function AssignmentStatusIndexChanged(sender, args) {
var tableView = $find('<%# ((GridItem)Container)
.OwnerTableView.ClientID %>');
var value = sender.get_selectedItem().get_value();
if (value != "")
tableView.filter('tclmArrangement', args.get_item()
.get_value(), 'EqualTo');
else
tableView.filter('tclmArrangement', args.get_item()
.get_value(), 'NoFilter')
}
</script>
</telerik:RadCodeBlock>
</FilterTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("IsAssigned", typeof(bool));
dt.Columns.Add("EmployeeName", typeof(string));
string[] employeeName = { "Patrick", "Bucky", "Henry", "Jesus", "Linda" };
int[] isAssigned = { 1, 1, 0, 0, 0 };
// Loop
for (int i = 0; i < employeeName.Length; i++)
dt.Rows.Add(isAssigned[i], employeeName[i]);
ViewState["Data"] = dt;
rg.DataSource = dt;
rg.DataBind();
dt.Dispose();
}
}
protected void rg_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
rg.DataSource = ViewState["Data"] as DataTable;
}
This link helped me.
http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/functionality/filtering/how-to/apply-default-filter-on-initial-load
One thing which is not specified in the link is to set "EnableLinqExpression=false"
I chose to take "Setting the initial filter in the code-behind" approach. Filter expressions can be formed as follows.
http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/functionality/filtering/how-to/operate-with-the-filterexpression-manually

Error adding to a database in a website remake

I am trying to add a item to my database through a class made by me. I have this error
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
Additional information: Input string was not in a correct format.
I am not sure where I went wrong but here is my code
protected void btnAdd_Click(object sender, EventArgs e)
{
string filename = FileUpload1.PostedFile.FileName;
int filebytes = FileUpload1.PostedFile.ContentLength;
byte[] image = new byte[filebytes];
FileUpload1.PostedFile.InputStream.Read(image, 0, filebytes);
string imagepath = "~/Image/" + filename;
pro.SaveNewProduct(int.Parse(txtID.Text), txtPName.Text, int.Parse(txtPrice.Text), txtDes.Text, imagepath, int.Parse(DDLCatagory.SelectedValue), int.Parse(DDLNPCAA.SelectedValue), DDLproductype.SelectedValue, int.Parse(txtQuant.Text));
}
public void SaveNewProduct(int id, string name, int price, string description, string image, int catagory, int popularity, string kindof, int quantity)
{
dal.ClearParams();
dal.AddParam("#ItemID", id);
dal.AddParam("#Name", name);
dal.AddParam("#Price", price);
dal.AddParam("#Descriptions", description);
dal.AddParam("#Images", image);
dal.AddParam("#Catagory", catagory);
dal.AddParam("#Popularity", popularity);
dal.AddParam("#Type", kindof);
dal.AddParam("#Quantity", quantity);
dal.ExecuteProcedure("spSNI");
}
Also I get the error at the pro.savenewproduct.
I have triple checked to see if I made any mistakes in what I typed as parameters and so far nothing seems off.
I am assuming you mean this, also I only typed 20 in the textbox for price to get this error:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div style="float:right; margin-right:300px">
<asp:Image ID="Image1" runat="server" Width="200px" Height="200px" />
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br /><br />
<asp:Label ID="lblPName" runat="server" Text="Product Name"></asp:Label>
<asp:TextBox runat="server" ID="txtPName"></asp:TextBox>
<asp:Label ID="lblPrice" runat="server" Text="Price"></asp:Label>
<asp:TextBox runat="server" ID="txtPrice"></asp:TextBox>
<br /><br />
<asp:Label ID="lblDes" runat="server" Text="Description"></asp:Label>
<asp:TextBox runat="server" ID="txtDes"></asp:TextBox>
<asp:Label ID="lblquant" runat="server" Text="Quantity"></asp:Label>
<asp:TextBox runat="server" ID="txtQuant"></asp:TextBox>
<br /><br />
<asp:DropDownList runat="server" ID="DDLproductype">
<asp:ListItem>Select Product Type</asp:ListItem>
<asp:ListItem>Physical Product</asp:ListItem>
<asp:ListItem>Service Product</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList runat="server" ID="DDLNPCAA"></asp:DropDownList>
<asp:DropDownList runat="server" ID="DDLCatagory"></asp:DropDownList>
<br />
<asp:Label ID="lblID" runat="server" Text="ID of Existing Item"></asp:Label>
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
<asp:DropDownList ID="DDListofitems" runat="server"></asp:DropDownList>
<br />
<asp:Button ID="btnupdateID" runat="server" Text="Update ID of Item" OnClientClick="btnupdateID_Click" OnClick="btnupdateID_Click" />
<br /><br />
<asp:Button ID="btnAdd" runat="server" Text="Add New Item Or Update" OnClick="btnAdd_Click" />