I've been trying with no success to create a shopping cart in c# asp.net and SQL server.
I was able to retrieve the products from Database and to create a detail view for each product as well.
Right now I need to create the button "add to cart", I know that I have to create a session variable with an array to save the products information and then show it in the cart but I don't know how.
This is my code in productsDetail.cs:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connexionBD = new SqlConnection(this.data_un_jouet.ConnectionString);
SqlCommand commandeJouets = null;
SqlDataReader lecteurJouets = null;
try
{
connexionBD.Open();
String id = Request.QueryString["no"];
Session["product"] = id;
string myQuery = data_un_jouet.SelectCommand;
commandeJouets = new SqlCommand(myQuery, connexionBD);
commandeJouets.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32(id);
lecteurJouets = commandeJouets.ExecuteReader();
TableRow uneLigne;
TableCell uneCellule;
while (lecteurJouets.Read())
{
uneLigne = new TableRow();
string myID = Convert.ToString(lecteurJouets["id"]);
uneCellule = new TableCell();
uneCellule.Text = Convert.ToString(lecteurJouets["name"]);
uneLigne.Cells.Add(uneCellule);
uneCellule = new TableCell();
uneCellule.Text = "<img src=" + lecteurJouets["image"].ToString() + "/>";
uneLigne.Cells.Add(uneCellule);
uneCellule = new TableCell();
uneCellule.Text = Convert.ToString(lecteurJouets["description"]);
uneLigne.Cells.Add(uneCellule);
uneCellule = new TableCell();
uneCellule.Text = Convert.ToString(lecteurJouets["price"]);
uneLigne.Cells.Add(uneCellule);
uneCellule = new TableCell();
uneCellule.Text = "<a href=\"cart.aspx?no=" + myID + "\" />Add to cart</a>";
uneLigne.Cells.Add(uneCellule);
this.un_jouet.Rows.Add(uneLigne);
}
lecteurJouets.Close();
commandeJouets.Dispose();
}
catch (Exception ex)
{
msgErreur.Text = "Erreur de connexion ! " + ex.Message;
}
finally
{
connexionBD.Close();
}
I know most of the code is in french, I've tried to translate some of it.
This code works just fine, the problem is that I don't know what to do when the "Add to cart button" is clicked.
I've created a session variable but it only contains the product ID.
Thank you very much for your help,
Like you said you need to assign an array to the session. Better yet, use a List since you don't have a fixed number of items. Let's say that we store the IDs of the items in the shopping cart, and that those IDs are ints. So first we need to instantiate the List. There are many places where you can do this, but for now the Page_Load event is fine.
If (Session["ShoppingCart"] == null)
{
Session["ShoppingCart"] = new List<int>();
}
We first check to see if we've already assigned the session variable, and if not we do so.
Then when the customer adds an item to the shopping cart (say presses a button), you need to add this to the code handling that event:
var products = (List<int>)Session["ShoppingCart"];
products.Add(newProductId);
What I haven't done here (and you should) is to check in the session variable actually has a List to avoid errors. Remember that sessions are not strongly typed.
For better and cleaner code, you should encapsulate the session inside it's own get/set property.
Related
I am pretty new in .NET* and **SharePoint and I have the following problem.
I am developing a Web Part (into Share Point 2013) that retrieve n SharePoint list (the number of these lists is variable, it is not a fixed number) and use the content of these lists to render n DropDown (the content of these drop down is the content of the related SharePoint list).
So basically into the Page_Load() method of my Web Part I have something like this (it works):
else if (mode != null && mode.Equals("scelta_campi_facoltativi_etichetta"))
{
SPList listaCampiOpzionaliEtichetta = contextWeb.Lists["ListaCampiOpzionaliEtichetta"];
String tipoDocumentiInternalName = listaCampiOpzionaliEtichetta.Fields["TipoDocumento"].InternalName;
Clausola c = null;
if (tipoDoc.Equals("docEntrata"))
{
c = new Clausola(Clausola.condizione.Eq, Clausola.tipoCampo.Choice, Clausola.CondizioneExtra.no, "Entrata", tipoDocumentiInternalName);
}
else if(tipoDoc.Equals("docUscita"))
{
c = new Clausola(Clausola.condizione.Eq, Clausola.tipoCampo.Choice, Clausola.CondizioneExtra.no, "Uscita", tipoDocumentiInternalName);
}
string q = Query.creaQueryWhere(c.query);
SPQuery queryQ = new SPQuery();
queryQ.Query = q;
SPListItemCollection etichetteCollection = listaCampiOpzionaliEtichetta.GetItems(queryQ);
Table table = new Table();
table.CellPadding = 2;
table.CellSpacing = 2;
table.Width = Unit.Percentage(100);
foreach (SPListItem item in etichetteCollection)
{
Debug.WriteLine("etichetta: " + item["NomeLista"] + " URL sito: " + item["UrlSito"]);
SPSite sitoEtichettaCorrente = new SPSite(item["UrlSito"].ToString()); // Top level website of the site collection
SPWeb currentWebSite = sitoEtichettaCorrente.OpenWeb();
//SPList eitchettaCorrenteList = currentWebSite.GetList(item["NomeLista"].ToString());
SPList eitchettaCorrenteList = currentWebSite.Lists[item["NomeLista"].ToString()];
String nomeColonna = item["NomeColonna"].ToString();
String codice = item["Codice"].ToString();
TableRow rigaCorrente = new TableRow();
TableCell cell1Corrente = new TableCell();
TableCell cell2Corrente = new TableCell();
cell1Corrente.Controls.Add(new LiteralControl((String)item["NomeLista"]));
DropDownList dropDownnEtichetta = new DropDownList();
for (int i = 0; i < eitchettaCorrenteList.Items.Count; i++)
{
dropDownnEtichetta.CssClass = "chosen-select";
dropDownnEtichetta.ClientIDMode = ClientIDMode.Static;
dropDownnEtichetta.ID = (String)item["NomeLista"];
string valoreDaMostrareInternalName = eitchettaCorrenteList.Fields[nomeColonna].InternalName;
string valoreDaStampareInternalName = eitchettaCorrenteList.Fields[codice].InternalName;
string valoreDaMostrare = eitchettaCorrenteList.Items[i].GetFormattedValue(valoreDaMostrareInternalName);
string valoreDaStampare = eitchettaCorrenteList.Items[i].GetFormattedValue(valoreDaStampareInternalName);
dropDownnEtichetta.Items.Add(new ListItem(valoreDaMostrare, valoreDaStampare));
cell2Corrente.Controls.Add(dropDownnEtichetta);
rigaCorrente.Controls.Add(cell1Corrente);
rigaCorrente.Controls.Add(cell2Corrente);
}
table.Controls.Add(rigaCorrente);
}
sceltaCampiEtichettaPanel.Controls.Add(table);
HtmlGenericControl buttondiv = new HtmlGenericControl("div");
Button bottoneConfermaCampiFacoltativiEtichetta = new Button();
bottoneConfermaCampiFacoltativiEtichetta.Text = "Conferma";
bottoneConfermaCampiFacoltativiEtichetta.CssClass = "shiny-blue";
//bottoneConfermaCampiFacoltativiEtichetta.OnClientClick = "return validatePwd();";
//bottoneConfermaCampiFacoltativiEtichetta.Click += ButtonSalva_Click;
buttondiv.Controls.Add(new LiteralControl("<br/>"));
buttondiv.Controls.Add(bottoneConfermaCampiFacoltativiEtichetta);
sceltaCampiEtichettaPanel.Controls.Add(buttondiv);
}
As you can see I am retrieving a list of SharePoint lists. I iterate on each list and I populate the contend of the rendered DropDown with the content of the related current list.
Now my problem is: the user can select a value from these DropDown. I want to store (probably at class level) the values chosen by the user into these dropdown.
What could be a smart strategy to implement this task?
I have an asp.net program that creates a simple survey form for users to answer.
Most of the questions use a dropdownlist with answer scores from 1-5 (bad-good) and I'm trying to add an event handler to the dropdownlist objects so that the comments box is only enabled if the user selects a score between 1 and 2.
However when I add the delegate lambda call for the event handler, instead of each dropdownlist affecting their own corresponding comment box, they all seem to point only at the last one added (and they work once, then no more and only the last ddl continues having the expected behaviour).
My code:
//Called from Page_Load
private void PopulateSurvey()
{
btnSubmit.Enabled = true;
List<Question> questions = (from p in context.Questions
join q in context.Survey_Questions on p.ID equals q.QuestionID
where q.SurveyID == surveyid
select p).ToList();
Table tbl = new Table();
tbl.Width = Unit.Percentage(100);
TableRow tr;
TableCell tc;
TableCell tc1;
TableCell tc2;
TextBox txt;
CheckBox cbk;
DropDownList ddl = new DropDownList();
foreach (Question q in questions)
{
if (q.Division.Equals("General") || q.Division.Equals(ddlDivisions.SelectedValue.ToString()))
{
tr = new TableRow();
tc = new TableCell();
tc.Width = Unit.Percentage(55);
tc.Text = q.Text;
tc.Attributes.Add("id", q.ID.ToString());
tr.Cells.Add(tc);
tc = new TableCell();
if (q.QuestionType.ToLower() == "singlelinetextbox")
{
txt = new TextBox();
txt.ID = "txt_" + q.ID;
//txt.Width = Unit.Percentage(40);
tc.Controls.Add(txt);
}
if (q.QuestionType.ToLower() == "multilinetextbox")
{
txt = new TextBox();
txt.ID = "txt_" + q.ID;
txt.TextMode = TextBoxMode.MultiLine;
//txt.Width = Unit.Percentage(40);
tc.Controls.Add(txt);
}
if (q.QuestionType.ToLower() == "singleselect")
{
ddl = new DropDownList();
ddl.ID = "ddl_" + q.ID;
//ddl.Width = Unit.Percentage(41);
if (!string.IsNullOrEmpty(q.Options))
{
string[] values = q.Options.Split(',');
foreach (string v in values)
ddl.Items.Add(v.Trim());
}
ddl.AutoPostBack = true;
tc.Controls.Add(ddl);
}
//tc.Width = Unit.Percentage(60);
tr.Cells.Add(tc);
//Add comment row
tc1 = new TableCell();
//tc.Width = Unit.Percentage(5);
tc1.Text = "Comentario: ";
tc1.Attributes.Add("id", q.ID.ToString());
//tc1.Visible = false;
tr.Cells.Add(tc1);
tc2 = new TableCell();
txt = new TextBox();
txt.ID = "txt_" + q.ID + "comment";
txt.TextMode = TextBoxMode.SingleLine;
//txt.Width = Unit.Percentage(25);
tc2.Controls.Add(txt);
tr.Cells.Add(tc2);
ddl.SelectedIndexChanged+= (sender, e) => ScoreChanged(sender, e, tc1,tc2, ddl.SelectedIndex);
tbl.Rows.Add(tr);
}
}
pnlSurvey.Controls.Add(tbl);
}
protected void ScoreChanged (object sender, EventArgs e, TableCell tc1, TableCell tc2, int score)
{
if( score <2)
{
tc1.Visible = false;
tc2.Visible = false;
}
else
{
tc1.Visible = true;
tc2.Visible = true;
}
}
First thing that comes to mind is maybe the event handler keeps the references themselves,m instead of the orphaned objects created with each question, so all event handlers end up with the same tc1 and tc2 reference and thus only the last object? Is that the case and if so how do I go around it?
Your problem is in this line:
ddl.SelectedIndexChanged +=
(sender, e) => ScoreChanged(sender, e, tc1,tc2, ddl.SelectedIndex);
Two things are important here:
You are using an anonymous method to invoke ScoreChanged.
You are passing tc1 and tc2 as an argument to the ScoreChanged method. You have defined those variables at the beginning of your code block, outside the loop.
The magic word in this context is closure. Since tc1 and tc2 are defined outside the scope of the anonymous method, they turn into closures. That means the will not have the value at the time you define the method, but at the time you invoke it. Since you are constantly overwriting the value of the variables in the foreach loop, at the time of the invokation those variables will have the value of the last iteration of the loop.
The solution is simple: Declare the variables inside the loop. This will create a new closure for each iteration of the foreach:
TableRow tr;
TableCell tc;
TextBox txt;
CheckBox cbk;
foreach (Question q in questions)
{
TableCell tc1;
TableCell tc2;
DropDownList ddl; //Don't forget to include ddl, since you are using its selected index
//...
On a more general note: Don't do "declaration" blocks like this at the beginning of a method in C#. Declare the variable the first time you use it (unless there is a good reason to do otherwise, for example you want it to be a part of a closure). There are many good reasons for that and you just have experienced one of them. Another one would be that when you turn a part of your code to a method with Visual Studio's refactoring feature, you will pass the predeclared variables as ref params. These are the most obvious reasons. There are more.
I have a problem with my foreach loop. The prupose is to loop through items in a listbox and for every item there is, it should set the properties of the person equal to the properties of the person equal to a person object which i will insert into a list of persons.(The person has a item, with properties ect..). Problem: It inserts the first person with it's item into the list, but when it comes to the second person that it has to insert it changes the first person data to the same data as the second person data, and inserts the second person. So it always inserts the new person but changes all my old data that I have alredy inserted too be the same as the new person's.
private void btnOK_Click(object sender, EventArgs e)
{
bool bOK = false;
if (UC.IsEmpty(txtFirstName) || UC.IsEmpty(txtLastName) || UC.IsEmpty(txtID) || lstItemsAdded.Text == null) //Maak seker van die listItemsAdded se content... hier sal n error wees... j kan nog n else maak dat hy spesefiek toets of daar items in die lstbox is
{
UC.MB("Customer Information Missing", "Please supply enough customer information");
}
else
{
bOK = true;
}
if (bOK)
{
foreach (Item item in lstItemsAdded.Items)
{
PersonItemObject.FirstName = txtFirstName.Text;
PersonItemObject.LastName = txtLastName.Text;
PersonItemObject.ID = txtID.Text;
PersonItemObject.Email = txtEmail.Text;
PersonItemObject.Age = Convert.ToInt32(txtAge.Text);
PersonItemObject.Item.ItemCode = item.ItemCode;
PersonItemObject.Item.ItemDescription = item.ItemDescription;
PersonItemObject.Item.ItemName = item.ItemName;
PersonItemObject.Item.ItemPrice = item.ItemPrice;
It is supposed to add all the items in the listBox to the list in the next statement, and for each item it should add the persons details too.
PersonItemsList.Add(PersonItemObject);
If I added more than 1 item to a person it changes my old data that i have added in the list to be the same as then new person data, and inserts a new person into the list too.
}
DialogResult = DialogResult.OK;
Close();
}
}
In every iteration you are updating properties of the same object, and then inserting it into the list. SO in the end list contains several referencies to the same object.
What you should do is craeting new object for each iteration:
foreach (Item item in lstItemsAdded.Items)
{
PersonItem item = new PersonItem(); //just guessing the type here
item.FirstName = txtFirstName.Text;
...
PersonItemsList.Add(item);
}
You should create a new instance of your "PersonItemObject". Something like:
PersonItemObject = new PersonItemObjectClass()
as the first sentence of your loop, being PersonItemObjectClass the type of PersonItemObject. The problem here is, probably, you are using always the same instance and because of it the value is always changing.
You've got to create a new instance of whatever type PersonItemObject is, inside the foreach loop.
What you're adding to the PersonItemsList is actually a reference to a single instance of your class. Every time you iterate the loop, you're updating the same instance, so you have a list of identical looking objects.
foreach (Item item in lstItemsAdded.Items)
{
var PersonItemObject = new PersonItem();
PersonItemObject.FirstName = txtFirstName.Text;
PersonItemObject.LastName = txtLastName.Text;
...
PersonItemsList.Add(PersonItemObject);
}
You may want to read up on the differences between value types and reference types.
You have one PersonItemObject and you are changing it in every iteration.If you want to make a list of PersonItemObjects then create a new instance on each iteration:
foreach (Item item in lstItemsAdded.Items)
{
var PersonItemObject = new YourType();
PersonItemObject.FirstName = txtFirstName.Text;
PersonItemObject.LastName = txtLastName.Text;
...
}
This is happening because you're always changing the same PersonItemObject. You should create a new version of this object each time and add it your list.
foreach (Item item in lstItemsAdded.Items)
{
var newObject = new PersonItemObject();
newObject.FirstName = txtFirstName.Text;
newObject.LastName = txtLastName.Text;
newObject.ID = txtID.Text;
newObject.Email = txtEmail.Text;
newObject.Age = Convert.ToInt32(txtAge.Text);
newObject.Item.ItemCode = item.ItemCode;
newObject.Item.ItemDescription = item.ItemDescription;
newObject.Item.ItemName = item.ItemName;
newObject.Item.ItemPrice = item.ItemPrice;
PersonItemsList.Add(newObject);
}
You are not creating a new object each time you are setting the values to it. To create a new object the proper way would be like this:
foreach (Item item in lstItemsAdded.Items)
{
var newObject = new PersonItemObject()
{
FirstName = txtFirstName.Text;
LastName = txtLastName.Text;
ID = txtID.Text;
Email = txtEmail.Text;
Age = Convert.ToInt32(txtAge.Text);
Item.ItemCode = item.ItemCode;
Item.ItemDescription = item.ItemDescription;
Item.ItemName = item.ItemName;
Item.ItemPrice = item.ItemPrice;
}
PersonItemsList.Add(newObject);
}
When the add button is clicked second time, there is supposed to be two lines of data rows in the GridView ( the first row is the first click and the second row is the newly added data). However there is only one data row.
List<DonationReceivedItem> drList = new List<DonationReceivedItem>();
protected void lbnAdd_Click(object sender, EventArgs e)
{
DonationReceivedItem temp = new DonationReceivedItem();
temp.donation = dID;
temp.productVariant = gvSelectVairant.SelectedRow.Cells[1].Text;
temp.productQuantity = tbQuantity.Text;
temp.isDistributed = "0";
drList.Add(temp);
gvNonExpired.DataSource = drList;
gvNonExpired.DataBind();
}
Try changing the following code:
DonationReceivedItem temp = new DonationReceivedItem();
temp.donation = dID;
temp.productVariant = gvSelectVairant.SelectedRow.Cells[1].Text;
temp.productQuantity = tbQuantity.Text;
temp.isDistributed = "0";
drList.Add(temp);
gvNonExpired.DataSource = drList;
gvNonExpired.DataBind();
to:
DonationReceivedItem temp = new DonationReceivedItem();
drList = gvNonExpired.DataSource;
temp.donation = dID;
temp.productVariant = gvSelectVairant.SelectedRow.Cells[1].Text;
temp.productQuantity = tbQuantity.Text;
temp.isDistributed = "0";
drList.Add(temp);
gvNonExpired.DataSource = drList;
gvNonExpired.DataBind();
See if that makes a difference :)
Because you are creating a new list you are wiping the previous data. First instantiate the list with the old data, then add the new data.
Hi currently I have code that get the value of of a list item and checks to see whether the value in this list (the value in a "Phone number" column) exists agains a value sugmitted by a HTML form. If the record to be entered into the list via this HTML form contains a Phone number that is already in the list, the record will not be added. This works well for the first item in the list, however when another item is added into the list with a different Phone number, the code does not seem to pick up the Phone number for the second record and so if a third record is entered with same Phone number as the second record the validation does not take place, the code keeps on looking at the first record. Here is a listing of my code:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(valueListURL))
{
using (SPWeb web = site.OpenWeb())
{
try
{
//--This is very important--
web.AllowUnsafeUpdates = true;
SPList list = web.Lists["Contact Requests"];
SPListItemCollection collsListItems = list.Items;
//Following lines of code added for validation
oreach (SPListItem objListItem in list.Items)
{
string valuePhonenumber = objListItem["Phone number"].ToString();
string valueEmailaddress = objListItem["Email address"].ToString();
SPListItem newItem = list.Items.Add();
if (TextBox3.Text != valuePhonenumber)
{
newItem["Contact name"] = TextBox1.Text;
TextBox1.Text = null;
newItem["Company"] = TextBox2.Text;
TextBox2.Text = null;
newItem["Phone number"] = TextBox3.Text;
this.TextBox3.Text = null;
newItem["Email address"] = TextBox4.Text;
TextBox4.Text = null;
newItem["Best time to call you"] = TextBox5.Text;
TextBox5.Text = null;
newItem["Enquiry subject"] = DropDownList1.SelectedItem;
this.DropDownList1.ClearSelection();
newItem["Enquiry details"] = TextBox6.Text;
this.TextBox6.Text = null;
if (RadioButton1.Checked)
newItem["Contact method"] = Label1.Text;
this.RadioButton1.Checked = false;
if (RadioButton2.Checked)
newItem["Contact method"] = Label2.Text;
this.RadioButton2.Checked = false;
newItem.Update();
}
//this.Response.Redirect(Request.RawUrl);
//Lines of code below used to insert or inject a javacript in order to close
//modeal dialog box at the press of the button
this.Page.Response.Clear();
this.Page.Response.Write("
<script type=text/javascript>window.frameElement.commonModalDialogClose(1, 1);</script>");
//this.Page.Response.Write("Submitted!"); //replacement for the above javascript
this.Page.Response.End();
}
}
catch (Exception doh)
{
DisplayError(doh);
}
}
}
});
I am thinking of using a foor loop to iterate throught the list items to check for exisiting Phone number records. I am think of putting the
if (TextBox3.Text != valuePhonenumber)
{
}
shown in the code above inside of a foor loop, but Im not sure on how to achieve this without breaking the code. Would be much appreciated if anyone could assist me with this!
Thanks in advance,
Update!!!
I am now using caml query to query the list for the required value in this case its the value entered on the HTML form into TextBox3.Text. The result of the qquery then gets stored in the object "listItemsCollection". I then use this perform a check so if the value in "TextBox3.text" is not equal to the value stored in "listItemsCollection" then the records get added to the list, if it is equal then the records does not get added. The code is listed below:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(valueListURL))
//using (SPSite site = new SPSite(webUrl))
{
using (SPWeb web = site.OpenWeb())
{
try
{
//added to resolve the issue with security validation on the page
//--This is very important--
web.AllowUnsafeUpdates = true;
SPList list = web.Lists["Contact Requests"]
SPQuery query = new SPQuery();
// try and find phone number we dont want to add in list
string camlquery = "<Where><Eq><FieldRef Name='Phone number'/>" + "<Value Type='Text'>"
+ TextBox3.Text + "</Value></Eq></Where>";
query.Query = camlquery;
SPListItemCollection listItemsCollection = list.GetItems(query);
if (TextBox3.Text != listItemsCollection.ToString()) // if it doesn't exist in list,
//we can add it records
{
SPListItem newItem = list.Items.Add();
// add code goes here
newItem["Contact name"] = TextBox1.Text;
TextBox1.Text = null;
newItem["Company"] = TextBox2.Text;
TextBox2.Text = null;
newItem["Phone number"] = TextBox3.Text;
this.TextBox3.Text = null;
newItem["Email address"] = TextBox4.Text;
TextBox4.Text = null;
newItem["Best time to call you"] = TextBox5.Text;
TextBox5.Text = null;
newItem["Enquiry subject"] = DropDownList1.SelectedItem;
this.DropDownList1.ClearSelection();
newItem["Enquiry details"] = TextBox6.Text;
this.TextBox6.Text = null;
if (RadioButton1.Checked)
newItem["Contact method"] = Label1.Text;
this.RadioButton1.Checked = false;
if (RadioButton2.Checked)
newItem["Contact method"] = Label2.Text;
this.RadioButton2.Checked = false;
newItem.Update();
}
//this.Response.Redirect(Request.RawUrl);
//Lines of code below used to insert or inject a javacript in order to close
//modeal dialog box at the press of the button
this.Page.Response.Clear();
this.Page.Response.Write("<script
type=text/javascript>window.frameElement.commonModalDialogClose(1, 1);</script>");
//this.Page.Response.Write("Submitted!"); //replacement for the above javascript
this.Page.Response.End();
}
catch (Exception doh)
{
DisplayError(doh);
}
}
}
});
I haven't done much with CAML before which is why I seem to be struggling whith something that should be so simple. Any sujestions to get this working will be hugely appreciated!
Many thanks in advance
You could achieve this using a CAML Query. You simply create a query where the phone number equals (or contains, depends on your requirements) the input from the HTML form. When you execute the query, a result set (SPListItemCollection) is returned. If this result set already contains an item, you know it's a duplicate and do not add a new item. Refer to this article if you haven't worked with CAML Queries yet:
http://sharepointmagazine.net/articles/writing-caml-queries-for-retrieving-list-items-from-a-sharepoint-list
I finally found what the problem was, after doing some reading apparently when dealing with CAML its seems better to provide the internal system name of the list column or field. In my case I was using 'Phone number' before which is why the whole thing was not working.
string camlquery = #"<Where>
<Eq>
<FieldRef Name='Phone_x0020_number'/>
<Value Type='Text'>" + TextBox3.Text + #"</Value>
</Eq>
</Where>";
query.Query = camlquery;
SPListItemCollection listItemsCollection = list.GetItems(query);
if (listItemsCollection.Count == 0) // if it doesn't exist in list, we can add it
{
}
But by simply providing the internal system name for the list column or field as shown above ('Phone_x0020_number'). The whole thing now works. After all this time breakingmy head, all that was required was the internal system name for the column.....
private bool TryGetItem(Guid key, string value, SPList list, out SPListItemCollection items)
{
SPQuery query = new SPQuery();
string #template = #"<Where>
<Eq>
<FieldRef Name='{1}'/>
<Value Type='Text'>{0}</Value>
</Eq>
</Where>";
query.Query = string.Format(#template, key.ToString("D"), value);
items = list.GetItems(query);
return items.Count > 0;
}