Filtering data on load in a RadGrid FilterTemplate - radgrid

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

Related

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>

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>

RadComboBox DropDownList is dittached from its place

There is a RadGrid which contains RadcomboBox along with button next to it.
When user key-in something and click on button, data bind in RadComboBox related to key-in text and display in DropdownList.
but this DropdownList appear far below from RadcomboBox, which disturbs the look & feel of the page. Please refer the attached issue snapshot.
I tried to set ExpandDirection="Down" property but did not worked.
Also I tried to set EnableScreenBoundaryDetection="false", this sticks the
Dropdownlist at the bottom of page, so when I scroll the page , DropDown always stick at bottom & it also scrolls with the page.
Also, I set the HighlightTemplatedItems="true" but it is not working at all.
EDIT:
HTML code:
<telerik:RadMultiPage ID="RadMultiPage6" runat="server" SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView5" runat="server" Width="100%">
<%--<telerik:RadAjaxPanel ID="RadAjaxPanel5" runat="server">--%>
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"
ShowFooter="True" GroupingEnabled="False" ShowStatusBar="true"
AllowAutomaticInserts="False" AllowAutomaticUpdates="False" AllowAutomaticDeletes="true"
OnNeedDataSource= "rggstAcCode_NeedDataSource" OnItemDataBound="rggstAcCode_ItemDataBound"
OnInsertCommand="rggstAcCode_InsertCommand" OnDeleteCommand="rggstAcCode_DeleteCommand"
OnUpdateCommand="rggstAcCode_UpdateCommand" EnableEmbeddedSkins="true" Skin="Outlook">
<mastertableview commanditemdisplay="Top" autogeneratecolumns="false" datakeynames="AccountCodeID"
insertitempageindexaction="ShowItemOnCurrentPage" ShowFooter="True" ShowHeadersWhenNoRecords="true">
<CommandItemSettings AddNewRecordText="New" />
<Columns>
<telerik:GridEditCommandColumn UniqueName="imagebutton1" ButtonType="ImageButton"></telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260" DropDownWidth="310"
EnableLoadOnDemand="True" OnItemsRequested="ddlAccountCode_ItemsRequested" EnableItemCaching="true"
ShowMoreResultsBox="True" EnableVirtualScrolling="true" AllowCustomText="true" MarkFirstMatch="true"
Filter="Contains" HighlightTemplatedItems="true" CausesValidation="true" AppendDataBoundItems="true"
DataTextField="AccountDescription" DataValueField="AccountCodeID"
ShowDropDownOnTextboxClick="false"
OnClientDropDownOpening="OnClientDropDownOpening" OnClientItemsRequested="OnClientItemsRequested">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" OnClientClick="ButtonClicked()" UseSubmitBehavior="true" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
//Other columns
</Columns>
<EditFormSettings>
<EditColumn ButtonType="ImageButton" />
</EditFormSettings>
<PagerStyle AlwaysVisible="True" PageSizeControlType="RadComboBox" />
</mastertableview>
</telerik:RadGrid>
<%--</telerik:RadAjaxPanel>--%>
</telerik:RadPageView>
</telerik:RadMultiPage>
C# code:
protected void ddlAccountCode_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
Session["Text"] = e.Text;
Session["NumberOfItems"] = e.NumberOfItems;
RadComboBox combo = (RadComboBox)sender;
combo.ShowDropDownOnTextboxClick = false;
combo.Items.Clear();
combo.HighlightTemplatedItems = true;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
try
{
GridEditableItem editedItem = (sender as Button).NamingContainer as GridEditableItem;
RadComboBox combo = (RadComboBox)editedItem.FindControl("ddlAccountCode");
//clear the previous items on every new search
combo.Items.Clear();
combo.OpenDropDownOnLoad = true; // opens dropdown of RadComboBox on button click
combo.HighlightTemplatedItems = true; // to highlight the searched text
//Code related to search in RadComboBox
combo.DataBind();
}
catch (Exception ex)
{
}
}
Please let me know how to resolve the 2 issues. Please reply.
Thanks in advance.
Sorry i can't replicate your problem in my environment....
Here is my code using
.aspx
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"
ShowFooter="True" GroupingEnabled="False" ShowStatusBar="true"
AllowAutomaticInserts="False" AllowAutomaticUpdates="False" AllowAutomaticDeletes="true"
OnNeedDataSource="rggstAcCode_NeedDataSource">
<MasterTableView CommandItemDisplay="Top" AutoGenerateColumns="false"
InsertItemPageIndexAction="ShowItemOnCurrentPage" ShowFooter="True" ShowHeadersWhenNoRecords="true">
<CommandItemSettings AddNewRecordText="New" />
<Columns>
<telerik:GridEditCommandColumn UniqueName="imagebutton1" ButtonType="ImageButton"></telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260" DropDownWidth="310"
EnableItemCaching="true" ShowMoreResultsBox="True" EnableVirtualScrolling="true" AllowCustomText="true"
MarkFirstMatch="true" Filter="Contains" HighlightTemplatedItems="true" CausesValidation="true"
AppendDataBoundItems="true" ShowDropDownOnTextboxClick="false" OnItemsRequested="ddlAccountCode_ItemsRequested">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
<EditFormSettings>
<EditColumn ButtonType="ImageButton" />
</EditFormSettings>
<PagerStyle AlwaysVisible="True" PageSizeControlType="RadComboBox" />
</MasterTableView>
</telerik:RadGrid>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("AccountCode");
dt.Columns.Add("AccountDescription");
for (int i = 0; i < 10; i++) dt.Rows.Add("AccountCode" + i, "AccountDescription" + i);
ViewState["data"] = dt;
// Bind
RGGSTAcCode.DataSource = dt;
RGGSTAcCode.DataBind();
// Dispose
dt.Dispose();
}
}
protected void rggstAcCode_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RGGSTAcCode.DataSource = ViewState["data"] as DataTable;
}
protected void ddlAccountCode_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
Session["Text"] = e.Text;
Session["NumberOfItems"] = e.NumberOfItems;
RadComboBox combo = (RadComboBox)sender;
combo.ShowDropDownOnTextboxClick = false;
combo.Items.Clear();
combo.HighlightTemplatedItems = true;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
try
{
GridEditableItem editedItem = (sender as Button).NamingContainer as GridEditableItem;
RadComboBox combo = (RadComboBox)editedItem.FindControl("ddlAccountCode");
//clear the previous items on every new search
combo.Items.Clear();
combo.OpenDropDownOnLoad = true; // opens dropdown of RadComboBox on button click
combo.HighlightTemplatedItems = true; // to highlight the searched text
//Code related to search in RadComboBox
combo.DataSource = ViewState["data"] as DataTable;
combo.DataTextField = "AccountCode";
combo.DataValueField = "AccountCode";
combo.DataBind();
}
catch (Exception ex)
{
}
}
Result as below
I removed the RadAjaxPanel and used the asp.net UpdatePanel and the issue resolved as of now as the page will not post back on button click and above behavior will never happen. But I dont know why it is creating issue when I do not put RadGrid in RadAjaxPanel or UpdatePanel.

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

