Exit ListView Update Mode after clicking button - asp.net

I currently am using a listview to edit and update data. When I click edit it goes into the edit format that I want it to. I want to be able to exit the entire edit mode after the update button is clicked. Is this possible?
When I use ListView1.EditIndex = -1 it doesn't go back to the regular view.
protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
updateButton = true;
ListViewItem lvl = ListView1.Items[e.ItemIndex];
var formTitleListBox = (ListBox)lvl.FindControl("ListBox1");
var controlTypeListBox = (ListBox)lvl.FindControl("ControlType");
var formSectionListBox = (ListBox)lvl.FindControl("formsection");
var sortOrderTextBox = (TextBox)lvl.FindControl("SortOrderTextBox");
var subsectionListBox = (ListBox)lvl.FindControl("subsection");
var subSectionTextBox = (TextBox)lvl.FindControl("SubSectionOrderTextBox");
var sectionItemListBox = (ListBox)lvl.FindControl("sectionitem");
var sectionSortOrderTextBox = (TextBox)lvl.FindControl("SectionSortOrderTextBox");
var validationRuleListBox = (ListBox)lvl.FindControl("RuleDesc");
var crossItemListBox = (ListBox)lvl.FindControl("CrossItem");
var hiddenID = (HiddenField)lvl.FindControl("HiddenPrimaryID");
using (SqlConnection connection = new SqlConnection("Data Source=RCK-HRSA-DB01;Initial Catalog=ORHP_Dev03182014;User ID=ohitrural;Password=0h!trural"))
{
try
{
SqlCommand cmd1 = new SqlCommand("UPDATE ORHP_Dev03182014.Core.Form_Section_SubSection_Item_Rel SET FormID = #FormTitle, FormSectionID = #FormSection, SubSectionID = #SubSection, SectionItemID = #SectionItem, SortOrder = #SortOrder, SectionSortOrder = #SectionSortOrder, SubSectionSortOrder = #SubSectionSortOrder, ValidationRulesetId = #RuleDesc, ControlTypeID = #ControlType, CrossItemID = #CrossItem WHERE DataCollectionPeriodID = " + DropDownList2.SelectedValue + " AND FormSectionSubSectionItemRelID = #FormSectionSubSectionID");
connection.Open();
cmd1.Connection = connection;
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("#FormTitle", formTitleListBox.SelectedValue);
cmd1.Parameters.AddWithValue("#ControlType", DbNullIfNull(controlTypeListBox.SelectedValue));
cmd1.Parameters.AddWithValue("#FormSection", formSectionListBox.SelectedValue);
cmd1.Parameters.AddWithValue("#SortOrder", DbNullIfNull(sortOrderTextBox.Text));
cmd1.Parameters.AddWithValue("#SubSection", subsectionListBox.SelectedValue);
cmd1.Parameters.AddWithValue("#SubSectionSortOrder", DbNullIfNull(subSectionTextBox.Text));
cmd1.Parameters.AddWithValue("#SectionItem", sectionItemListBox.SelectedValue);
cmd1.Parameters.AddWithValue("#SectionSortOrder", DbNullIfNull(sectionSortOrderTextBox.Text));
cmd1.Parameters.AddWithValue("#RuleDesc", DbNullIfNull(validationRuleListBox.SelectedValue));
cmd1.Parameters.AddWithValue("#CrossItem", DbNullIfNull(crossItemListBox.SelectedValue));
cmd1.Parameters.AddWithValue("#FormSectionSubSectionID", hiddenID.Value);
cmd1.ExecuteNonQuery();
SqlDataAdapter dt = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
searchDS = new DataSet();
dt.Fill(ds);
searchDS = ds;
UpdatePanel1.Update();
ListView1.DataSource = searchDS;
ListView1.EditIndex = -1;
ListView1.DataBind();
e.Cancel = true;
}
catch (Exception ex)
{
}
}
}

Add ListView1.DataBind(); and also e.Cancel = true;.
// ...
cmd1.ExecuteNonQuery();
ListView1.EditIndex = -1;
ListView1.DataBind()
e.Cancel = true;
// ...
Side-note: remove the empty catch if you want to notice if something goes wrong.

Related

How to create SelectIndexChanged event for multiple selection in asp.net

