Error adding to a database in a website remake - sql

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" />

Related

Changing Hyperlink text in VB code for Gridview

In the VB code below, I'm trying to set the Hyperlink hypNote's text as "Add Note" when text is null. However it is not working. As a test, I've even set the Hyperlink text as "Test" and tried:
If hypNote.text = "Test" Then
hypNote.text = "Add Note"
End If
But still it doesn't work. Here's my code..
<asp:Panel ID="pnlOrders" runat="server">
<asp:Image ID="LiveOrders" alt="Live Gif" runat="server" class="extrasButton" ImageUrl="~/files/images/liveOrders.gif" />
<asp:SqlDataSource ID="DSOrders" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnectionString %>" SelectCommand="SELECT TOP (100) PERCENT tblOrders.OrderID, tblOrders.stallmessage, tblOrders.price, tblAccounts.city, tblAccounts.postcode, tblOrders.phoneNo, tblOrders.tblNo, tblOrders.info, tblOrders.orderDate, tblOrders.orderStatus, tblOrders.type, tblOrders.timeFor, tblOrders.paid, tblOrders.tblNo
FROM tblOrders INNER JOIN tblAccounts ON tblOrders.accountID = tblAccounts.AccountID
WHERE tblOrders.orderStatus='Completed'
ORDER BY tblOrders.timeFor ASC">
</asp:SqlDataSource>
<asp:GridView ID="gdvOrders" width="100%" runat="server" style="font-size:1.5em" ShowHeaderWhenEmpty="True" EmptyDataText="No orders" AllowPaging="True" AutoGenerateColumns="False" CssClass="mGrid" DataKeyNames="orderID" DataSourceID="DSOrders" PageSize="20" AllowSorting="True">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:TemplateField HeaderText="Order">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("stallMessage") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="price" HeaderText="Price" />
<asp:BoundField DataField="phoneNo" HeaderText="Phone No" />
<asp:TemplateField HeaderText="Address/Table No.">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("tblNo") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-ForeColor="Red" HeaderText="Note">
<ItemTemplate>
<asp:HyperLink ID="hypNote" style="Font-Size:20px; color:Red;" runat="server" NavigateUrl='<%# "~/editNote.aspx?note=" & Eval("info").ToString & "&orderID=" & Eval("orderID").ToString %>' ><%# Eval("info") %></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="type" HeaderText="Type" />
<asp:BoundField DataField="orderDate" DataFormatString="{0: H:mm:ss}" HeaderText="Order Time" SortExpression="orderDate" />
<asp:BoundField DataField="timeFor" DataFormatString="{0: H:mm:ss}" HeaderText="Time For" SortExpression="timeFor" />
<asp:BoundField DataField="paid" HeaderText="Paid" />
<asp:TemplateField ShowHeader="True">
<ItemTemplate>
<asp:ImageButton visible="true" ID="lnkSent" runat="server" CausesValidation="False"
onclientclick="return confirm('Mark As Sent?');"
ImageUrl="~/files/images/icons/sendIcon.png" onclick="lnkSent_Click"></asp:ImageButton>
<asp:HiddenField ID="hidnOrderID" runat="server" Value='<%# Eval("orderID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
Protected Sub gdvOrders_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gdvOrders.RowDataBound
For Each r As GridViewRow in gdvOrders.Rows
If r.RowType = DataControlRowType.DataRow Then
Dim hypNote As Hyperlink
hypNote = r.Cells(4).FindControl("hypNote")
If hypNote.text = "" Then
hypNote.text = "Add Note"
End If
End If
Next r
End Sub
Additionally, I wish to change the text color of the Hyperlink when "Add Note" is displayed.
I figured out my mistake. I changed this line to:
<asp:HyperLink ID="hypNote" style="Font-Size:20px; color:Red;" text='<%# Eval("info") %>' runat="server" NavigateUrl='<%# "~/editNote.aspx?note=" & Eval("info").ToString & "&orderID=" & Eval("orderID").ToString %>' ></asp:HyperLink>
I didn't have text= in there.
All worked fine then.

no data in asp table after Post back

