I have been trying to get a List that comes from a WCF and assign its values to a ListView control on Xamarin Android. But, I keep receiving this error,
Cannot implicitly convert type
System.Collections.Generic.List<sometexthere> to
Android.Widget.ListView.
The App code is
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.ACategory);
btnBack = FindViewById<Button>(Resource.Id.btnTest);
txtInform = FindViewById<TextView>(Resource.Id.textView1);
lstSubCat = FindViewById<ListView>(Resource.Id.lstSubCats);
btnBack.Text = "Back";
string mainCat = Intent.GetStringExtra("ButtonClicked") ?? "Item not available";
txtInform.Text = "You are viewing the " + mainCat + " Category. Choises in here will be populated when connected to database";
this.Title = mainCat;
IntSuk.SukMain sukachin = new IntSuk.SukMain();//This is a web reference
sukachin.GetSubCategoryCompleted += Sukachin_GetSubCategoryCompleted;
sukachin.GetSubCategoryAsync(mainCat);
}
private void Sukachin_GetSubCategoryCompleted(object sender, IntSuk.GetSubCategoryCompletedEventArgs e)
{
lstSubCat = e.Result.ToList();//Here is where the error occurs. The result is a List<T> type but lstSubCat is an Android ListView
}
The WCF code that communicates with this is
public List<string> GetSubCategory(string cat)
{
SqlCommand cmd = new SqlCommand("select SubCategoryNameEnglish from SubCategory where Category='"+ cat + "'",Connection);
DataTable dt = new DataTable();
dt = DataManage.ExecuteDT(cmd);//Datamanage is a new class file and no problem with it.
List<string> retList = new List<string>();
int counts = dt.Rows.Count;
int i;
for (i = 0; i <= counts - 1; i++)
{
retList.Add(dt.Rows[i]["SubCategoryNameEnglish"].ToString());
}
return retList; //This is what is returned to the App
}
Is there any way that I can make an explicit conversion or any solution? Any help is appreciated. Thanks!
Thanks for the hint Jason!
Finally it worked in the following way. In the client code,
private void Sukachin_GetSubCategoryCompleted(object sender, IntSuk.GetSubCategoryCompletedEventArgs e)
{
List<string> listItems = new List<string>();
listItems = e.Result.ToList();
ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, listItems);
lstSubCat.Adapter = adapter;
}
Related
I am creating an app that prints invoices through Microsoft RDLC report.The report showing some data but the tablix is not showing the values which i provide from dataset.Please see my code below and try to solve my problem.
private void InvoiceButton_Click(object sender, EventArgs e)
{
Parameters p = new Parameters();
List<Parameters> lst = new List<Parameters>();
p.date = CurrentDateTimePicker.Text;
p.CustomerName = CustomerTextBox.Text;
if (CartDataGridView.Rows.Count != 0)
{
for (int i = 0; i < CartDataGridView.Rows.Count-1; i++)
{
lst.Add(new Parameters
{
ItemName = CartDataGridView.Rows[i].Cells[1].Value.ToString(),
Price = CartDataGridView.Rows[i].Cells[2].Value.ToString(),
Quantity = CartDataGridView.Rows[i].Cells[3].Value.ToString(),
Company = CartDataGridView.Rows[i].Cells[4].Value.ToString(),
ExpiryDate = CartDataGridView.Rows[i].Cells[5].Value.ToString(),
Total = CartDataGridView.Rows[i].Cells[7].Value.ToString()
// Subtotal = (Convert.ToInt32(CartDataGridView.Rows[i].Cells[7].Value))
});
}
}
InvoiceForm f = new InvoiceForm();
ReportDataSource rd = new ReportDataSource("MyDataSet");
rd.Value = lst;
f.reportViewer1.LocalReport.ReportEmbeddedResource = "CPMSTestPhase.InvoiceReport.rdlc";
f.reportViewer1.LocalReport.DataSources.Add(rd);
ReportParameter[] rptparam = new ReportParameter[]
{
new ReportParameter("Date",p.date),
new ReportParameter("CustomerName",p.CustomerName),
// new ReportParameter("Subtotal",p.Subtotal.ToString()),
};
f.reportViewer1.LocalReport.SetParameters(rptparam);
f.reportViewer1.RefreshReport();
f.ShowDialog();
}
}ere
I try all solutions available on youtube but did not work.
I myself figured out the issue. The issue is with the order of dataset fields and my parameters class properties. They should be the same.
I'm trying to clear 3 TextView fields before new data is then displayed. I'm using SQLite and returning 3 phone numbers.
I can't run the app as I get "cannot convert from string to int" on the
txtFire.SetText("");
section of code.
The 3 fields in my SQLite DB are TEXT fields, so slightly confused on how to resolve this.
Any advice is appreciated.
private void EmergencyServicesData()
{
var location = FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteCountry).Text;
ICursor selectData = sqliteDB.RawQuery("SELECT POLICE, FIRE, MEDICAL FROM EmergencyServices WHERE COUNTRY = '" + location + "'", new string[] { });
if (selectData.Count > 0)
{
selectData.MoveToFirst();
do
{
txtFire = (TextView)FindViewById(Resource.Id.txtFire);
txtMedical = (TextView)FindViewById(Resource.Id.txtMedical);
txtPolice = (TextView)FindViewById(Resource.Id.txtPolice);
txtFire.SetText("");
txtMedical.SetText("");
txtPolice.SetText("");
EmergencyServices emergencyServices = new EmergencyServices();
EmergencyServices.Clear();
emergencyServices.POLICE = selectData.GetString(selectData.GetColumnIndex("POLICE"));
emergencyServices.FIRE = selectData.GetString(selectData.GetColumnIndex("FIRE"));
emergencyServices.MEDICAL = selectData.GetString(selectData.GetColumnIndex("MEDICAL"));
EmergencyServices.Add(emergencyServices);
}
while (selectData.MoveToNext());
selectData.Close();
}
foreach (var item in EmergencyServices)
{
LayoutInflater layoutInflater = (LayoutInflater)BaseContext.GetSystemService(Context.LayoutInflaterService);
View addView = layoutInflater.Inflate(Resource.Layout.EmergencyServices, null);
TextView txtPoliceData = addView.FindViewById<TextView>(Resource.Id.txtPolice);
TextView txtFireData = addView.FindViewById<TextView>(Resource.Id.txtFire);
TextView txtMedicalData = addView.FindViewById<TextView>(Resource.Id.txtMedical);
txtPoliceData.Text = item.POLICE;
txtFireData.Text = item.FIRE;
txtMedicalData.Text = item.MEDICAL;
container.AddView(addView);
}
}
You have nullpointers in your textviews. Change to this.
LayoutInflater layoutInflater = (LayoutInflater)BaseContext.GetSystemService(Context.LayoutInflaterService);
View addView = layoutInflater.Inflate(Resource.Layout.EmergencyServices, null);
txtFire = addView.FindViewById<TextView>(Resource.Id.txtFire);
txtMedical = addView.FindViewById<TextView>(Resource.Id.txtMedical);
txtPolice = addView.FindViewById<TextView>(Resource.Id.txtPolice);
I am trying to get the data from my SQLite table into a List<string> and then into an ArrayAdapter<string> and into a ListView.
How would I get the data pulled from the below code, into a ListView using an ArrayAdapter?
DB Helper.cs:
public List<string> getNoteList()
{
List<string> noteList = new List<string>();
SQLiteDatabase db = this.ReadableDatabase;
ICursor cursor = db.Query(DB_TABLE, new string[] { DB_COLUMN}, null, null, null, null, null);
while (cursor.MoveToNext())
{
int index = cursor.GetColumnIndex(DB_COLUMN);
noteList.Add(cursor.GetString(index));
}
return noteList;
}
As you can see it is put into noteList, but how would I code an array adapter so that the noteList goes into a ListView?
UPDATE 1: MainActivity.cs
public void LoadNoteList()
{
List<string> noteList = dbHelper.getNoteList();
adapter = new ArrayAdapter<string>(this, Resource.Layout.list_black_text, noteList);
lvNotes.Adapter = adapter;
}
Error:
Change noteList's type to ArrayList and add follow line at the place after your ListView being initialization
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, noteList);
listview.setAdapter(adapter);
try this
here cards is my linked-list
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice);
for (MerchantCard card : cards) {
arrayAdapter.add(card.getName());
}
ListView listView = (ListView) mView.findViewById(R.id.listView);
listView.setAdapter(arrayAdapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedCardTypeId = cards.get(position).getId();
Log.d("request", cards.get(position).getId() + " " + cards.get(position).getName());
}
});
To better explain my problem with my personal website project, I would start off with the database that I have created. The table is called guitarItems.
This table is where i get data for displaying images and guitar details in the webpage. In order to do this, I created a method named "GetGuitarItems" to execute and read the sql statements.
public static ArrayList GetGuitarItems(string itemCategory)
{
ArrayList list = new ArrayList();
string query = string.Format("SELECT * FROM guitarItems WHERE brand LIKE '{0}'", itemCategory);
try
{
conn1.Open();
command1.CommandText = query;
SqlDataReader reader = command1.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32(0);
string type = reader.GetString(1);
string brand = reader.GetString(2);
string model = reader.GetString(3);
double price = reader.GetDouble(4);
string itemimage1 = reader.GetString(5);
string itemimage2 = reader.GetString(6);
string description = reader.GetString(7);
string necktype = reader.GetString(8);
string body = reader.GetString(9);
string fretboard = reader.GetString(10);
string fret = reader.GetString(11);
string bridge = reader.GetString(12);
string neckpickup = reader.GetString(13);
string bridgepickup = reader.GetString(14);
string hardwarecolor = reader.GetString(15);
GuitarItems gItems = new GuitarItems(id, type, brand, model, price, itemimage1, itemimage2, description, necktype, body,
fretboard, fret, bridge, neckpickup, bridgepickup, hardwarecolor);
list.Add(gItems);
}
}
finally
{
conn1.Close();
}
return list;
}
Next part is this code where you display the data that you have retrieved from the database.
public partial class Pages_GuitarItems1 : System.Web.UI.Page
{
private string brandType = "Ibanez";
private int x = 0;
protected void Page_Load(object sender, EventArgs e)
{
FillPage();
}
private void FillPage()
{
ArrayList itemList = new ArrayList();
ArrayList itemListPage = new ArrayList();
if (!IsPostBack)
{
itemList = ConnectionClassGuitarItems.GetGuitarItems("%");
}
else
{
itemList = ConnectionClassGuitarItems.GetGuitarItems(brandType);
}
StringBuilder sb = new StringBuilder();
foreach (GuitarItems gList in itemList)
{
itemListPage.Add("GuitarItemsIbanezDetails" + (x + 1) + ".aspx");
sb.Append(
string.Format(
#"
<div class='one-two'>
<a href='{3}' runat='server'><img runat='server' src='{0}'/></a>
<div class='content'>
<div id='label'>{1} {2}</div>
</div>
</div>", gList.ItemImage1, gList.Brand, gList.Model, itemListPage[x]));
x++;
}
lblOutput.Text = sb.ToString();
}
}
Now the problem is its displaying every guitar items in the database. As shown from the code above, what I'm trying to display is only the guitar items with brand "Ibanez" in it. I have my suspicions with the foreach code but atleast for now, the GetGuitarItemsMethod is designed to get only the Ibanez guitar items and the data will be passed on to the ArrayList itemList variable for displaying. And I have also checked the sql statement and it seems correct. Hope you guys can help me on this one.
Change from
if (!IsPostBack)
{
itemList = ConnectionClassGuitarItems.GetGuitarItems("%");
}
else
{
itemList = ConnectionClassGuitarItems.GetGuitarItems(brandType);
}
to
itemList = ConnectionClassGuitarItems.GetGuitarItems(brandType);
I am trying to View a report dynamically from code behind. But when the parameters are changed from dynamic textboxes added in the page. in the report refresh() the data is not changed.
I call sqlDS() and reportBuild() in the !IsPostback.
This method is for defining the sqlDatasource:
protected void sqlDS()
{
string conString, prName = "";
int counter = 0;
Reporting rep = new Reporting();
rep = rep.searchReport(repID_HF.Value);
Reporting repFold = new Reporting();
repFold = repFold.searchFolder(foldID_HF.Value);
if (repFold.FolderName.Split('(')[1] == "Web Reports)")
{
conString = dbSql.connectionStringAll;
prName = dbSql.providerName;
}
else
{
conString = db.connectionStringAll;
prName = db.providerName;
}
SqlDataSource1.ConnectionString = conString;
SqlDataSource1.ProviderName = prName;
string sqlString = System.IO.File.ReadAllText(Server.MapPath("~/Reports/SQLs/" + rep.SqlFile));
sqlString.Replace(System.Environment.NewLine, " ");
SqlDataSource1.SelectCommand = sqlString;
SqlDataSource1.CancelSelectOnNullParameter = false;
Reporting repParam = new Reporting();
allPs = repParam.getAllParamRep(rep.RepID);
foreach (Reporting itemParam in allPs)
{
if (itemParam.ParamType == "Date")
{
SqlDataSource1.SelectParameters.Add(":" + itemParam.ParamName, itemParam.ParamDefaultValue);
counter++;
}
else if (itemParam.ParamType == "Text")
{
SqlDataSource1.SelectParameters.Add(":" + itemParam.ParamName, itemParam.ParamDefaultValue);
counter++;
}
else if (itemParam.ParamType == "Menu")
{
counter++;
}
}
}
This method is for declaring the report properties:
protected void reportBuild()
{
Reporting rep2 = new Reporting();
rep2 = rep2.searchReport(repID_HF.Value);
ReportViewer1.LocalReport.ReportPath = "Reports/RDLC/" + rep2.RdlcFile;
this.ReportViewer1.LocalReport.ReportEmbeddedResource = rep2.RdlcFile;
ReportParameter[] paramss = new ReportParameter[SqlDataSource1.SelectParameters.Count];
for (int i = 0; i < SqlDataSource1.SelectParameters.Count; i++)
{
paramss[i] = new ReportParameter(SqlDataSource1.SelectParameters[i].Name.Split(':')[1], SqlDataSource1.SelectParameters[i].DefaultValue);
}
ReportDataSource rds = new ReportDataSource(rep2.DatasetName.Split('.')[0], SqlDataSource1);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rds);
//paramss[0] = new ReportParameter("TDATE", SqlDataSource1.SelectParameters[0].DefaultValue);
//paramss[1] = new ReportParameter("CUST_NUM", SqlDataSource1.SelectParameters[1].DefaultValue);
ReportViewer1.LocalReport.SetParameters(paramss);
ReportViewer1.LocalReport.Refresh();
}
In the reportViewer refresh method i try to set the new parameters according to the dynamic textboxes added in the page:
protected void ReportViewer1_ReportRefresh(object sender, System.ComponentModel.CancelEventArgs e)
{
foreach (Control txt in Panel1.Controls)
{
if (txt is TextBox)
{
txts.Add(txt);
}
}
foreach (TextBox txtbox in txts)
{
Reporting repP = new Reporting();
repP = repP.searchParam(txtbox.Attributes["pID"].ToString());
if (repP.ParamType == "Date")
{
SqlDataSource1.SelectParameters[":" + repP.ParamName].DefaultValue = txtbox.Text;
}
else if (repP.ParamType == "Text")
{
SqlDataSource1.SelectParameters[":" + repP.ParamName].DefaultValue = txtbox.Text;
}
}
//Reporting r = new Reporting();
//r = r.searchReport(repID_HF.Value);
//Reporting rep = new Reporting();
//rep = rep.searchReport(repID_HF.Value);
//ReportDataSource rds = new ReportDataSource(rep.DatasetName.Split('.')[0], SqlDataSource1);
//this.ReportViewer1.Reset();
//ReportViewer1.LocalReport.DataSources.Clear();
//ReportViewer1.LocalReport.DataSources.Add(rds);
ReportParameterInfoCollection x = ReportViewer1.LocalReport.GetParameters();
//Response.Redirect(Request.RawUrl);
ReportViewer1.LocalReport.Refresh();
}
I tried debugging and found every thing is working correctly the SQL parameters changed, the Report Parameters also is changed.
so why the data in the report is not changed? Plz help me
I got a better and easier way to solve this problem using this link
http://www.igregor.net/post/2007/12/Adding-Controls-to-an-ASPNET-form-Dynamically.aspx
And you can use array of strings to pass attributes.