pass parameter value from one method to another aspx.net - asp.net

I need help here. Below is my code. In this line of code
dtCurrentTable.Rows[0]["Kolicina"] = Convert.ToInt32(Label37.Text) + 3;
instead of 3 in next method this Label37.Text value should be incremented for one each time when user press the button.So I want this label value in next method to start to count from current value for one each time on button click.
protected void btnTest_Click(object sender, EventArgs e)
{
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
decimal old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int16>("TarifaID");
newValue = old - 1;
// so i need label value from here to go in next method and increment++
Label37.Text = newValue.ToString();
decimal newIznos = oldIznos - Convert.ToDecimal(Cena1);
dtCurrentTable.Rows[clickedIndex].SetField("Kolicina", newValue.ToString());
dtCurrentTable.Rows[clickedIndex].SetField("VkIznos", newIznos.ToString());
}
protected void Button6_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["string2"].ConnectionString);
conn.Open();
ViewState["count"] = Convert.ToInt32(ViewState["count"]) + 1;
// SqlCommand sqlCmd = new SqlCommand();
// sqlCmd.CommandText = "SupaSpanak";
// sqlCmd.Connection = conn;
// sqlCmd.CommandType = CommandType.StoredProcedure;
SqlCommand cmd1 = new SqlCommand("SELECT pkid,Artikal,Vid,EdMera,TarifaID,Cena1 FROM Artikli WHERE Artikal= 'N KREM SUPA OD SPANA]++' AND Cena1 = 130.00", conn);
//brojac za kolicina
count++;
decimal noofcount = count;
Session["kolicina"] = noofcount;
Label5.Text = Session["kolicina"].ToString();//ViewState["count"].ToString();//
SqlDataReader reader = cmd1.ExecuteReader();
if (reader.Read())
{
Label9.Text = (string)reader["pkid"].ToString();
Label3.Text = (string)reader["Artikal"].ToString();
Label23.Text = (string)reader["Vid"].ToString();
Label10.Text = (string)reader["EdMera"].ToString();
Label7.Text = (string)reader["TarifaID"].ToString();
Label4.Text = (string)reader["Cena1"].ToString();
decimal cena = Convert.ToDecimal(Label5.Text);//kolicina
decimal kolicina = Convert.ToDecimal(Label4.Text);//cena
//vkIznos
decimal mnoz = cena * kolicina;
Label6.Text = mnoz.ToString();
Convert.ToDecimal(Label6.Text);
conn.Close();
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
if (Label37.Text == "0")
{
dtCurrentTable.Rows[0]["Kolicina"] = Label5.Text;
}
if (Label37.Text != "0")
{
//Here this current value of Label37.text need to be incremented for one each time when button is clicked.
dtCurrentTable.Rows[0]["Kolicina"] = Convert.ToInt32(Label37.Text) + 3;
}

you need viewstate,
public int Counter
{
get
{
if (ViewState["Counter"] != null)
{
return Convert.ToInt32(ViewState["Counter"]);
}
else
return 0;
}
set { ViewState["Counter"] = value; }
}
protected void Button6_Click(object sender, EventArgs e)
{
//other codes..
Counter = Counter + 1;
if (Label37.Text != "0")
{
dtCurrentTable.Rows[0]["Kolicina"] = Convert.ToInt32(Label37.Text) + Counter;
}
}

Related

I am creating an application in windows form

I want to add labels through loop
`private void CourseOutcomes_Load(object sender, EventArgs e)
{
studentDetails dets = new studentDetails();
dets.ShowDialog();
name=dets.CourseName;
labelCourseName.Text = name;
string id = dets.CourseValue;
SqlDataReader sdr = bznessLogic.GetQuestions(id);
List<Label> lbl = new List<Label>();
int count = 0;
while (sdr.Read())
{
MessageBox.Show("s");
lbl[count] = new Label();
lbl[count].Text = sdr[0].ToString();
this.Controls.Add(lbl[count]);
count++;
}
sdr.Close();
}`
But it keeps giving error
'Index was out of range.
Should I initiablize it diffrently or..
So it turns out I just needed to initialize it properly which I expected, noob mistake but here we are.
private void CourseOutcomes_Load(object sender, EventArgs e)
{
studentDetails dets = new studentDetails();
dets.ShowDialog();
name=dets.CourseName;
labelCourseName.Text = name;
string id = dets.CourseValue;
SqlDataReader sdr = bznessLogic.GetQuestions(id);
List<Label> lbl = new List<Label>();
int count = 0;
while (sdr.Read())
{
MessageBox.Show("s");
lbl.Add(new Label() { Name="lbl"+count});
lbl[count].Text = sdr[0].ToString();
this.Controls.Add(lbl[count]);
count++;
}
sdr.Close();
}

subtract label values in asp.net

I want to subtract number from Label on button click.When i do that on button click values is subtracted just once, and on second click on the same button nothing is happen.I cannot figure out what is the problem?-Here is my code:
protected void btnTest_Click(object sender, EventArgs e)
{
Session["Counter"] = newValue;
if (ViewState["Markici"] != null)
{
dtCurrentTable = (DataTable)ViewState["Markici"];
ViewState["Markici"] = dtCurrentTable;
dtCurrentTable = (DataTable)ViewState["Markici"];
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
decimal old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int32>("TarifaID");
decimal newIznos = oldIznos - Convert.ToDecimal(Cena1);
dtCurrentTable.Rows[clickedIndex].SetField("Kolicina", newValue.ToString());
dtCurrentTable.Rows[clickedIndex].SetField("VkIznos", newIznos.ToString());
//Here i do the operation
decimal minus = Convert.ToDecimal(Label42.Text) - Convert.ToDecimal(Cena1);
Label26.Text = minus.ToString();
}
All the time I was subtracting in wrong label..
decimal minus = Convert.ToDecimal(Label42.Text) - Convert.ToDecimal(Cena1);
Label42.Text = minus.ToString();

Pop up if text box is blank at update

I have a web form that uses a text box to update a comments field in the database. I would like to check for a blank before update and have a reminder box that says "Comment section blank, continue?", then have a yes / no option. This would allow the user to return to the update without making changes. The text box is visible when the user selects edit on the row in a gridview. I will provide code below so that anyone can see what I am doing. If this cannot be done this way, simply a message box saying that the comment section is blank would suffice.
Here is the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Configuration;
namespace AnnoTracker
{
public partial class WebForm1 : System.Web.UI.Page
{
public static class MyVariables
{
public static int PI = 0;
public static string JN = "";
public static string ST = "";
public static string AT = "";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
dlAnnoType.SelectedValue = "Agency Error";
}
}
protected void EditSummary(object sender, GridViewEditEventArgs e)
{
gvSummary.EditIndex = e.NewEditIndex;
string _custName = gvSummary.DataKeys[e.NewEditIndex].Value.ToString();
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvSummary.EditIndex = -1;
BindData();
}
protected void gvSummary_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvSummary.PageIndex = e.NewPageIndex;
MyVariables.PI = e.NewPageIndex;
BindData();
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvSummary.EditIndex == e.Row.RowIndex)
{
DropDownList dlBU = (DropDownList)e.Row.FindControl("dlBU");
string _custName = gvSummary.DataKeys[e.Row.RowIndex].Values[1].ToString();
string BUquery = "select distinct Unit from vw_BU where Business='" + _custName + "'";
SqlCommand BUcmd = new SqlCommand(BUquery);
dlBU.DataSource = GetData(BUcmd);
dlBU.DataTextField = "Unit";
dlBU.DataValueField = "Unit";
dlBU.DataBind();
dlBU.Items.FindByValue((e.Row.FindControl("lblBU") as Label).Text).Selected = true;
DropDownList dlPA = (DropDownList)e.Row.FindControl("dlPA");
string _PAcustName = gvSummary.DataKeys[e.Row.RowIndex].Values[1].ToString();
string PAquery = "select PA from PA where Business='" + _PAcustName + "' order by PA";
SqlCommand PAcmd = new SqlCommand(PAquery);
dlPA.DataSource = GetData(PAcmd);
dlPA.DataTextField = "PA";
dlPA.DataValueField = "PA";
dlPA.DataBind();
dlPA.Items.FindByValue((e.Row.FindControl("lblPA") as Label).Text).Selected = true;
DropDownList dlET = (DropDownList)e.Row.FindControl("dlET");
string ETquery = "select distinct ErrorType from ErrorType order by ErrorType";
SqlCommand ETcmd = new SqlCommand(ETquery);
dlET.DataSource = GetData(ETcmd);
dlET.DataTextField = "ErrorType";
dlET.DataValueField = "ErrorType";
dlET.DataBind();
dlET.Items.FindByValue((e.Row.FindControl("lblET") as Label).Text).Selected = true;
DropDownList dlAA = (DropDownList)e.Row.FindControl("dlAA");
string AAquery = "select distinct AAA from ActualAgencyError";
SqlCommand AAcmd = new SqlCommand(AAquery);
dlAA.DataSource = GetData(AAcmd);
dlAA.DataTextField = "AAA";
dlAA.DataValueField = "AAA";
dlAA.DataBind();
dlAA.Items.FindByValue((e.Row.FindControl("lblAA") as Label).Text).Selected = true;
}
}
protected void UpdateSummary(object sender, GridViewUpdateEventArgs e)
{
string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
string ET = (gvSummary.Rows[e.RowIndex].FindControl("dlET") as DropDownList).SelectedItem.Value;
string AA = (gvSummary.Rows[e.RowIndex].FindControl("dlAA") as DropDownList).SelectedItem.Value;
string PA = (gvSummary.Rows[e.RowIndex].FindControl("dlPA") as DropDownList).SelectedValue;
string AnnotationNumber = gvSummary.DataKeys[e.RowIndex].Value.ToString();
string sgkComments = (gvSummary.Rows[e.RowIndex].FindControl("tbsgkComm") as TextBox).Text;
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
string query = "update vw_GridviewSource set [BusinessUnit] = #BU, [ErrorType] = #ET, [sgkComments] = #sgk, [ActualAgencyError] = #AA, [PA] = #PA where [AnnotationNumber] = #AnnoNum";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#BU", BU);
cmd.Parameters.AddWithValue("#AnnoNum", AnnotationNumber);
cmd.Parameters.AddWithValue("#ET", ET);
cmd.Parameters.AddWithValue("#AA", AA);
cmd.Parameters.AddWithValue("#sgk", sgkComments);
cmd.Parameters.AddWithValue("#PA", PA);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
//gvSummary.DataBind();
BindData();
}
private void BindData()
{
if (MyVariables.JN != "" && MyVariables.ST != "" && MyVariables.AT != "")
{
dlJobName.SelectedValue = MyVariables.JN;
dlJobName.DataBind();
dlStage.SelectedValue = MyVariables.ST;
dlStage.DataBind();
dlAnnoType.SelectedValue = MyVariables.AT;
dlAnnoType.DataBind();
}
String conString = System.Configuration.ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
string query = "select [Page_ID],[AnnotationNumber],[AnnotationBy],[PA],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource order by [Page_ID]";
SqlCommand cmd = new SqlCommand();
if (dlJobName.SelectedValue != "" & dlStage.SelectedValue != "")
{
query = "select [Page_ID],[AnnotationNumber],[AnnotationBy],[PA],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource where Name = '" + dlJobName.SelectedValue + "' and AnnotationDate = '" + dlStage.SelectedValue + "' order by [Page_ID]";
//cmd.Parameters.AddWithValue("#Name", dlJobName.SelectedValue);
//cmd.Parameters.AddWithValue("#Stage", dlStage.SelectedValue);
}
if (dlAnnoType.SelectedValue != "" && (dlJobName.SelectedValue != "" && dlStage.SelectedValue != ""))
{
query = "select [Page_ID],[AnnotationNumber],[AnnotationBy],[PA],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource where AnnotationType = '" + dlAnnoType.SelectedValue + "' and Name = '" + dlJobName.SelectedValue + "' and AnnotationDate = '" + dlStage.SelectedValue + "' order by [Page_ID]";
}
if (dlAnnoType.SelectedValue != "" && (dlJobName.SelectedValue.Length < 2 && dlStage.SelectedValue.Length < 2) )
{
query = "select [Page_ID],[AnnotationNumber],[AnnotationBy],[PA],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource where AnnotationType = '" + dlAnnoType.SelectedValue + "' order by [Page_ID]";
}
cmd.CommandText = query;
SqlConnection con = new SqlConnection(conString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
gvSummary.DataSource = ds;
gvSummary.PageIndex = MyVariables.PI;
gvSummary.DataBind();
//string #Name;
//string #Stage;
//#Name = dlJobName.SelectedValue;
//#Stage = dlStage.SelectedValue;
//string query = "select [AnnotationNumber],[AnnotationBy],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource where Name = '" + #Name + "' and AnnotationDate = '" + #Stage + "'";
//SqlCommand cmd = new SqlCommand(query);
//gvSummary.DataSource = GetData(cmd);
//gvSummary.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
protected void dlJobName_SelectedIndexChanged(object sender, EventArgs e)
{
MyVariables.JN = dlJobName.SelectedValue;
dlStage.DataBind();
MyVariables.ST = dlStage.SelectedValue;
gvSummary.DataBind();
BindData();
}
protected void dlStage_SelectedIndexChanged(object sender, EventArgs e)
{
MyVariables.JN = dlJobName.SelectedValue;
//dlStage.DataBind();
MyVariables.ST = dlStage.SelectedValue;
MyVariables.AT = dlAnnoType.SelectedValue;
gvSummary.DataBind();
BindData();
}
protected void dlAnnoType_SelectedIndexChanged(object sender, EventArgs e)
{
MyVariables.AT = dlAnnoType.SelectedValue;
MyVariables.JN = dlJobName.SelectedValue;
//dlStage.DataBind();
MyVariables.ST = dlStage.SelectedValue;
gvSummary.DataBind();
BindData();
}
}
}
You show only server side code, and it's more complicated doing chek on server side and show message on client.
Simple sample of chek on client side by javascript:
<script type="text/javascript">
function MyConfirm() {
if (document.getElementById("tb1").value == '')
if (confirm("Comment section blank, continue?"))
return true;
else
return false;
else true;
}
</script>
<asp:TextBox runat="server" ID="tb1" />
<asp:Button runat="server" ID="btn1" onclick="btn1_Click" OnClientClick="return MyConfirm();" Text="Save" />

how to do gridview sorting without data Source?

i am trying to do sorting and paging for my gridview without datasource but when i click on the header of the gridview to sort it , nothing happen but when i click for paging is working fine and there is no error. how to do about it?
this is my code:
protected void Page_Load(object sender, EventArgs e)
{
dbBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtSortTable = GridView1.DataSource as DataTable;
if (dtSortTable != null)
{
DataView dvSortedView = new DataView(dtSortTable);
dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
GridView1.DataSource = dvSortedView;
GridView1.DataBind();
}
}
private string getSortDirectionString(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
if(sortDirection== SortDirection.Ascending)
{
newSortDirection = "ASC";
}
else
{
newSortDirection = "DESC";
}
return newSortDirection;
}
private void dbBind()
{
DataSet ds;
string startdate = (string)(Session["startdate"]);
string enddate = (string)(Session["enddate"]);
var format = "dd/MM/yyyy";
DateTime one = DateTime.ParseExact(startdate, format, CultureInfo.InvariantCulture);
DateTime two = DateTime.ParseExact(enddate, format, CultureInfo.InvariantCulture);
if (two >= one)
{
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=n;Integrated Security=True");
//conn.Open();
SqlCommand cmd = new SqlCommand("SELECT [AmountSpent], [TimeDate]=convert(nvarchar,timedate,103), [StallNo] FROM [StudentTransactions] WHERE TimeDate BETWEEN #one AND #two", conn);
cmd.Parameters.AddWithValue("#one", one);
cmd.Parameters.AddWithValue("#two", two);
ds = new DataSet();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
if (ds.Tables.Count > 0)
{
DataView dv = ds.Tables[0].DefaultView;
if (ViewState["SortDirection"] != null)
{
sortDirection = ViewState["SortDirection"].ToString();
}
if (ViewState["SortExpression"] != null)
{
sortExpression = ViewState["SortExpression"].ToString();
dv.Sort = string.Concat(sortExpression, " ", sortDirection);
}
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
//GridView1.DataBind();
//conn.Close();
}
else
{
GridView1.Visible = false;
string strMsg = " Data not found for the choosen dates.";
Response.Write("<script>alert('" + strMsg + "')</script>");
}
}

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