I have updatePanel, in which I am having tables as shown
<asp:UpdatePanel ID="DynCreated" EnableViewState="true" UpdateMode="Conditional"
runat="server">
<ContentTemplate >
<div style="display: none" enableviewstate="true">
<asp:TextBox ID="flgClear" EnableViewState="true" Text="" runat="server"></asp:TextBox>
<asp:TextBox ID="flgAdd" EnableViewState="true" Text="" runat="server"></asp:TextBox>
<asp:TextBox ID="txtList" EnableViewState="true" Text="|" runat="server"></asp:TextBox>
<asp:TextBox ID="txtDelete" EnableViewState="true" Text="|" runat="server"></asp:TextBox></div>
<asp:Table ID="tblGrid" CssClass="grid" CellPadding="0" CellSpacing="0"
Width="100%" EnableViewState="true" runat="server"> <asp:TableRow TableSection="TableHeader" ID="trHeader" CssClass="crid-header Datagrid-header"
runat="server" EnableViewState="true">
<asp:TableHeaderCell ID="hdrSequence" runat="server">
<asp:Label ID="lblSequence" Text="#" CssClass="cel" runat="server" />
</asp:TableHeaderCell>
<asp:TableHeaderCell ID="hdrHouseBill" runat="server">
<asp:Label ID="lblHouseBill" Text="HouseBill" CssClass="ceva-form-label" runat="server" />
</asp:TableHeaderCell>
<asp:TableHeaderCell ID="hdrFileNumber" runat="server">
<asp:Label ID="lblFileNumber" Text="FileNumbere" CssClass="ceva-form-label" runat="server" />
</asp:TableHeaderCell>
</asp:TableRow>
</asp:Table>
<br />
<br />
<div class="text-center">
<asp:Button ID="btnAddNewHB" CssClass="tn btn-dialog" Text="Add New Status"
OnClientClick="return ShowNewLeg();" runat="server" />
<asp:Button Text="Validate" CssClass="cen btn-dialog" runat="server" ID="btnValidate" />
<asp:Button ID="btnSave" CssClass="tn-dialog" Text="Save" OnClientClick="return Save()" Visible="false"
runat="server" />
<asp:Button ID="btnCancel" CssClass=" btn-dialog" OnClientClick="window.returnValue = 1; window.close(); return false;"
Text="Cancel" CausesValidation="false" runat="server" />
<asp:Button ID="btnClear" CssClass=tn btn-dialog" Text="Clear All" OnClientClick="return ClearTable();"
runat="server" />
<input type="hidden" id="hndtimeformat" runat="server" name="hndtimeformat" value="0"
style="display: none" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
From the back-end i am adding new Row to the tblGrid
For j As Integer = tblGrid.Rows.Count To maxRow
Dim newRow As TableRow= New TableRow()
newRow.Cells.Add(CreateNewLabel(tblGrid.Rows.Count, "SEQ",
tblGrid.Rows.Count, tblGrid.Rows.Count, "40px", bColor))
newRow.Cells.Add(CreateNewText(tblGrid.Rows.Count, "HB", "",
tblGrid.Rows.Count, "10px", "", 3, "none", False))
newRow.Cells.Add(CreateNewLabel(tblGrid.Rows.Count, "FN", "", tblGrid.Rows.Count, "60px", ""))
newRow.Cells.Add(CreateNewDD(tblGrid.Rows.Count, "ST", statusup, tblGrid.Rows.Count, "10px", "", 3, "none", True))
newRow.Cells.Add(CreateNewDT(tblGrid.Rows.Count, "datetime", "", tblGrid.Rows.Count, ""))
newRow.Cells.Add(CreateNewAC(tblGrid.Rows.Count, "LC", "", "", tblGrid.Rows.Count, "0.0", AutoCompletor.DisplayFieldType.Code, "", "", False))
newRow.Cells.Add(CreateNewText(tblGrid.Rows.Count, "SG", "", tblGrid.Rows.Count, "10px", "", 0, "none"))
newRow.Cells.Add(CreateNewCB(tblGrid.Rows.Count, "CB", "", tblGrid.Rows.Count, "5px", bColor))
newRow.Cells.Add(CreateNewText(tblGrid.Rows.Count, "Note", "", tblGrid.Rows.Count, "10px", "", 0, "none"))
newRow.Cells.Add(CreateNewLabel(tblGrid.Rows.Count, "Er", "", tblGrid.Rows.Count, "40px", bColor))
newRow.Cells.Add(CreateNewImage(tblGrid.Rows.Count, "btn", tblGrid.Rows.Count)) tblGrid.Rows.Add(newRow) Next j
I am getting data what ever i have before post back, after post back its not having any data which is present in the tabGrid.
Do I need to use ViewState or Session? is there any way i get the data?
Please advice !!
Put your data into a viewstate and get them after postback
You can use a ViewState variable if you need to use this data only during navigation inside this page. If you want keep alive data for the entire session better to use a Session variable, so you will not loose these rows also if you go in other pages.
Asp:Table isn't the right element to use if you want manage data, i suggest to try this solution (is only an example):
<asp:GridView runat="server" ID="tblGrid" CssClass="grid" CellPadding="0" CellSpacing="0">
<Columns >
<asp:TemplateField >
<HeaderTemplate >
<asp:Label ID="lblSequence" Text="#" CssClass="cel" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblSequenceItem" Text="<%# Eval("col1") %>" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lblHouseBill" Text="HouseBill" CssClass="ceva-form-label" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblHouseBillItem" Text="<%# Eval("col2") %>" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lblFileNumber" Text="FileNumbere" CssClass="ceva-form-label" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblFileNumberItem" Text="<%# Eval("col3") %>" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and this for runtime data binding:
Creation of datatable
Dim dt As New Data.DataTable("rows")
Dim col1 As New Data.DataColumn("col1", GetType(String))
Dim col2 As New Data.DataColumn("col2", GetType(Integer))
Dim col3 As New Data.DataColumn("col3", GetType(String))
dt.Columns.Add(col1)
dt.Columns.Add(col2)
dt.Columns.Add(col3)
dt.Rows.Add ("test",1,"test") 'statement for row insert
ViewState("datasource") = dt
tblGrid.DataSource = dt
tblGrid.DataBind()
And binding in postback:
Dim dt As New Data.DataTable("rows")
If Not ViewState("datasource") Is Nothing Then dt = ViewState("datasource")
tblGrid.DataSource = dt
tblGrid.DataBind()