Oracle Count with Function

I have a SQL like this.
SELECT A.HESAP_NO, A.TEKLIF_NO1 || '/' || A.TEKLIF_NO2 AS TEKLIF
MV_K(A.TEKLIF_NO1,A.TEKLIF_NO2, A.DATE) AS KV
FROM S_TEKLIF A
When i want calculate MV_K(A.TEKLIF_NO1,A.TEKLIF_NO2, A.DATE)/COUNT(#TEKLIF) but it doesn't work.
I use Oracle.
How can i divide in Oracle like that?
Here is my FULL aspx code;
<%# Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# Import Namespace="System" %>
<%# Import Namespace="System.Configuration" %>
<%# Import Namespace="System.IO" %>
<%# Import Namespace="System.Text" %>
<%# Import Namespace="System.Data.SqlClient" %>
<%# Import Namespace="System.Web.UI.WebControls" %>
<%# Import Namespace="System.Collections.Generic" %>
<%# Import Namespace="System.Linq" %>
<%# Import Namespace="System.Web" %>
<%# Import Namespace="System.Web.UI" %>
<%# Import Namespace="System.Collections" %>
<%# Import Namespace="System.Data.OracleClient" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Calculate.Visible = false;
}
protected void Calculate_Click(object sender, EventArgs e)
{
Calculate.Visible = true;
double sumMV = 0;
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gvr.FindControl("NameCheckBoxField2");
if (cb.Checked == true)
{
double amount = Convert.ToDouble(gvr.Cells[9].Text);
sumMV += amount;
}
}
GridView1.FooterRow.Cells[9].Text = String.Format("{0:n}", sumMV);
double sumRISK = 0;
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gvr.FindControl("NameCheckBoxField1");
if (cb.Checked == true)
{
double amount = Convert.ToDouble(gvr.Cells[7].Text);
sumRISK += amount;
}
}
GridView1.FooterRow.Cells[7].Text = String.Format("{0:n}", sumRISK);
double sumKV = 0;
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gvr.FindControl("NameCheckBoxField3");
if (cb.Checked == true)
{
double amount = Convert.ToDouble(gvr.Cells[11].Text);
if (amount != -1)
{
sumKV += amount;
}
}
}
GridView1.FooterRow.Cells[11].Text = String.Format("{0:n}", sumKV);
}
protected void SendToGridview_Click(object sender, EventArgs e)
{
DateTime dt_stb;
Calculate.Visible = true;
string strQuery = string.Empty;
string ConnectionString = ConfigurationManager.ConnectionStrings["ora"].ConnectionString;
OracleConnection myConnection = new OracleConnection(ConnectionString);
string txtBoxText1 = ((TextBox)Page.FindControl("TextBox1")).Text;
if (txtBoxText1 != "")
{
strQuery = #"SELECT A.HESAP_NO, A.TEKLIF_NO1 || '/' || A.TEKLIF_NO2 AS TEKLIF, A.MUS_K_ISIM AS MUSTERI,
B.MARKA, C.SASI_NO, C.SASI_DURUM, D.TAS_MAR, NVL(RISK_SASI(A.TEKLIF_NO1, A.TEKLIF_NO2, C.URUN_SIRA_NO, C.SIRA_NO, :S_TARIH_B),0) AS RISK,
NVL(MV_SASI(A.TEKLIF_NO1, A.TEKLIF_NO2, C.SIRA_NO, C.URUN_SIRA_NO, :S_TARIH_B),0) AS MV,
MV_K(A.TEKLIF_NO1,A.TEKLIF_NO2, :S_TARIH_B)/COUNT(*) OVER() AS KV
FROM S_TEKLIF A, S_URUN B, S_URUN_DETAY C, KOC_KTMAR_PR D
WHERE A.TEKLIF_NO1 || A.TEKLIF_NO2 = B.TEKLIF_NO1 || B.TEKLIF_NO2
AND A.TEKLIF_NO1 || A.TEKLIF_NO2 = C.TEKLIF_NO1 || C.TEKLIF_NO2
AND B.SIRA_NO = C.URUN_SIRA_NO
AND C.SASI_DURUM IN ('A','R')
AND B.DISTRIBUTOR = D.DIST_KOD
AND B.MARKA = D.MARKA_KOD
AND B.URUN_KOD = D.TAS_KOD ";
}
string param = "";
foreach (ListItem l in CheckBoxList1.Items)
{
if (l.Selected)
{
param += string.Format("'{0}'", l.Value);
param += ",";
}
}
try
{
param = param.Remove(param.Length - 1);
strQuery = strQuery + " AND A.HESAP_NO IN (" + param + ")";
OracleCommand myCommand = new OracleCommand(strQuery, myConnection);
myCommand.CommandType = System.Data.CommandType.Text;
myCommand.Connection = myConnection;
myCommand.CommandText = strQuery;
dt_stb = DateTime.Parse(txtBoxText1);
myCommand.Parameters.AddWithValue(":S_TARIH_B", dt_stb);
myConnection.Open();
OracleDataReader dr = myCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
GridView1.DataSource = dr;
GridView1.DataBind();
GridView1.Visible = true;
myConnection.Close();
}
catch
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('Choose at least one customer!')", true);
Calculate.Visible = false;
GridView1.Visible = false;
TextBox1.Text = string.Empty;
}
double sumMV = 0;
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gvr.FindControl("NameCheckBoxField2");
if (cb.Checked == true)
{
double amountMV = Convert.ToDouble(gvr.Cells[9].Text);
sumMV += amountMV;
}
}
GridView1.FooterRow.Cells[9].Text = String.Format("{0:n}", sumMV);
double sumRISK = 0;
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gvr.FindControl("NameCheckBoxField1");
if (cb.Checked == true)
{
double amountBV = Convert.ToDouble(gvr.Cells[7].Text);
sumRISK += amountBV;
}
}
GridView1.FooterRow.Cells[7].Text = String.Format("{0:n}", sumRISK);
double sumKV = 0;
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gvr.FindControl("NameCheckBoxField3");
if (cb.Checked == true)
{
double amountKV = Convert.ToDouble(gvr.Cells[11].Text);
if (amountKV != -1)
{
sumKV += amountKV;
}
}
}
GridView1.FooterRow.Cells[11].Text = String.Format("{0:n}", sumKV);
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
#form1
{
height: 729px;
width: 1083px;
}
.style1
{
width: 265px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<br />
<img src="../images/Scania_Logo.gif" style="height: 49px; width: 193px" />
<asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="X-Large"
ForeColor="Blue" Height="40px" Text="BV & RISK SIMULATOR"
Width="329px" style="text-align: center"></asp:Label>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<br />
<div style="OVERFLOW-Y:scroll; WIDTH:362px; HEIGHT:177px">
<br />
<table border="5" bordercolor=blue style="height: 116px; width: 343px">
<tr>
<td class="style1">
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataSourceID="ChechkBoxDataSource" DataTextField="MUS_K_ISIM"
DataValueField="HESAP_NO" Font-Size="12pt">
</asp:CheckBoxList>
</td>
</tr>
</table>
</div>
<div style="width: 331px">
<br />
<asp:Textbox ID="TextBox1" runat="server" Font-Size="X-Small" Height="13px" Font-Names="Verdana" Width="75px" ></asp:Textbox>
<asp:CalendarExtender Format="dd/MM/yyyy" ID="TextBox1_CalendarExtender" runat="server"
TargetControlID="TextBox1">
</asp:CalendarExtender>
<asp:Image ID="ImageButton3" runat="server" ImageUrl="~/images/SmallCalendar.gif"/>
<br />
</div>
<asp:SqlDataSource ID="ChechkBoxDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ora %>"
ProviderName="<%$ ConnectionStrings:ora.ProviderName %>"
SelectCommand="SELECT DISTINCT(A.HESAP_NO),A.MUS_K_ISIM
FROM S_TEKLIF A
ORDER BY A.MUS_K_ISIM">
</asp:SqlDataSource>
<br />
<asp:Button ID="SendToGridview" runat="server" Text="Calculate" Width="73px"
onclick="SendToGridview_Click" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server"
Width="16px" CellPadding="4"
GridLines="None" Height="16px" ForeColor="#333333"
AutoGenerateColumns="False" DataKeyNames="RISK,MV" BorderColor="White"
BorderStyle="Ridge" ShowFooter="True" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField HeaderText="HESAP" DataField="HESAP_NO" />
<asp:BoundField HeaderText="TEKLIF" DataField="TEKLIF" >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField HeaderText="MUSTERI" DataField="MUSTERI" >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField HeaderText="MARKA" DataField="MARKA" />
<asp:BoundField HeaderText="SASI" DataField="SASI_NO" >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField HeaderText="DURUM" DataField="SASI_DURUM" />
<asp:BoundField HeaderText="TASIT MARKA" DataField="TAS_MAR" >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField HeaderText="BV" DataField="RISK" DataFormatString="{0:n2}"/>
<asp:templatefield headertext="">
<itemtemplate>
<asp:CheckBox DataField="NameCheckBoxField1" ID="NameCheckBoxField1" Checked="True" runat="server"></asp:CheckBox>
</itemtemplate>
</asp:templatefield>
<asp:BoundField HeaderText="MV" DataField="MV" DataFormatString="{0:n2}"/>
<asp:templatefield headertext="">
<itemtemplate>
<asp:CheckBox DataField="NameCheckBoxField2" ID="NameCheckBoxField2" Checked="True" runat="server"></asp:CheckBox>
</itemtemplate>
</asp:templatefield>
<asp:BoundField HeaderText="KV" DataField="KV" DataFormatString="{0:n2}"/>
<asp:templatefield headertext="">
<itemtemplate>
<asp:CheckBox DataField="NameCheckBoxField3" ID="NameCheckBoxField3" Checked="True" runat="server"></asp:CheckBox>
</itemtemplate>
</asp:templatefield>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" ForeColor="White" Font-Bold="True" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<sortedascendingcellstyle backcolor="#F4F4FD" />
<sortedascendingheaderstyle backcolor="#5A4C9D" />
<sorteddescendingcellstyle backcolor="#D8D8F0" />
<sorteddescendingheaderstyle backcolor="#3E3277" />
<SortedAscendingCellStyle BackColor="#F5F7FB"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#6D95E1"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#E9EBEF"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#4870BE"></SortedDescendingHeaderStyle>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ora %>"
ProviderName="<%$ ConnectionStrings:ora.ProviderName %>"
SelectCommand=" SELECT A.HESAP_NO, A.TEKLIF_NO1 || '/' || A.TEKLIF_NO2 AS TEKLIF, A.MUS_K_ISIM ,
B.MARKA, C.SASI_NO, C.SASI_DURUM, D.TAS_MAR, NVL(RISK_SASI(A.TEKLIF_NO1, A.TEKLIF_NO2, C.URUN_SIRA_NO, C.SIRA_NO, :S_TARIH_B),0) AS RISK,
NVL(MV_SASI(A.TEKLIF_NO1, A.TEKLIF_NO2, C.URUN_SIRA_NO, C.SIRA_NO, :S_TARIH_B),0) AS MV,
MV_K(A.TEKLIF_NO1,A.TEKLIF_NO2, :S_TARIH_B)/COUNT(*) OVER() AS KV, 'NameCheckBoxField1' = 0x1, 'NameCheckBoxField2' = 0x1, 'NameCheckBoxField3' = 0x1
FROM S_TEKLIF A, S_URUN B, S_URUN_DETAY C, KOC_KTMAR_PR D
WHERE A.TEKLIF_NO1 || A.TEKLIF_NO2 = B.TEKLIF_NO1 || B.TEKLIF_NO2
AND A.TEKLIF_NO1 || A.TEKLIF_NO2 = C.TEKLIF_NO1 || C.TEKLIF_NO2
AND B.SIRA_NO = C.URUN_SIRA_NO
AND C.SASI_DURUM IN ('A','R')
AND B.DISTRIBUTOR = D.DIST_KOD
AND B.MARKA = D.MARKA_KOD
AND B.URUN_KOD = D.TAS_KOD ">
</asp:SqlDataSource>
<br />
<asp:Button ID="Calculate" runat="server" onclick="Calculate_Click"
Text="Calculate" />
<br />
<br />
</form>
</body>
</html>
Obviously untested, but it should be something like:
SELECT A.HESAP_NO
, A.TEKLIF_NO1 || '/' || A.TEKLIF_NO2 AS TEKLIF
, MV_K(A.TEKLIF_NO1,A.TEKLIF_NO2, A.DATE) / count(*) over () AS KV
FROM S_TEKLIF A
Explanation: if you want to use count(*), you'd have to aggregate in your query, but you're not doing that. So instead you can use an analytic function count(*) over () which counts the same number for each row.
Hope this helps.
Regards,
Rob.
I think you need to explain better what you are counting in your example. Your query shows values that get returned for each row, then you want to divide by "COUNT(#TEKLIF)"
is that notation meant to be the count of distinct TEKLIFs? Or the count of rows for the TEKLIF in this row? Or the count of all rows in the table?
e.g.)
SELECT A.HESAP_NO
, A.TEKLIF_NO1 || '/' || A.TEKLIF_NO2 AS TEKLIF
, MV_K(A.TEKLIF_NO1,A.TEKLIF_NO2, A.DATE) / count(distinct TEFLIK) over () AS KV
FROM S_TEKLIF A
or
SELECT A.HESAP_NO
, A.TEKLIF_NO1 || '/' || A.TEKLIF_NO2 AS TEKLIF
, MV_K(A.TEKLIF_NO1,A.TEKLIF_NO2, A.DATE) / count(*) over (partition by TEFLIK) AS KV
FROM S_TEKLIF A
or Rob's solution
Hope that one of those helps.