showing ListView error - c#-4.0

Am not able to do INSERT UPDATE DELETE AND CLEAR operatopns on my ListView in WinForms
Here's my Code:
private void Form1_Load(object sender, EventArgs e)
{
ShowData();
}
private void ShowData()
{
SqlConnection con = new SqlConnection("User id=sa;password=sql#123;database=arvind;server=ASHOK-PC");
con.Open();
SqlCommand cmd = new SqlCommand("select * from Login_1",con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
listView1.DataContext = dt.DefaultView;
}
I got error in DataContext as
System.Windows.Forms.ListView does not contain a definition for datacontext and no extension method accepting a first argument of type System.Windows.Forms.Listview could be found.

You appear to be trying to follow a code example made for WPF when you're using Windows Forms. The WinForms ListView indeed does not have such a property and in fact doesn;t support data-binding.
Do yourself a favour and use a DataGridView. Just assign the DataTable itself to the DataSource property. Binding the DefaultView is pointless.

Related

Shared Preference Empty On Next run

I have A SharedPreference That I want to save an array list for the next time I open the app. But The next time I start the app it comes up as empty. I execute the save onDestroy because I dont want to push a button. I dont know whats going on. Any help would be appreciated.
I run LoadData() Method inside onCreate() Method.
public void LoadData(){
SharedPreferences sp = getSharedPreferences("SavedArrayList",MODE_PRIVATE);
Gson gson = new Gson();
String json = sp.getString("Arraylist", null);
Type type = new TypeToken<ArrayList<ListItems>>() {}.getType();
if (json != null)items = gson.fromJson(json, type);
}
#Override
protected void onDestroy() {
SharedPreferences sp = getSharedPreferences("SavedArrayList",MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
Gson gson = new Gson();
String json = gson.toJson(items);
editor.putString("Arraylist", json);
editor.apply();
super.onDestroy();
}
All I did was moved it to onPause and onResume now it works fine.

Android studio room database - not returning values in onRestart() method

My app is a list of element names. Clicking one goes to another activity with more details, and an editText and button to change its name. When I go back to the list, I want it to have the new name if updated. My onCreate method has this code which populates it from the database perfectly (ignore the hardcoded size, its just simpler for debugging)
final String DATABASE_NAME = "element_db";
final AppDatabase appDatabase;
appDatabase = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, DATABASE_NAME).build();
ListView list = (ListView)findViewById(R.id.listView);
final String[] element = new String[3];
new Thread(new Runnable() {
#Override
public void run() {
List<Element> elements;
elements = appDatabase.elementDao().fetchElements(); // a dao query "select*from"
int size = elements.size();
for (int i = 0; i < size; i++){
element[i] = elements.get(i).getName();
}
}
}) .start();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_list_view, R.id.textView, element);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, itemdetail.class);
i.putExtra("pos", position);
startActivity(i);
}
});
To achieve an updated list when returning to this screen, I copied the above code into the onRestart method, but now the database does not return anything. If I just set the array that goes into the adapter to {"a", "a", "a"} the list populates fine. Any ideas why the database works onCreate but not onRestart?
I think you can use ViewModel and livedata to observe any database change

Efficient way to return ID values from Access table for c# combo box

I'm using the following code to populate my combobox for further function. Is there a better way for populating my combo box in class context? I realize that if the number of records is in the thousands then probably this is not the best practice.
private void Form1_Load(object sender, EventArgs e)
{
Book myBook = new Book;
myBook.Connect();
comboBox1.DataSource=myBook.IDs();
}
class Book
{
OleDbCommand Comm;
OleDbConnection Conn;
OleDbDataReader Reader;
string queryString;
public void Connect()
{
Conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Book.accdb");
}
public List<string> IDs()
{
string singleID = null;
List<string> IDs = new List<string>();
queryString = "Select bID from Books";
Comm = new OleDbCommand(queryString, Conn);
Reader = Comm.ExecuteReader();
while (Reader.Read())
{
singleID = Reader[0].ToString();
IDs.Add(singleID);
}
Conn.Close();
Reader.Close();
return IDs;
}
}
The method you are using to populate the combo box appears to be technically correct. You are probably right that if it will result in a combo box with a huge number of items then it may not work that well in practice, but that is more a question of "UI design" (i.e., "Is using a single combo box the right choice for having the user make a selection?") than "code design" (i.e., "I'm using a combo box, so what is the best way to get the items into it?").

How to control flow of multiple Rss Files