cascading dropdownlist, second dropdown storing wrong value in database

I have two dropdowns Complaint_Type and Complaint_SubType. Using SqlDataSource I have populated both. SubType dropdown gets correctly populated when I choose the Type dropdown. When I select the values and press submit and check in the database both the type and subtype values are same.
.aspx code
<asp:ScriptManager ID="smDDL" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="upDDL" runat="server">
<ContentTemplate>
<div class="form-group" style="margin-bottom: 25px;">
<asp:Label ID="lblCType" runat="server" Text="Complaint Type" data-toggle="tooltip" title="Select Complaint Type" />
<asp:RequiredFieldValidator ID="RfvDDLCompType" runat="server" ErrorMessage="Please Select Complaint Type" ControlToValidate="ddlCType" ForeColor="Red" InitialValue="0" Display="Dynamic"> *</asp:RequiredFieldValidator>
<asp:DropDownList ID="ddlCType" runat="server" CssClass="form-control" DataSourceID="SqlDataSource1" DataTextField="Comp_Type" DataValueField="Type_ID" AutoPostBack="True" OnDataBound="DDLCTypeDataBound" Style="width: 400px">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ComplaintWebsiteConnectionString %>" SelectCommand="SELECT * FROM [Complaint_Type]"></asp:SqlDataSource>
</div>
<div class="form-group" style="margin-bottom: 25px;">
<asp:Label ID="lblSubType" runat="server" Text="Complaint Sub Type" data-toggle="tooltip" title="Select Complaint Sub Type" />
<asp:RequiredFieldValidator ID="rfvDDlSubType" runat="server" ErrorMessage="Please Select Complaint Sub Type" ControlToValidate="ddlSubType" ForeColor="Red" InitialValue="0" Display="Dynamic"> *</asp:RequiredFieldValidator>
<asp:DropDownList ID="ddlSubType" runat="server" CssClass="form-control" DataSourceID="SqlDataSource2" DataTextField="Comp_SubType" DataValueField="Type_ID" OnDataBound="DDLSubTypeDataBound" Style="width: inherit">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ComplaintWebsiteConnectionString %>" SelectCommand="SELECT * FROM [Complaint_SubType] WHERE ([Type_ID] = #Type_ID2)">
<SelectParameters>
<asp:ControlParameter ControlID="ddlCType" Name="Type_ID2" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</div>
</ContentTemplate>
</asp:UpdatePanel>
.cs code
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DDLCTypeDataBound(object sender, EventArgs e)
{
ddlCType.Items.Insert(0, new ListItem("Select", "0"));
}
protected void DDLSubTypeDataBound(object sender, EventArgs e)
{
ddlSubType.Items.Insert(0, new ListItem("Select", "0"));
}
protected void btn_Reset(object Sender, EventArgs e)
{
}
protected void btnReport_Click(object Sender, EventArgs e)
{
SqlConnection con = new SqlConnection(Utils.Connection);
String query = "insert into CITIZEN_COMPLAINTS(TYPE, SUBTYPE, LOCATION, DESCRIPTION, IMAGE) values (#TYPE, #SUBTYPE, #LOCATION, #DESCRIPTION, #IMAGE)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#TYPE", SqlDbType.Int).Value = ddlCType.SelectedValue;
cmd.Parameters.Add("#SUBTYPE", SqlDbType.Int).Value = ddlSubType.SelectedValue;
cmd.Parameters.Add("#LOCATION", SqlDbType.VarChar).Value = txtLoc.Text;
cmd.Parameters.Add("#DESCRIPTION", SqlDbType.VarChar).Value = txtDesc.Text;
cmd.Parameters.Add("#IMAGE", SqlDbType.VarChar).Value = Utils.file_upload(fuImage);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
//...
}
finally
{
con.Close();
}
}
The reason is because the DataValueField="Type_ID" is same for both drop downs in your markup for these drop downs.
For the second drop down for sub types, you should have something like DataValueField="SubType_ID".
Assuming the primary key column in Complaint_SubType table is SubType_ID, the markup below will solve your problem. Note the DataValueField in these two markups, which should be different.
Type drop down
<asp:DropDownList ID="ddlCType" runat="server" CssClass="form-control"
DataSourceID="SqlDataSource1" DataTextField="Comp_Type" DataValueField="Type_ID"
AutoPostBack="True" OnDataBound="DDLCTypeDataBound" Style="width: 400px">
</asp:DropDownList>
Sub Type drop down
<asp:DropDownList ID="ddlSubType" runat="server" CssClass="form-control"
DataSourceID="SqlDataSource2" DataTextField="Comp_SubType" DataValueField="SubType_ID"
OnDataBound="DDLSubTypeDataBound" Style="width: inherit">
</asp:DropDownList>

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

Textboxes inside gridview validation

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>