I want to select multiple item from checkbox list and then fill another check Box list on select index changed event of First check box list but after one selection its not working for another selected items because of "Auto Post Back = true" while debbuging i can see pointer start from page load event. I want after selection of all Item it should be fire "ddlregion_SelectedIndexChanged" so that I can able see all selected Item related value in another check Box List.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRegion();
}
}
Due to this its not fetching data for another selected Items how to solve this issues Please help me.
ddlRegion Code Binding:
public void BindRegion()
{
OracleCommand Cmd = new OracleCommand("select * from regions", con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlregion.DataSource = ds;
ddlregion.DataTextField = "REGION_DESC";
ddlregion.DataValueField = "REGION_CODE";
ddlregion.DataBind();
}
Select Index Changed Event
protected void ddlregion_SelectedIndexChanged(object sender, EventArgs e)
{
ddlDepot.Items.Clear();
ddlDepot.Items.Add(new ListItem("--Select Depot--", ""));
foreach (ListItem item in ddlregion.Items)
{
if (item.Selected == true)
{
string str = "select d.depot_code, d.depot_description from regions r, sub_regions sr, depots d where r.region_code = sr.region_code and sr.sub_region_code = d.sub_region_code and active = 'Y' and r.region_code in " + ddlregion.SelectedValue + "";
OracleCommand Cmd = new OracleCommand(str, con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlDepot.DataSource = ds;
ddlDepot.DataTextField = "DEPOT_DESCRIPTION";
ddlDepot.DataValueField = "DEPOT_CODE";
ddlDepot.DataBind();
}
}
}
You need to build your region list for the SQL, then once done call your SQL and Bind.
string regions = "";
bool regionSelected = false;
foreach (ListItem item in ddlregion.Items)
{
if (item.Selected == true)
{
regions += item.SelectedValue + ",";
regionSelected = true;
}
}
// looping done so clean up string for SQL
regions = "(" + regions.TrimEnd(',') + " )";
//only run if a region is selected
if(regionSelected)
{
string str = "select d.depot_code, d.depot_description from regions r, sub_regions sr,
depots d where r.region_code = sr.region_code and
sr.sub_region_code = d.sub_region_code and active = 'Y' and r.region_code
in " + regions;
OracleCommand Cmd = new OracleCommand(str, con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlDepot.DataSource = ds;
ddlDepot.DataTextField = "DEPOT_DESCRIPTION";
ddlDepot.DataValueField = "DEPOT_CODE";
ddlDepot.DataBind();
}

Argument of Out Range Exception while trying to read data from a List

I have a method that reads data from a database table using SqlDataReader.
i assign data retrieved by SqlDataReader into a List and return it.
when i want to assign the List data from method into the List on Code behind file,
i encounter the following error:
and here is my code
public List<string> displayCustoemrhShipOrder()
{
List<string> drList = new List<string>();
int i = 0;
string sConnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection SqlCOn = new SqlConnection(sConnectionString);
SqlCommand SqlCmd = new SqlCommand();
SqlCmd.Connection = SqlCOn;
SqlCmd.CommandText = "displayCustomerShipOrder";
SqlCmd.CommandType = CommandType.StoredProcedure;
SqlCOn.Open();
SqlCmd.Parameters.AddWithValue("ShipOrderID",shipOrderID);
SqlDataReader reader = SqlCmd.ExecuteReader();
while (reader.Read())
{
drList.Insert(i, reader.GetValue(i).ToString());
i++;
}
//reader.Close();
//sqlCon.Close();
reader.Dispose();
SqlCOn.Dispose();
return (drList);
}
code behind code:
protected void Page_Load(object sender, EventArgs e)
{
// string shipOrderID = Session["shipOrderID"].ToString();
// int ID = Convert.ToInt32(shipOrderID);
int ID = 700;
Classes.CustomerShipOrder cuShipOrder = new Classes.CustomerShipOrder(ID);
List<string> ordrList = new List<string>(16);
ordrList= cuShipOrder.displayCustoemrhShipOrder();
cuid.Text = ordrList[0];
Label2.Text = ordrList[1];
Label3.Text = ordrList[2];
Label4.Text = ordrList[3];
Label5.Text = ordrList[4];
Label6.Text = ordrList[5];
Label7.Text = ordrList[6];
Label8.Text = ordrList[7];
Label9.Text = ordrList[8];
Label10.Text = ordrList[9];
Label11.Text = ordrList[10];
stored procedure used :
#ShipOrderID int
as
begin
select * from customerShipOrder where shipOrderID = #ShipOrderID;
end

Data is not filling in dataview

I am trying to bind my repeater with dataview but it is not showing me data in dataview when i see it through breakpoint
private void Get_Data()
{
String File = Server.MapPath("BlogContent.xml");
DataSet ds = new DataSet();
ds.ReadXml(File);
DataView dv = new DataView(ds.Tables[0]);
DataTable dt = dv.Table;
ViewState.Add("Mytable", dt);
}
private void Bind_Data(int take, int pageSize)
{
PagedDataSource page = new PagedDataSource();
page.AllowCustomPaging = true;
page.AllowPaging = true;
DataTable dtv = (DataTable)ViewState["Mytable"];
DataView dv = new DataView();
dv = dtv.DefaultView;
dv.RowFilter = "id>=" + pageSize + " AND " + "id<=" + take;
page.DataSource = dv;
page.PageSize = psize;
Repeater1.DataSource = page;
Repeater1.DataBind();
if (!IsPostBack)
{
int rowcount = dtv.Rows.Count;
CreatePagingControl(rowcount);
}
}
PagedDataSource page = new PagedDataSource();
page.AllowCustomPaging = true;
page.AllowPaging = true;
DataTable dtv = (DataTable)ViewState["Mytable"];
DataView dv = new DataView();
dv = dtv.DefaultView;
dv.RowFilter = "id>=" + pageSize + " AND " + "id<=" + take;
page.DataSource = dv;
page.PageSize = psize;
Repeater1.DataSource = page;
Repeater1.DataBind();
if (!IsPostBack)
{
int rowcount = dtv.Rows.Count;
CreatePagingControl(rowcount);
}
please check it and tell me where i am going wrong.. I try to add paging in repeater control the number of paging display well but data is not fetching in dataview . When i check my datatable it is filling but when it comes to dataview shows me nothng
I got the answers.. The order of id in my xml was not in correct In my xml the id of each node is like
5
3
4
1
2
I do it correct
1
2
3
4
5
and it is working now ....

Must Declare the scalar variable "Post_ID"

I am getting this error "Must Declare the scalar variable "Post_ID" if i try to update 2 different ID's in my table. In other words, i can update as many times as i need to for example ID # 25 but if i try to update ID # 26 then i get the error above. My insert function works fine only my update function. Pls. help and i appreciate your time. Note, the DateKeyNames = ID. Here is my code for the update only:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE MyTable SET Post_ID=#Post_ID, Date=#Date, Description=#Description WHERE ID=#ID";
TextBox myTextBox11 = GV_InlineEditing.Rows[0].FindControl("GV_Post_ID") as TextBox;
TextBox myTextBox22 = GV_InlineEditing.Rows[0].FindControl("TextBox2") as TextBox;
TextBox myTextBox33 = GV_InlineEditing.Rows[0].FindControl("TextBox3") as TextBox;
if (myTextBox11 != null)
{
cmd.Parameters.Add("#Post_ID", SqlDbType.VarChar).Value = myTextBox11.Text;
}
else
{
TextBox GV_Post_ID = GV_InlineEditing.Rows[0].Cells[0].FindControl("GV_Post_ID") as TextBox;
}
if (myTextBox22 != null)
{
cmd.Parameters.Add("#Date", SqlDbType.VarChar).Value = myTextBox22.Text;
}
else
{
TextBox GV_Post_ID = GV_InlineEditing.Rows[0].Cells[0].FindControl("Date") as TextBox;
}
if (myTextBox33 != null)
{
cmd.Parameters.Add("#Description", SqlDbType.VarChar).Value = myTextBox33.Text;
}
else
{
TextBox GV_Post_ID = GV_InlineEditing.Rows[0].Cells[0].FindControl("Description") as TextBox;
}
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(GV_InlineEditing.Rows[e.RowIndex].Cells[1].Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
GV_InlineEditing.EditIndex = -1;
BindData();
Your logic is somewhat faulty:
if (myTextBox11 != null)
{
//add paramter
cmd.Parameters.Add("#Post_ID", SqlDbType.VarChar).Value = myTextBox11.Text;
}
else
{
//declare a different textbox and do not add the SQL parameter
TextBox GV_Post_ID = GV_InlineEditing.Rows[0].Cells[0].FindControl("GV_Post_ID") as TextBox;
}
This pattern is repeated for myTextBox22 and myTextBox33.
I would suggest this logic instead:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE MyTable SET Post_ID=#Post_ID, Date=#Date, Description=#Description WHERE ID=#ID";
TextBox myTextBox11 = GV_InlineEditing.Rows(0).FindControl("GV_Post_ID") as TextBox;
TextBox myTextBox22 = GV_InlineEditing.Rows(0).FindControl("Date") as TextBox;
TextBox myTextBox33 = GV_InlineEditing.Rows(0).FindControl("Description") as TextBox;
if (myTextBox11 == null) {
//try an alternate control for myTextBox11
myTextBox11 = GV_InlineEditing.Rows(0).Cells(0).FindControl("GV_Post_ID") as TextBox;
}
if (myTextBox22 == null) {
//try an alternate control for myTextBox22
myTextBox22 = GV_InlineEditing.Rows(0).Cells(0).FindControl("Date") as TextBox;
}
if (myTextBox33 == null) {
//try an alternate control for myTextBox33
myTextBox33 = GV_InlineEditing.Rows(0).Cells(0).FindControl("Description") as TextBox;
}
if (myTextBox11 != null & myTextBox22 != null & myTextBox33 != null) {
//all three textbox controls found
cmd.Parameters.Add("#Post_ID", SqlDbType.VarChar).Value = myTextBox11.Text;
cmd.Parameters.Add("#Date", SqlDbType.VarChar).Value = myTextBox22.Text;
cmd.Parameters.Add("#Description", SqlDbType.VarChar).Value = myTextBox33.Text;
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(GV_InlineEditing.Rows(e.RowIndex).Cells(1).Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
UPDATE
Add else conditions to Throw New Exception("myTextBox11 is null"); for myTextBox11, myTextBox22, and myTextBox33.
That will allow you to see if both:
GV_InlineEditing.Rows(0).FindControl("Date") as TextBox;
and:
GV_InlineEditing.Rows(0).Cells(0).FindControl("GV_Post_ID");
are failing.
I always do something like this like this:
protected void Gridview1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
int id = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox date = (TextBox)row.FindControl("date");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "update t_your_table " +
"set " +
"date = #date, " +
" time = #time where id = #ID "
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = id;
cmd.Parameters.Add("#date", SqlDbType.VarChar).Value = date.Text;
You have to get your datakeyname into the variables. That way it will use that field no matter what row is clicked.

WebPart in Sharepoint freezes after clicking a linkbutton

I have a user control inside a webpart inside sharepoint that I add some linkbuttons dynamically during runtime. each one when clicked is supposed to download a certain file from the database. however when one of those linkbuttons is clicked, this file is downloaded for once and then i can't click any other buttons or links or even the same one again on this user control and webpart. but i can still click other things outside the user control and webpart. do u have any idea? please tell me which part of the code i can add here if you need to check something. thank you :)
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 Microsoft.SharePoint;
using System.Collections.Generic;
using System.Drawing;
public class SearchResult : IComparable
{
private string __nID;
private string __sQuestion;
private string __sAnswer;
private string __nCategoryID;
private string __nPermission;
private string __nLastEdit;
private int __nOccurrence;
public SearchResult()
{
__nOccurrence = 0;
}
public string ID
{
get { return __nID; }
set { __nID = value; }
}
public string Quest
{
get { return __sQuestion; }
set { __sQuestion = value; }
}
public string Answer
{
get { return __sAnswer; }
set { __sAnswer = value; }
}
public string CategoryID
{
get { return __nCategoryID; }
set { __nCategoryID = value; }
}
public string Permission
{
get { return __nPermission; }
set { __nPermission = value; }
}
public string LastEdit
{
get { return __nLastEdit; }
set { __nLastEdit = value; }
}
public int Occurrence
{
get { return __nOccurrence; }
set { __nOccurrence = value; }
}
#region IComparable Members
public int CompareTo(SearchResult res)
{
if (this.Occurrence > res.Occurrence)
return -1;
if (this.Occurrence < res.Occurrence)
return 1;
return 0;
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
SearchResult res = (SearchResult)obj;
if (this.Occurrence > res.Occurrence)
return -1;
if (this.Occurrence < res.Occurrence)
return 1;
return 0;
}
#endregion
}
[System.ComponentModel.Description("Questions")]
public partial class SampleProvider : System.Web.UI.UserControl, SmartPart.IConnectionProviderControl
{
const string FAQConnectionString = "";
private int FileID = 1;
private string CaregoryID = "1";
TextBox tbQuestion;
TextBox tbAnswer;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["CategoryID"] = "0";
LoadTree();
}
System.Web.HttpContext context = System.Web.HttpContext.Current;
string username = context.User.Identity.Name;
LoadQuestions();
}
void LoadQuestions()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = FAQConnectionString;
System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand();
com.Connection = con;
com.CommandText = "SELECT * FROM Questions";
System.Data.SqlClient.SqlDataReader dr;
con.Open();
dr = com.ExecuteReader();
PlaceHolderQuestions.Controls.Clear();
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/><br/><br/>"));
while (dr.Read())
{
if (ViewState["CategoryID"].ToString() != dr[3].ToString())
continue;
Label question = new Label();
question.Text = dr[1].ToString();
question.Font.Name = "Cambria";
question.Font.Bold = true;
question.Font.Size = 11;
question.Width = 500;
Label answer = new Label();
answer.Text = dr[2].ToString();
answer.Font.Name = "Cambria";
answer.Font.Size = 11;
answer.Width = 500;
LinkButton lnkbtnEdit = new LinkButton();
lnkbtnEdit.Click += new EventHandler(lnkbtnEdit_Click);
lnkbtnEdit.CommandArgument = dr[0].ToString();
lnkbtnEdit.CommandName = "edit";
lnkbtnEdit.Text = "Edit";
lnkbtnEdit.Font.Name = "Cambria";
lnkbtnEdit.Font.Size = 11;
lnkbtnEdit.Width = 50;
PlaceHolderQuestions.Controls.Add(question);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/>"));
PlaceHolderQuestions.Controls.Add(answer);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/>"));
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString = FAQConnectionString;
System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand();
comm.Connection = conn;
/////////////////////////// dr[2] for the QuestionID column at the question table
comm.CommandText = "SELECT * FROM Files WHERE QuestionID = " + dr[0].ToString();
System.Data.SqlClient.SqlDataReader drr;
conn.Open();
drr = comm.ExecuteReader();
while (drr.Read())
{
LinkButton lnkbtnDownloadFile = new LinkButton();
//name of the file ---> drr[2]
lnkbtnDownloadFile.Click += new EventHandler(lnkbtnDownloadFile_Click);
lnkbtnDownloadFile.Text = drr[2].ToString();
lnkbtnDownloadFile.CommandArgument = drr[2].ToString();
PlaceHolderQuestions.Controls.Add(lnkbtnDownloadFile);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/>"));
}
ShowLabels(dr[0].ToString());
conn.Close();
PlaceHolderQuestions.Controls.Add(lnkbtnEdit);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<p/>"));
}
con.Close();
}
void EditQuestion(string ID)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = FAQConnectionString;
SqlCommand com = new SqlCommand("SELECT * FROM Questions WHERE ID = '" + ID + "'");
com.Connection = con;
SqlDataReader dr;
con.Open();
string quest="";
string answer = "";
string categoryID = "";
string lastEdit = "";
dr = com.ExecuteReader();
while (dr.Read())
{
quest = dr[1].ToString();
answer = dr[2].ToString();
categoryID = dr[3].ToString();
lastEdit = dr[5].ToString();
}
tbQuestion = new TextBox();
tbAnswer = new TextBox();
tbQuestion.TextMode = TextBoxMode.MultiLine;
tbAnswer.TextMode = TextBoxMode.MultiLine;
tbQuestion.Width = 360;
tbAnswer.Width = 360;
tbQuestion.Text = quest;
tbAnswer.Text = answer;
PlaceHolderQuestions.Controls.Clear();
PlaceHolderQuestions.Controls.Add(tbQuestion);
PlaceHolderQuestions.Controls.Add(tbAnswer);
SqlConnection conn = new SqlConnection();
conn.ConnectionString = FAQConnectionString;
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
/////////////////////////// dr[2] for the QuestionID column at the question table
comm.CommandText = "SELECT * FROM Files WHERE QuestionID = " + ID;
SqlDataReader drr;
conn.Open();
drr = comm.ExecuteReader();
PlaceHolder PlaceHolderFiles = new PlaceHolder();
PlaceHolderQuestions.Controls.Add(PlaceHolderFiles);
// for showing links to the files
while (drr.Read())
{
LinkButton lb = new LinkButton();
//name of the file ---> drr[2]
// lb.Click += new EventHandler(lb_Click);
lb.Text = drr[2].ToString();
PlaceHolderFiles.Controls.Add(lb);
LinkButton lnkbtnDelete = new LinkButton();
// lnkbtnDelete.Click+= new EventHandler(delete_Click);
lnkbtnDelete.CommandArgument = lb.Text;
lnkbtnDelete.Text = "Delete";
lnkbtnDelete.Width = 60;
lnkbtnDelete.Height = 25;
PlaceHolderFiles.Controls.Add(lnkbtnDelete);
PlaceHolderFiles.Controls.Add(new LiteralControl("<br/>"));
}
LinkButton lnkbtnSave = new LinkButton();
lnkbtnSave.Click += new EventHandler(lnkbtnSave_Click);
lnkbtnSave.Text = "Save";
PlaceHolderQuestions.Controls.Add(lnkbtnSave);
conn.Close();
}
void lnkbtnSave_Click(object sender, EventArgs e)
{
if (sender is LinkButton && (sender as LinkButton).CommandName == "save")
SaveQuestion((sender as LinkButton).CommandArgument);
}
private void UpdateQuestionByID(int questionID, string question, string answer, string lastEdited)
{
using (SqlConnection conn = new SqlConnection(FAQConnectionString))
{
conn.Open();
const string QUERY =
#"UPDATE Questions " +
#"SET Question = #Question, Answer = #Answer, LastEdit = #LastEdited " +
#"WHERE ID = #QuestionID";
using (SqlCommand cmd = new SqlCommand(QUERY, conn))
{
cmd.Parameters.AddWithValue("#Question", question);
cmd.Parameters.AddWithValue("#Answer", answer);
cmd.Parameters.AddWithValue("#LastEdited", lastEdited);
cmd.Parameters.AddWithValue("#QuestionID", questionID);
cmd.ExecuteNonQuery();
}
}
}
void SaveQuestion(string ID)
{
UpdateQuestionByID(int.Parse(ID), tbQuestion.Text, tbAnswer.Text, "a");
}
void lnkbtnEdit_Click(object sender, EventArgs e)
{
//if (sender is LinkButton && (sender as LinkButton).CommandName=="edit")
// EditQuestion((sender as LinkButton).CommandArgument);
string id = (sender as LinkButton).CommandArgument.ToString();
Response.Redirect("http://kermit:91/BIMS/Shared%20Documents/EditQuestion.aspx?k="+id);
ViewState["EditID"] = (sender as LinkButton).CommandArgument;
}
void lnkbtnDownloadFile_Click(object sender, EventArgs e)
{
if (sender is LinkButton)
DownloadFile((sender as LinkButton).CommandArgument);
}
private void DownloadFile(string fileName)
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = FAQConnectionString;
con.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Files WHERE FileName = #ID";
cmd.Parameters.Add("#ID", System.Data.SqlDbType.NVarChar).Value = fileName;
System.Data.SqlClient.SqlDataReader sqlRead = cmd.ExecuteReader();
if (sqlRead.HasRows)
{
while (sqlRead.Read())
{
byte[] fileData = (byte[])sqlRead[3];
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=" + sqlRead[2]);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(fileData);
//Response.Flush();
//Response.End();
Response.Clear();
}
}
con.Close();
sqlRead.Close();
}
protected void lnkbtnAddQuestion_Click(object sender, EventArgs e)
{
}
private void LoadTree()
{
tvCategory.Nodes.Clear();
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = FAQConnectionString;
System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand();
com.Connection = con;
com.CommandText = "SELECT * FROM QuestionCategory WHERE ParentCategoryID = -1";
System.Data.SqlClient.SqlDataReader dr;
con.Open();
dr = com.ExecuteReader();
while (dr.Read())
{
TreeNode tn = new TreeNode();
tn.Text = dr[1].ToString();
tn.Value = dr[0].ToString();
tvCategory.Nodes.Add(tn);
AddChildren(tn);
}
con.Close();
}
private void AddChildren(TreeNode tn)
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = FAQConnectionString;
System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand();
com.Connection = con;
com.CommandText = "SELECT * FROM QuestionCategory WHERE ParentCategoryID = " + tn.Value;
System.Data.SqlClient.SqlDataReader dr;
con.Open();
dr = com.ExecuteReader();
while (dr.Read())
{
TreeNode ctn = new TreeNode();
ctn.Text = dr[1].ToString();
ctn.Value = dr[0].ToString();
tn.ChildNodes.Add(ctn);
AddChildren(ctn);
}
con.Close();
}
protected void tvCategory_SelectedNodeChanged(object sender, EventArgs e)
{
ViewState["CategoryID"] = tvCategory.SelectedValue;
// CaregoryID = tvCategory.SelectedValue;
LoadQuestions();
tvCategory.SelectedNode.Selected = false;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = FAQConnectionString;
SqlDataAdapter adp = new SqlDataAdapter();
DataTable QuestionsTable = new DataTable();
using (SqlConnection oCn = new SqlConnection(FAQConnectionString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Questions", oCn);
cmd.CommandType = CommandType.Text;
adp.SelectCommand = cmd;
adp.Fill(QuestionsTable);
}
List<String> wordsSearched = new List<string>();
List<SearchResult> searchResults = new List<SearchResult>();
string[] words = txtbxSearch.Text.ToLower().Split();
//filtering the unnecessary words to prevent searching for
foreach (string s in words)
{
if (s == "to" || s == "the" || s == "is" || s == "are" || s == "in" || s == "of" || s == "on" || s == "with" || s == "are" || s == "it" || s == "this")
continue;
wordsSearched.Add(s);
}
//adding the search result and determine the frequency of occurrence
for (int i = 0; i < QuestionsTable.Rows.Count; i++)
foreach (string w in wordsSearched)
if (QuestionsTable.Rows[i][1].ToString().ToLower().IndexOf(w) > -1 || QuestionsTable.Rows[i][2].ToString().ToLower().IndexOf(w) > -1)
{
SearchResult result = new SearchResult();
result.ID = QuestionsTable.Rows[i][0].ToString();
result.Quest = QuestionsTable.Rows[i][1].ToString();
result.Answer = QuestionsTable.Rows[i][2].ToString();
result.CategoryID = QuestionsTable.Rows[i][3].ToString();
result.Permission = QuestionsTable.Rows[i][4].ToString();
result.LastEdit = QuestionsTable.Rows[i][5].ToString();
result.Occurrence++;
bool isFound = false;
for (int j = 0; j < searchResults.Count; j++)
if (searchResults[j].ID == result.ID)
{
searchResults[j].Occurrence++;
isFound = true;
break;
}
if (!isFound)
searchResults.Add(result);
}
SearchInTags(wordsSearched, searchResults);
searchResults.Sort();
//Session["SearchResults"] = searchResults;
//Response.Redirect("SearchResults.aspx");
LoadSearchResults(searchResults, wordsSearched);
}
void SearchInTags(List<string> words, List<SearchResult> searchResults)
{
foreach (string s in words)
{
using (SqlConnection con = new SqlConnection(FAQConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Questions INNER JOIN QuestionKeyword ON Questions.ID=QuestionKeyword.QuestionID INNER JOIN Keywords ON QuestionKeyword.KeywordID=Keywords.ID WHERE Keywords.Keyword LIKE '%" + s + "%'", con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
SearchResult result = new SearchResult();
result.ID = dr[0].ToString();
result.Quest = dr[1].ToString();
result.Answer = dr[2].ToString();
result.CategoryID = dr[3].ToString();
result.Permission = dr[4].ToString();
result.LastEdit = dr[5].ToString();
result.Occurrence++;
bool isFound = false;
for (int j = 0; j < searchResults.Count; j++)
if (searchResults[j].ID == result.ID)
{
searchResults[j].Occurrence++;
isFound = true;
break;
}
if (!isFound)
searchResults.Add(result);
}
}
}
}
string[] ColorWords(string[] words, string color, List<string> selected)
{
for (int i = 0; i < words.Length; i++)
for(int j=0; j<selected.Count; j++)
if(words[i].ToLower()==selected[j].ToLower())
{
words[i] = "<span style='color: red;'>" + words[i] + "</span>";
break;
}
return words;
}
string ColorText(string text, List<string> selected)
{
int searchFrom = 0;
foreach (string s in selected)
{
int startIndex = text.ToLower().IndexOf(s, searchFrom);
if (startIndex < 0)
continue;
int length = s.Length;
text = text.Insert(startIndex, "<span style='color: red;'>");
text = text.Insert(startIndex + length + 26, "</span>");
}
return text;
}
void LoadSearchResults(List<SearchResult> searchResults, List<string> selected)
{
PlaceHolderQuestions.Controls.Clear();
foreach (SearchResult res in searchResults)
{
Label question = new Label();
question.Text = ColorText(res.Quest, selected);
question.Font.Name = "Cambria";
question.Font.Bold = true;
question.Font.Size = 11;
question.Width = 500;
Label answer = new Label();
answer.Text = ColorText(res.Answer, selected);
answer.Font.Name = "Cambria";
answer.Font.Size = 11;
answer.Width = 500;
HyperLink edit = new HyperLink();
string url = "http://kermit:91/BIMS/Shared%20Documents/EditQuestion.aspx?k=";
url += res.ID;
edit.NavigateUrl = url;
edit.Text = "Edit";
edit.Font.Name = "Cambria";
edit.Font.Size = 11;
edit.Width = 50;
PlaceHolderQuestions.Controls.Add(question);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/>"));
PlaceHolderQuestions.Controls.Add(answer);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/>"));
SqlConnection conn = new SqlConnection();
conn.ConnectionString = FAQConnectionString;
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
/////////////////////////// dr[2] for the QuestionID column at the question table
comm.CommandText = "SELECT * FROM Files WHERE QuestionID = " + res.ID;
SqlDataReader drr;
conn.Open();
drr = comm.ExecuteReader();
while (drr.Read())
{
LinkButton lb = new LinkButton();
//name of the file ---> drr[2]
// lb.Click += new EventHandler(lb_Click);
lb.Text = drr[2].ToString();
PlaceHolderQuestions.Controls.Add(lb);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/>"));
}
ShowLabels(res.ID);
conn.Close();
PlaceHolderQuestions.Controls.Add(edit);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<p/>"));
}
}
void ShowLabels(string questionID)
{
SqlConnection con = new SqlConnection(FAQConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM QuestionKeyword INNER JOIN Keywords ON QuestionKeyword.KeyWordID=Keywords.ID WHERE QuestionID = " + questionID;
cmd.Connection = con;
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
Label lblKeyword = new Label();
lblKeyword.ForeColor = Color.Green;
lblKeyword.Text = dr[4].ToString();
PlaceHolderQuestions.Controls.Add(lblKeyword);
PlaceHolderQuestions.Controls.Add(new LiteralControl(" \t "));
}
con.Close();
PlaceHolderQuestions.Controls.Add(new LiteralControl("<p/>"));
}
#region IConnectionProviderControl Members
public object GetProviderData()
{
return null;
}
public string ProviderMenuLabel
{
get { return "Sends text data to"; }
}
#endregion
}
the weird thing that it works well when i put the same code in an asp.net page!!
Ahmad,
Check out the following link on the MSDN forums, as I believe the situation is similar (if not identical) to what you're describing:
http://social.msdn.microsoft.com/forums/en-US/sharepointdevelopment/thread/107b2c17-07fe-4a15-ad81-dcb31e1e9c84/
A couple of different approaches/solutions are discusssed.
I hope this helps!

Resources