I developed RssFeed Application using LWUIT j2me(java) for 2 xml files, now I want to show those 2 xml files on LWUIT Tabs.
That means, when my application runs, default tab will be displayed (on that tab my first Rss xml file Titles should be displayed), and when the user click on tab2 my second Rss xml titles should be displayed.
I am able to display the same titles of one rss files on both the tabs, how to control my flow to achieve my task?
Here my code:
public class XMLMidlet extends MIDlet implements ActionListener {
public XMLMidlet() {
Display.init(this);
news = new Vector();
m_backCommand = new Command("Back");
cmdExit = new Command("EXIT");
cmdDetails = new Command("Details");
}
public void startApp() {
//RssFeed URL's
String urls[] = {"http://topnews-23.rss",
"http://topstory-12.rss"};
for(int i=0;i<urls.length;i++){
ParseThread myThread = new ParseThread(this,urls[i]);
//this will start the second thread
myThread.getXMLFeed(urls[i]);
}
}
//method called by the parsing thread
public void addNews(News newsItem,String url) {
try{
news.addElement(newsItem);
form1 = new Form();
myNewsList = new List(newsVector);
newsList =new List(newsVector);
myNewsList.setRenderer(new NewsListCellRenderer());
newsList.setRenderer(new NewsListCellRenderer());
tabs=new Tabs(Component.TOP);
tabs.addTab("TopNews", myNewsList);
tabs.addTab("Topstory",newsList);
form1.addComponent(tabs);
form1.show();
}
catch(Exception e){
e.printStackTrace();
}
}
You should move below code
myNewsList = new List(newsVector);
newsList =new List(newsVector);
myNewsList.setRenderer(new NewsListCellRenderer());
newsList.setRenderer(new NewsListCellRenderer());
tabs=new Tabs(Component.TOP);
form1 = new Form();
tabs=new Tabs(Component.TOP);
tabs.addTab("TopNews", myNewsList);
tabs.addTab("Topstory",newsList);
from addNews method to constructor XMLMidlet. addNews method should use url parameter to differ for which list the newsItem is directed.
Update
Below is how I think you should implement addNews method:
public void addNews(News newsItem, String url) {
if (url.endsWith("topnews-20.rss")) {
myNewsList.addElement(newsItem);
} else if (url.endsWith("topstory-25.rss")) {
newsList.addElement(newsItem);
}
}
serRenderer does not need to be called from addNews and form1.show() should be moved to startApp.

Binding an external (BCS) list to a SPDataGrid in Sharepoint 2010

I've created a BCS service and created an external list from the BCS content-type.
I have then tried to add a SPGridView control to a webpart. I am getting an exception as soon as I call my SPGridview's DataBind() method, here is what the code looks like:
namespace BCSService.CustomWebPart
{
[ToolboxItemAttribute(false)]
public class CustomWebPart : WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = #"~/_CONTROLTEMPLATES/BCSShims/CustomWorkEstimateWebPart/CustomWorkEstimateWebPartUserControl.ascx";
private SPGridView gv;
private SPDataSource spdata;
private SPSite site;
private SPWeb web;
private SPList we_list;
protected override void CreateChildControls()
{
base.CreateChildControls();
Control control = Page.LoadControl(_ascxPath);
Controls.Add(control);
this.site = SPContext.Current.Site;
this.web = this.site.OpenWeb();
this.we_list = this.web.Lists["BCSList"];
this.spdata = new SPDataSource();
Controls.Add(this.spdata);
this.gv = new SPGridView();
this.gv.AutoGenerateColumns = false;
Controls.Add(this.gv);
}
protected void BindColumns()
{
this.spdata.DataSourceMode = SPDataSourceMode.List;
this.spdata.List = this.we_list;
this.spdata.UseInternalName = true;
this.spdata.DataBind();
this.gv.AllowSorting = false;
this.gv.PageSize = 200;
this.gv.DataSource = this.spdata;
Dictionary<string, string> listFields = new Dictionary<string, string>();
listFields.Add("CompanyName", "Company Name");
listFields.Add("ContactDetails", "Contact Details");
listFields.Add("ProjectDescription", "Description");
foreach (var row in listFields)
{
SPBoundField boundField = new SPBoundField();
boundField.HeaderText = row.Value;
boundField.DataField = row.Key;
this.gv.Columns.Add(boundField);
}
}
protected override void RenderContents(HtmlTextWriter writer)
{
if (!Page.IsPostBack)
{
this.BindColumns();
this.gv.DataBind();
}
this.gv.RenderControl(writer);
}
}
}
The DataBind() method is throwing the following exception:
Object reference not set to an instance of an object.
at Microsoft.SharePoint.WebControls.SPDataSourceViewResultItem.System.ComponentModel.ICustomTypeDescriptor.GetProperties()
at System.ComponentModel.TypeDescriptor.MergedTypeDescriptor.System.ComponentModel.ICustomTypeDescriptor.GetProperties()
at System.ComponentModel.TypeDescriptor.GetPropertiesImpl(Object component, Attribute[] attributes, Boolean noCustomTypeDesc, Boolean noAttributes)
at System.ComponentModel.TypeDescriptor.GetProperties(Object component)
at Microsoft.SharePoint.WebControls.SPBoundField.DataBindingEventHandler(Object sender, EventArgs e)
at System.Web.UI.Control.OnDataBinding(EventArgs e)
at System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding)
at System.Web.UI.Control.DataBindChildren()
at System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding)
at System.Web.UI.Control.DataBindChildren()
at System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding)
at System.Web.UI.WebControls.GridView.CreateRow(Int32 rowIndex, Int32 dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState, Boolean dataBind, Object dataItem, DataControlField[] fields, TableRowCollection rows, PagedDataSource pagedDataSource)
at System.Web.UI.WebControls.GridView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding)
at Microsoft.SharePoint.WebControls.SPGridView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding)
at System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data)
at System.Web.UI.WebControls.GridView.PerformDataBinding(IEnumerable data)
at System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data)
at System.Web.UI.WebControls.DataBoundControl.PerformSelect()
at BCSService.CustomWebPart.CustomWorkEstimateWebPart.RenderContents(HtmlTextWriter writer)
I have verified that this.we_list is not empty (In Visual Studio debugger's locals tab, I can see this.we_list.Items.Count is set to 99, although this.we_list.ItemCount is set to 0.)
Also, that all seems to work okay against non-external lists, but I see nothing in the docs about external lists not being supported in SPGridView or SPDataSource, and the exception makes no mention of external lists not being supported. Has anyone run into this issue?
This seems to be a possible Sharepoint Server 2010 bug (I'm using Sharepoint Server 2010 Enterprise Edition). Ultimately, I solved the problem by adding a to_datatable() conversion method to my BCS service entity that simply uses the statis ReadList() method, collects its output, and inserts the data into a DataTable object.

Resources