I am new to ASP.NET
ERROR: "The FormView 'FormView1' fired event ItemInserting which wasn't handled. "
I have a FormView that set to Insert Mode when the page first initially loaded. I also want to pre-populated the values in those input textboxes and dropdownlists. So I was able to make it works by using the code behind and write the values to those boxes, but when I click "Insert" LinkButton, it give me that error.
Here is my FormView codes:
<asp:FormView ID="FormView1" DefaultMode="Insert" runat="server"
DateSourceID="dsApprovedCreateNew"
DataKeyNames="ApprovedID"
>
<InsertItemTemplate>
<table class="FormDetail" width="95%" height="100%" align="center" class="FormDetail" >
<tr>
<td class="right">MDF Name:</td>
<td>
<asp:TextBox ID="MDFName" runat="server" Width="50%" Text='<%# Bind("MDFName") %>' > </asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ControlToValidate="MDFName" Text="The MDFName field is required!" runat="server" />
</td>
</tr>
<tr>
<td>Vendor Name</td>
<td>
<asp:DropDownList ID="ddlVendorList" runat="server"></asp:DropDownList>
</td>
</tr>
<tr>
<td>Vendor BU</td>
<td>
<asp:DropDownList ID="ddlVendorBUList" runat="server"></asp:DropDownList>
</td>
</tr>
<tr>
<td class="right">Vendor Quarter:</td>
<td>
<asp:DropDownList ID="VendorQuarter" runat="server" Text='<%# Bind("VendorQuarter") %>'
AppendDataBoundItems="true">
<asp:ListItem Value="Q1">Q1</asp:ListItem>
<asp:ListItem Value="Q2">Q2</asp:ListItem>
<asp:ListItem Value="Q3">Q3</asp:ListItem>
<asp:ListItem Value="Q4">Q4</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="right">MDF Amount:</td>
<td>
<asp:TextBox ID="MDFAmount" runat="server" Width="20%" TextMode="SingleLine" Text='<%# Bind("VendorQuarter") %>'></asp:TextBox>
<asp:CustomValidator ID="RangeValidator3" runat="server" ControlToValidate="MDFAmount"
ErrorMessage="Enter numerical value only!" ClientValidationFunction="validateNumber"/>
<asp:RequiredFieldValidator ControlToValidate="MDFAmount" Text="The MDFAmount field is required!" runat="server" />
<%--
<asp:RegularExpressionValidator ID="RangeValidator4" runat="server" ControlToValidate="MDFAmount"
Display="Dynamic" ErrorMessage="*Enter numerical value only"
ValidationExpression="^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$"/>
--%>
</td>
</tr>
<tr>
<td class="right">Begin Date (mm/dd/yyyy):</td>
<td>
<asp:TextBox ID="BeginDate" runat="server" Width="50%" TextMode="SingleLine" DataFormatString="{0:MM/dd/yyyy}"
ApplyFormatInInsertMode="true" ></asp:TextBox>
<asp:RegularExpressionValidator ID="RangeValidator1" runat="server" ControlToValidate="BeginDate" ForeColor="Red"
ErrorMessage="Enter Valid Date in dd/mm/yyyy format." SetFocusOnError="True" Display="Dynamic" Type="Date"
ValidationExpression="^(0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d$">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="right">End Date (mm/dd/yyyy):</td>
<td>
<asp:TextBox ID="EndDate" runat="server" Width="50%"></asp:TextBox>
<asp:RegularExpressionValidator ID="RangeValidator2" runat="server" ControlToValidate="EndDate" ForeColor="Red"
ErrorMessage="Enter Valid Date in dd/mm/yyyy format." SetFocusOnError="True" Display="Dynamic" Type="Date"
ValidationExpression="^(0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d$"/>
</td>
</tr>
<tr>
<td class="right">MDF Summary:</td>
<td>
<asp:TextBox ID="MDFSummary" TextMode="MultiLine" Width="50%" Height="100" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="right">Status:</td>
<td>
<asp:DropDownList ID="Status" runat="server"
AppendDataBoundItems="true">
<asp:ListItem>Active</asp:ListItem>
<asp:ListItem>Inactive</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2">
<asp:linkbutton id="InsertButton"
text="Insert"
commandname="Insert"
runat="server" />
<asp:linkbutton id="CancelButton"
text="Cancel"
commandname="Cancel"
runat="server" />
</td>
</tr>
</table>
<asp:HiddenField ID="CreatedBy" runat="server" value="44444"/>
</InsertItemTemplate>
</asp:FormView>
<asp:sqldatasource id="dsApprovedCreateNew"
connectionstring="<%$ ConnectionStrings:ConnectionString%>"
SelectCommand="SELECT p.*
, (SELECT VendorName FROM MDF_Vendor WHERE VendorID = p.VendorID) AS VendorName
, (SELECT VendorBUName FROM MDF_VendorBU WHERE VendorBUID = p.VendorBUID) AS VendorBUName
FROM dbo.MDF_Proposed p Where p.ProposedID = 63"
InsertCommand = "INSERT INTO [MDF_Approved] ([VendorID], [VendorBUID], [MDFName]
, [BeginDate], [EndDate], [CreatedBy])
VALUES (#VendorID, #VendorBUID, #MDFName, #BeginDate, #EndDate, '1234') "
runat="server">
<SelectParameters>
<asp:QueryStringParameter Name="ProposedID" QueryStringField="ProposedID" runat="server" />
</SelectParameters>
</asp:sqldatasource>
</form>
The Code Behind (I am a newbie, so don't laugh at my codes, suggestions are welcome)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//FormView1.PreRender += FormView1_PreRender;
//FormView1.DataBinding += FormView1_DataBinding;
if (!IsPostBack)
{
//Response.Write("ProposedID: " + Request.QueryString["ProposedID"]);
int ProposedID = FetchQueryStringIdentifierByKey("ProposedID");
Response.Write("ProposedID : " + ProposedID);
//FormView1.DataSource = this.GetData(ProposedID);
//FormView1.DataBind();
FillFormValues(ProposedID);
//GetData(ProposedID);
}
}
protected int FetchQueryStringIdentifierByKey(string key)
{
int identifier;
var isInt = int.TryParse(Request.QueryString[key], out identifier);
return (isInt) ? identifier : 0;
}
private DataSet GetData(int RecID)
{
string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string query = "SELECT * FROM MDF_Proposed WHERE ProposedID = 63";
SqlCommand cmd = new SqlCommand(query);
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("#RecID", SqlDbType.Int, 10);
param[0].Value = 1; // RecID;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
using (SqlConnection con = new SqlConnection(GetConnectionString()))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
private void FillFormValues(int RecID)
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM MDF_Proposed WHERE ProposedID = 63";
cmd.Parameters.AddWithValue("#RecID", RecID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
if (FormView1.CurrentMode == FormViewMode.Insert)
{
Response.Write("The Mode: " + FormView1.CurrentMode);
TextBox MDFName = (TextBox)FormView1.FindControl("MDFName");
MDFName.Text = objDs.Tables[0].Rows[0]["MDFName"].ToString();
TextBox MDFAmount = (TextBox)FormView1.FindControl("MDFAmount");
MDFAmount.Text = objDs.Tables[0].Rows[0]["MDFAmount"].ToString();
TextBox BeginDate = (TextBox)FormView1.FindControl("BeginDate");
BeginDate.Text = FormatDateNoTime(objDs.Tables[0].Rows[0]["BeginDate"].ToString());
TextBox EndDate = (TextBox)FormView1.FindControl("EndDate");
EndDate.Text = FormatDateNoTime(objDs.Tables[0].Rows[0]["EndDate"].ToString());
fillVendorDLL(Convert.ToInt32(objDs.Tables[0].Rows[0]["VendorID"]));
fillVendorBUDLL(Convert.ToInt32(objDs.Tables[0].Rows[0]["VendorID"]), Convert.ToInt32(objDs.Tables[0].Rows[0]["VendorBUID"]));
TextBox MDFSummary = (TextBox)FormView1.FindControl("MDFSummary");
MDFSummary.Text = objDs.Tables[0].Rows[0]["MDFSummary"].ToString();
}
else
{
Response.Write("Nothing");
}
}
else
{
Response.Write("No Record found");
}
}
protected void fillVendorDLL(int VendorID)
{
//DropDownList ddlVendor = (DropDownList)sender;
// DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl("updateVendorName");
//DropDownList ddlVendor = (DropDownList)sender;
//DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl(ddlID);
DropDownList ddlVendor =
(DropDownList)FormView1.FindControl("ddlVendorList");
if (ddlVendor != null)
{
//Response.Write("SelectChanged");
//int VendorID = Convert.ToInt32(ddlVendor.SelectedValue.ToString());
//Response.Write("VendorID: " + VendorID);
ddlVendor.Items.Clear();
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorID, VendorName FROM dbo.MDF_Vendor";
cmd.Parameters.AddWithValue("#VendorID", VendorID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in objDs.Tables[0].Rows)
{
ddlVendor.Items.Insert(0, new ListItem((dr["VendorName"]).ToString(), (dr["VendorID"]).ToString()));
ddlVendor.SelectedValue = Convert.ToString(VendorID);
}
}
}
}
protected void fillVendorBUDLL(int VendorID, int VendorBUID)
{
//DropDownList ddlVendor = (DropDownList)sender;
// DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl("updateVendorName");
//DropDownList ddlVendor = (DropDownList)sender;
//DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl(ddlID);
DropDownList ddlVendorBU =
(DropDownList)FormView1.FindControl("ddlVendorBUList");
if (ddlVendorBU != null)
{
//Response.Write("SelectChanged");
//int VendorID = Convert.ToInt32(ddlVendor.SelectedValue.ToString());
//Response.Write("VendorID: " + VendorID);
ddlVendorBU.Items.Clear();
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorBUID, VendorBUName FROM dbo.MDF_VendorBU WHERE VendorID = #VendorID";
cmd.Parameters.AddWithValue("#VendorID", VendorID);
cmd.Parameters.AddWithValue("#VendorBUID", VendorBUID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in objDs.Tables[0].Rows)
{
ddlVendorBU.Items.Insert(0, new ListItem((dr["VendorBUName"]).ToString(), (dr["VendorBUID"]).ToString()));
ddlVendorBU.SelectedValue = Convert.ToString(VendorBUID);
}
}
}
}
public string GetConnectionString(){
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
private void ExecuteInsert(string VendorName, string VendorBU, string MDFAmount
, string StartDate, string EndDate, string VendorQuarter, string MDFName, String MDFSummary, string Status, string CreatedBy)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO MDF_Proposed (VendorID, VendorBUID, MDFAmount, BeginDate, EndDate, VendorQuarter
, MDFName, MDFSummary, Status, CreatedBy) VALUES "
+ " (#VendorID, #VendorBUID, #MDFAmount, #StartDate, #EndDate, #VendorQuarter, #MDFName, #MDFSummary, #Status, #CreatedBy)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[10];
param[0] = new SqlParameter("#VendorID", SqlDbType.VarChar, 50);
param[1] = new SqlParameter("#VendorBUID", SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#MDFAmount", SqlDbType.Decimal);
param[2].Precision = 19;
param[2].Scale = 4;
param[3] = new SqlParameter("#StartDate", SqlDbType.DateTime);
param[4] = new SqlParameter("#EndDate", SqlDbType.DateTime);
param[5] = new SqlParameter("#VendorQuarter", SqlDbType.VarChar, 50);
param[6] = new SqlParameter("#MDFName", SqlDbType.VarChar, 50);
param[7] = new SqlParameter("#MDFSummary", SqlDbType.VarChar, 2000);
param[8] = new SqlParameter("#Status", SqlDbType.VarChar, 50);
param[9] = new SqlParameter("#CreatedBy", SqlDbType.Int, 10);
param[0].Value = VendorName;
param[1].Value = VendorBU;
param[2].Value = MDFAmount;
param[3].Value = StartDate;
param[4].Value = EndDate;
param[5].Value = VendorQuarter;
param[6].Value = MDFName;
param[7].Value = MDFSummary;
param[8].Value = Status;
param[9].Value = CreatedBy;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
//ClientScript.RegisterStartupScript(this.GetType(), "scriptid", window.parent.location.href='ViewVendors.aspx'", true);
Response.Write("<script>window.parent.location = 'ProposalListView.aspx';</script>");
//Response.Redirect("ProposalListView.aspx");
//Response.Write("<script>this.dialog('close');</script>");
}
}
public static void ClearControls(Control Parent){
if (Parent is TextBox)
{ (Parent as TextBox).Text = string.Empty; }
else
{
foreach (Control c in Parent.Controls)
ClearControls(c);
}
}
public string FormatDateNoTime(string input)
{
string thedate;
DateTime strDate = DateTime.Parse(input);
thedate = strDate.ToString("MM/dd/yyyy");
return thedate;
}
}
You can also use the DataBound event:
protected void FormView1_DataBound(object sender, EventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.Insert)
{
var textBox = (TextBox) FormView1.FindControl("MyTextBox");
textBox.Text = "Default Value";
}
}
Related
I have problem with files. I'm trying to download files from databases
through gridview, but after I download them, they are with wrong name and extensions. Their name are my web form name and their extensions are .aspx.
In the database they are saved in the correct format.
Here are my code-behind
public partial class data : System.Web.UI.Page
{
string cs = ConfigurationManager.ConnectionStrings["DecumentsConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillData();
}
}
private void FillData()
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("getDecuments", cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
FileInfo filename = new FileInfo(FileUpload1.FileName);
byte[] documentContent = FileUpload1.FileBytes;
string name = filename.Name;
string extnt = filename.Extension;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("savedocument", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#Content", documentContent);
cmd.Parameters.AddWithValue("#extn",extnt);
con.Open();
cmd.ExecuteNonQuery();
}
}
private void Donwload(int id)
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("getdocument", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID", id);
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
}
string name = dt.Rows[0]["name"].ToString();
byte[] document = (byte[])dt.Rows[0]["DocumentContent"];
Response.ClearContent();
Response.ContentType = "application/octetstream";
Response.AddHeader("Content-Dispisition", string.Format("attachment;filename={0}", name));
Response.AddHeader("Content-Lenght", document.Length.ToString());
Response.BinaryWrite(document);
Response.Flush();
Response.Close();
}
protected void OpenDocument(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
GridViewRow gr = (GridViewRow)lnk.NamingContainer;
int id = int.Parse(GridView1.DataKeys[gr.RowIndex].Value.ToString());
Donwload(id);
}
}
}
and my html
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Document"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" />
<br />
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID">
<Columns>
<asp:TemplateField HeaderText="Documents">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" OnClick="OpenDocument" runat="server" Text='<%# Eval("name") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
</div>
</form>
img
I have a asp calendar utility in ascx page. I want to unselect the selected date on second click on the same date. The following are my codes. Kindly help in this.
<%# Control Language="C#" AutoEventWireup="true"CodeFile="Calendar.ascx.cs"Inherits="WebUserControl" %>
<table>
<tr>
<td width="100%">
<asp:DropDownList ID="ddlyear" runat="server"
onselectedindexchanged="ddlyear_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="2014" Value="2014" Selected="True"></asp:ListItem>
<asp:ListItem Text="2015" Value="2015"></asp:ListItem>
<asp:ListItem Text="2016" Value="2016"></asp:ListItem>
<asp:ListItem Text="2017" Value="2017"></asp:ListItem>
<asp:ListItem Text="2018" Value="2018"></asp:ListItem>
<asp:ListItem Text="2019" Value="2019"></asp:ListItem>
<asp:ListItem Text="2020" Value="2020"></asp:ListItem>
<asp:ListItem Text="2021" Value="2021"></asp:ListItem>
<asp:ListItem Text="2022" Value="2022"></asp:ListItem>
<asp:ListItem Text="2023" Value="2023"></asp:ListItem>
<asp:ListItem Text="2024" Value="2024"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td width="100%" dir="ltr">
<asp:DataList ID="DataList1" runat="server" HorizontalAlign="Center"
RepeatDirection="Horizontal" RepeatColumns="4"
onitemdatabound="DataList1_ItemDataBound"
>
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="txt1" runat="server" Text='<%#Eval("Month") %>' Visible="false" Font-Names="Arial"></asp:Label>
<asp:HiddenField ID="hdn1" runat="server" />
<asp:Calendar ID="Calendar1" runat="server" NextPrevFormat="CustomText" SelectionMode="Day" NextMonthText="" PrevMonthText="" Font-Names="A" OtherMonthDayStyle-BorderStyle="NotSet" OtherMonthDayStyle-Wrap="False" OtherMonthDayStyle-ForeColor="#CCCCCC">
<TitleStyle
BackColor="#6EC347"
ForeColor="White"
Height="36"
Font-Size="Large"
Font-Names="Arial"
/>
<SelectedDayStyle
BackColor="Green"
BorderColor="SpringGreen"
/>
</asp:Calendar>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
My code behind for this ascx page is
public partial class WebUserControl : System.Web.UI.UserControl
{
int month = 1;
public event EventHandler YearChanged;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadcalendar();
}
}
private void loadcalendar()
{
DataTable dt = new DataTable();
dt.Columns.Add("Month", typeof(string));
dt.Rows.Add("January");
dt.Rows.Add("February");
dt.Rows.Add("March");
dt.Rows.Add("April");
dt.Rows.Add("May");
dt.Rows.Add("June");
dt.Rows.Add("July");
dt.Rows.Add("August");
dt.Rows.Add("September");
dt.Rows.Add("October");
dt.Rows.Add("Novemeber");
dt.Rows.Add("December");
DataList1.DataSource = dt;
DataList1.DataBind();
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
string year = ddlyear.SelectedValue.ToString();
String str = ((Label)e.Item.FindControl("txt1")).Text;
DateTime Now = DateTime.Now;
DateTime TempDate = new DateTime(Convert.ToInt32(year), month, 1);
// DateTime TempDate = new DateTime(Now.Year,Now.Month, 1);
((Calendar)e.Item.FindControl("Calendar1")).VisibleDate = TempDate;
month = month + 1;
}
}
protected void ddlyear_SelectedIndexChanged(object sender, EventArgs e)
{
loadcalendar();
YearChanged(sender, e);
}
}
My Aspx.cs page code is like this
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
cnn.ConnectionString = connStr;
cnn.Open();
string eid;
string ename = DropDownList2.SelectedValue.ToString();
if (ename == "1")
{
eid = "1";
}
else
{
eid = "2";
}
int cid = Int32.Parse(DropDownList1.SelectedValue.ToString());
//String sqlSelect = String.Format("Select Customer_Id from Customer where Customer_Name='{0}'", cname);
//SqlCommand cmd1 = new SqlCommand(sqlSelect, cnn);
//int cid = (int)cmd1.ExecuteScalar();
DataList dl;
dl = ((DataList)patchCalendar.FindControl("DataList1"));
foreach (DataListItem dli in dl.Items)
{
string month = Convert.ToString(((Label)dli.FindControl("txt1")).Text);
string day = Convert.ToString(((Calendar)dli.FindControl("Calendar1")).SelectedDate.Day);
string year = Convert.ToString(((Calendar)dli.FindControl("Calendar1")).SelectedDate.Year);
string date = ((Calendar)dli.FindControl("Calendar1")).SelectedDate.ToShortDateString();
if (date == "1/1/0001")
{
year = null;
date = null;
day = null;
}
else
{
SqlCommand cmd = new SqlCommand("insert into Patching_Dates values(#cid,#eid,#year,#month,#day,#date)", cnn);
cmd.Parameters.AddWithValue("#cid", cid);
cmd.Parameters.AddWithValue("#eid", eid);
cmd.Parameters.AddWithValue("#year", year);
cmd.Parameters.AddWithValue("#month", month);
cmd.Parameters.AddWithValue("#day", day);
cmd.Parameters.AddWithValue("#date", date);
cmd.ExecuteNonQuery();
}
}
cnn.Close();
string act = "Patching Dates Added";
cnn.Open();
SqlCommand cmd2 = new SqlCommand("insert into Logs values(#Username,#Activity,#Time)", cnn);
cmd2.Parameters.AddWithValue("#Username", (string)(Session["user"]));
cmd2.Parameters.AddWithValue("#Activity", act);
cmd2.Parameters.AddWithValue("#Time", System.DateTime.Now.ToString());
cmd2.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
First check Calendar1 control having value if yes then reset it by this
Calendar1.SelectedDates.Clear();
I am trying to use Autocomplete Extender in my Project but its not working and I am using Vs2008 .net framework 3.5
and also it gives me error for grid-view paging that source is not available
this my .aspx code
<asp:TextBox ID="txtsearch" runat="server" Width="158px" CssClass="text"
Height="22px" ontextchanged="txtsearch_TextChanged"/>
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
ServiceMethod="GetFilterCategoryName" CompletionSetCount="1" CompletionInterval="10"
EnableCaching="true" MinimumPrefixLength="1" TargetControlID="txtsearch"
UseContextKey="true">
</cc1:AutoCompleteExtender>
this is my Axpx.cs code
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod()]
public static List<string> GetFilterCategoryName(string prefixText)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("select Question from quick_search where Question like #Name+'%'", conn);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> answer = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
answer.Add(dt.Rows[i][1].ToString());
}
return answer;
}
Add a script Manager to the aspx file.
Try like this
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods = "true"></asp:ScriptManager>
<asp:TextBox ID="txtsearch" runat="server" Width="158px" CssClass="text" Height="22px" ontextchanged="txtsearch_TextChanged"/>
<cc1:AutoCompleteExtender ServiceMethod="GetFilterCategoryName"
MinimumPrefixLength="1"
CompletionInterval="0" EnableCaching="false" CompletionSetCount="10"
TargetControlID="txtsearch"
ID="autoCompleteExtender1" runat="server" FirstRowSelected = "false">
</cc1:AutoCompleteExtender>
COde Behind:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod()]
public static List<string> GetFilterCategoryName(string prefixText)
{
SqlConnection conn = new sqlConnection(ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("select Question from quick_search where Question like #Name+'%'", conn);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> answer = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
answer.Add(dt.Rows[i][1].ToString());
}
return answer;
}
My requirement is same as stockoverflow tag display. I have a repeater control in which i am binding few columns. Now i want to display different tags associated with the corresponding thread. Please find the code...
<asp:Repeater ID="repForumThread" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<table width="100%">
<tr>
<td>
<asp:HyperLink ID="hlCategory" runat="server" NavigateUrl='<%#GetRouteUrl("CategoryRoute", new {CategoryNo= Eval("CategoryId"),CategoryName = Eval("CategoryTitle").ToString().ToLower().Trim().Replace(" ","-")}) %>'
Text='<%# DataBinder.Eval(Container.DataItem, "CategoryTitle")%>'></asp:HyperLink>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblThreadTitle" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "ThreadTitle") %>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:HyperLink ID="hlThreadCreatedBy" runat="server" NavigateUrl='<%#GetRouteUrl("ProfileRoute", new {Member= Eval("MemberId"),MemberName = Eval("ThreadCreatedBy").ToString().ToLower().Trim().Replace(" ","-")}) %>'
Text='<%# DataBinder.Eval(Container.DataItem, "ThreadCreatedBy")%>'></asp:HyperLink>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblCreatedOn" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"ThreadCreatedOn") %>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblDescription" runat="server" CssClass="HeaderTextSmall" Text='<%#DataBinder.Eval(Container.DataItem, "ThreadDescription")%>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:PlaceHolder ID="phTag" runat="server"></asp:PlaceHolder>
</td>
</tr>
</table>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
public void BindRepForumThread()
{
SqlConnection dBConnection = null;
try
{
dBConnection = new SqlConnection();
DataTable dtTag = new DataTable();
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SP_GetThreadDetails", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#threadId", SqlDbType.Int).Value = threadId;
dBConnection.Open();
dataAdapter.SelectCommand = cmd;
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
DataTable dtThread = new DataTable();
DataRow drThread;
dtThread.Columns.Add("ThreadId");
dtThread.Columns.Add("CategoryId");
dtThread.Columns.Add("CategoryTitle");
dtThread.Columns.Add("ThreadTitle");
dtThread.Columns.Add("ThreadDescription");
dtThread.Columns.Add("ThreadCreatedBy");
dtThread.Columns.Add("ThreadCreatedOn");
dtThread.Columns.Add("MemberId");
dtThread.Columns.Add("TagId");
dtThread.Columns.Add("TagDescription");
foreach (DataRow dr in ds.Tables[0].Rows)
{
drThread = dtThread.NewRow();
drThread["ThreadId"] = dr["T_ThreadId"];
drThread["CategoryId"] = dr["C_CategoryId"];
drThread["CategoryTitle"] = dr["C_CategoryTitle"];
drThread["ThreadTitle"] = dr["T_ThreadTitle"];
drThread["ThreadDescription"] = dr["T_ThreadDescription"];
drThread["ThreadCreatedBy"] = dr["Mem_MemberUserName"];
drThread["ThreadCreatedOn"] = dr["T_ThreadCreatedOn"];
drThread["MemberId"] = dr["T_ThreadCreatedBy"];
if (ds.Tables[1].Rows.Count > 0)
{
phTag.Controls.Clear();
foreach (DataRow dr1 in ds.Tables[1].Rows)
{
HyperLink hlTag = new HyperLink();
hlTag.Text = dr1["Tg_TagName"].ToString();
int TagId = Convert.ToInt32(dr1["Tg_TagId"].ToString());
hlTag.ID = "hlTag" + TagId.ToString();
hlTag.NavigateUrl = hlTag.GetRouteUrl("TagRoute", new { Id = TagId, TagName = hlTag.Text.ToString().ToLower().Trim().Replace(" ", "-") });
phTag.Controls.Add(hlTag);
}
}
dtThread.Rows.Add(drThread);
}
repForumThread.DataSource = dtThread;
repForumThread.DataBind();
dBConnection.Close();
}
}
catch (Exception Ex)
{
throw Ex;
}
finally
{
// Close data reader object and database connection
if (dBConnection.State == ConnectionState.Open)
dBConnection.Close();
}
}
evreything is working fine. I am able to generate hyperlinks dynamically but I am not able to display the created hyperlinks & it is throwing the error "Object reference not set to an instance of an object" for placeholder.
Thanks in advance.
Well I have resolved the problem. I was missing OnItemCreate function of repeater cotrol where we can findcontrol of a place holder & then we can add hyperlinks dynamically.
protected void repForumThread_ItemCrteated(object sender, RepeaterItemEventArgs e)
{
DataRowView drv = e.Item.DataItem as DataRowView;
DataTable dtTag = new DataTable();
if (Cache["TagData"] != null)
{
dtTag = (DataTable)Cache["TagData"];
}
if (dtTag.Rows.Count > 0)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
PlaceHolder plTag = e.Item.FindControl("phTag") as PlaceHolder;
if (plTag != null)
{
plTag.Controls.Clear();
foreach (DataRow dr1 in dtTag.Rows)
{
HyperLink hlTag = new HyperLink();
hlTag.Text = dr1["Tg_TagName"].ToString();
int TagId = Convert.ToInt32(dr1["Tg_TagId"].ToString());
hlTag.ID = "hlTag" + TagId.ToString();
hlTag.NavigateUrl = hlTag.GetRouteUrl("TagRoute", new { Id = TagId, TagName = hlTag.Text.ToString().ToLower().Trim().Replace(" ", "-") });
plTag.Controls.Add(hlTag);
}
}
}
}
}
Untitled Page
<telerik:GridTemplateColumn Visible="false">
<ItemTemplate>
<asp:Label ID="lblEmpID" runat="server" Text='<%# bind("pid") %>'>
</asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn UniqueName="Fname" HeaderText="Fname" DataField="Fname" CurrentFilterFunction="NotIsNull" SortExpression="Fname">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="Lname" HeaderText="Lname" DataField="Lname" CurrentFilterFunction="NotIsNull" SortExpression="Lname">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="Designation" HeaderText="Designation" DataField="Designation" CurrentFilterFunction="NotIsNull" SortExpression="Designation">
</telerik:GridBoundColumn>
<telerik:GridEditCommandColumn>
</telerik:GridEditCommandColumn>
<telerik:GridButtonColumn CommandName="Delete" Text="Delete" UniqueName="column">
</telerik:GridButtonColumn>
</Columns>
<EditFormSettings>
<FormTemplate>
<table>
<tr>
<td>Fname*</td>
<td>
<asp:HiddenField ID="Fname" runat="server" Visible="false" />
<asp:TextBox ID="txtFname" runat="server" Text='<%#("Fname")%>'>
</asp:TextBox>
<asp:RequiredFieldValidator ID="EvalFname" ControlToValidate="txtFname" ErrorMessage="Enter Name" runat="server" ValidationGroup="Update">
*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Lname*</td>
<td>
<asp:HiddenField ID="HiddenField1" runat="server" Visible="false" />
<asp:TextBox ID="txtLname" runat="server" Text='<%#("Lname")%>'>
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtLname" ErrorMessage="Enter Name" runat="server" ValidationGroup="Update">
*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Designation*
</td>
<td>
<asp:HiddenField ID="HiddenField2" runat="server" Visible="false" />
<asp:TextBox ID="txtDesignation" runat="server" Text='<%#("Designation")%>'>
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="txtDesignation" ErrorMessage="Enter Designation" runat="server" ValidationGroup="Update">
*</asp:RequiredFieldValidator>
</td>
</tr>
</table>
</FormTemplate>
<EditColumn UpdateText="Update record" UniqueName="EditCommandColumn1" CancelText="Cancel edit">
</EditColumn>
</EditFormSettings>
</MasterTableView>
</telerik:RadGrid>
</form>
this is my code i want to perform validation using the required validators but i think m missing smthin so pls help,
here's my code behind
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using Telerik.Web.UI;
public partial class Default7 : System.Web.UI.Page
{
string strQry;
public SqlDataAdapter da;
public DataSet ds;
public SqlCommand cmd;
public DataTable dt;
string strCon = "Data Source=MINETDEVDATA; Initial Catalog=ML_SuppliersProd; User Id=sa; Password=#MinetApps7;";
public SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
dt = new DataTable();
con = new SqlConnection(strCon);
da = new SqlDataAdapter();
try
{
strQry = "SELECT * FROM table2";
con.Open();
da.SelectCommand = new SqlCommand(strQry,con);
da.Fill(dt);
RadGrid1.DataSource = dt;
}
finally
{
con.Close();
}
}
protected void RadGrid1_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
con = new SqlConnection(strCon);
cmd = new SqlCommand();
GridDataItem item = (GridDataItem)e.Item;
string pid = item.OwnerTableView.DataKeyValues[item.ItemIndex]["pid"].ToString();
con.Open();
string delete = "DELETE from table2 where pid='"+pid+"'";
cmd.CommandText = delete;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
{
GridEditableItem radgriditem = e.Item as GridEditableItem;
string pid = radgriditem.OwnerTableView.DataKeyValues[radgriditem.ItemIndex]["pid"].ToString();
string firstname = (radgriditem["Fname"].Controls[0] as TextBox).Text;
string lastname = (radgriditem["Lname"].Controls[0] as TextBox).Text;
string designation = (radgriditem["Designation"].Controls[0] as TextBox).Text;
con = new SqlConnection(strCon);
cmd = new SqlCommand();
try
{
con.Open();
string update = "UPDATE table2 set Fname='" + firstname + "',Lname='" + lastname + "',Designation='" + designation + "' WHERE pid='" + pid + "'";
cmd.CommandText = update;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
RadGrid1.Controls.Add(new LiteralControl("Unable to update Reason: " + ex.Message));
e.Canceled = true;
}
}
protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
{
GridEditFormInsertItem insertitem = (GridEditFormInsertItem)e.Item;
string firstname = (insertitem["Fname"].Controls[0] as TextBox).Text;
string lastname = (insertitem["Lname"].Controls[0] as TextBox).Text;
string designation = (insertitem["Designation"].Controls[0] as TextBox).Text;
con = new SqlConnection(strCon);
cmd = new SqlCommand();
try
{
con.Open();
String insertQuery = "INSERT into table1(Fname,Lname,Designation) Values ('" + firstname + "','" + lastname + "','" + designation + "')";
cmd.CommandText = insertQuery;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception ex)
{
RadGrid1.Controls.Add(new LiteralControl("Unable to insert Reason:" + ex.Message));
e.Canceled = true;
}
}
}
Does your button have the same ValidationGroup value as your Validator controls?