C# Instances error - c#

so I have my Winform, in which I have a dgv with data in it, and I need to be able to save that data into two separated arraylists when the appropiate cell is clicked.
No problem with that really, but I hav which might be possibly the dumbest error to be ever programmed:
I need to instance the class where the arraylists are, "clsAL", but the programme still throws an error, arguing that the "Object reference not set to an instance of an object". Here's the code (ingore anything that has nothing to do with this, specially if it's in spanish :D)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication7
{
public partial class FormH : Form
{
clsAL cls;
public FormH()
{
InitializeComponent();
}
private void FormH_Load(object sender, EventArgs e)
{
cls = new clsAL();
OleDbCommand comm;
OleDbConnection conn = new OleDbConnection();
DataSet dset;
OleDbDataAdapter adap = new OleDbDataAdapter();
OleDbCommandBuilder cmb;
conn.ConnectionString = "Provider = 'Microsoft.Jet.OLEDB.4.0'; Data Source = 'RoboTIC.mdb'";
comm = new OleDbCommand("Select * From tblHistorial", conn);
adap = new OleDbDataAdapter(comm);
dset = new DataSet();
adap.Fill(dset, "tblHistorial");
dgvHistorial.DataSource = dset.Tables["tblHistorial"];
}
private void dgvHistorial_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
cls = new clsAL();
string operacion = dgvHistorial.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
cls.dir.Clear();
cls.time.Clear();
string aux = "";
for (int a = 0; a > operacion.Length; a++)
{
aux = aux + operacion[a];
if (aux == "a")
{
cls.dir.Add("avanzar");
}
if (aux == "d")
{
cls.dir.Add("derecha");
}
if (aux == "i")
{
cls.dir.Add("izquierda");
}
if (aux == "r")
{
cls.dir.Add("retroceder");
}
if (aux == "/")
{
}
if (aux != "a" && aux != "a" && aux != "a" && aux != "a" && aux != "/")
{
cls.time.Add(Convert.ToInt32(operacion[a]+operacion[a+1]));
}
}
}
}
}

The problem is with the dir arraylist in clsAl. This is a NullReferenceException. It is because you haven't allocated the dir arraylist at the time you're trying to call Clear() on it.
In the constructor for clsAl add
clsAl()
{
dir = new ArrayList();
time = new ArrayList();
}
and you will stop getting these exceptions.

Related

WinForm DataGridView have only one row although DataSource have two or more rows

I set a List have 2 elements to the dataGridView's DataSource, but it's always have one row, the RowCount property is 1. This is so strange
My code below have some Entity class name which I must explain.
HoaDon is Order
ChiTietHoaDon is OrderDetail
SanPham is Product
Code:
using GymFitnessOlympic.Controller;
using GymFitnessOlympic.Models;
using GymFitnessOlympic.Models.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GymFitnessOlympic.View.ActForm
{
public partial class FrmBanHang2 : Form
{
List<SanPham> allSanPham;
List<ChiTietHoaDon> allChiTiet = new List<ChiTietHoaDon>();
HoaDon hoaDon = new HoaDon();
public FrmBanHang2()
{
InitializeComponent();
int phongID = Login.GetPhongHienTai().MaPhongTap;
allSanPham = SanPhamController.GetList(phongID);
dgrChiTiet.AutoGenerateColumns = false;
dgrChiTiet.AutoGenerateColumns = false;
loadListSanPham(allSanPham);
}
void loadListSanPham(List<SanPham> li)
{
lbSanPham.DataSource = li;
}
void updateTable()
{
dgrChiTiet.DataSource = allChiTiet;
int n = dgrChiTiet.RowCount;
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (spnQuantity.Value <= 0)
{
dxErrorProvider1.SetError(spnQuantity, "Quantity must be greater than 0");
spnQuantity.Focus();
return;
}
int gia;
if (!int.TryParse(txtPrice.Text, out gia) || (gia % 500 != 0) || gia <= 0)
{
txtPrice.Focus();
dxErrorProvider1.SetError(txtPrice, "Invalid Price");
return;
}
if (lbSanPham.SelectedItem != null)
{
var sp = (SanPham)lbSanPham.SelectedItem;
int soLuong = int.Parse(spnQuantity.Text);
ChiTietHoaDon c = new ChiTietHoaDon()
{
Gia = gia,
MaSanPham = sp.MaSanPham,
SoLuong = soLuong,
SanPham = sp
};
var old = allChiTiet.FirstOrDefault(c1 => c1.MaSanPham == c.MaSanPham);
if (old != null)
{
old.SoLuong += c.SoLuong;
}
else
{
allChiTiet.Add(c);
}
}
updateTable();
}
private void lbSanPham_SelectedIndexChanged(object sender, EventArgs e)
{
if (lbSanPham.SelectedItem != null)
{
var sp = (SanPham)lbSanPham.SelectedItem;
txtTenSanPham.Text
= sp.TenSanPham;
txtPrice.Text = sp.Gia.ToString();
spnQuantity.Text = "1";
}
}
}
}
This is because you are using List<ChiTietHoaDon> as data source of your datagridview and it doesn't notify changes so the grid doesn't show new items.
You should use BindingList<ChiTietHoaDon> instead.
But if you want to continue using List<ChiTietHoaDon>, to update the grid you can first set dgrChiTiet.DataSource=null; and then dgrChiTiet.DataSource = allChiTiet;

Update datagrid data in another page's form in Asp.net C#

I am new to asp.net and now I am testing simple methods. I want to edit datagrid in form of another page. Here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class mymembertype : System.Web.UI.Page
{
public static int mem_typeid;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["valueid"] != null)
{
mem_typeid = (int)(Session["valueid"]);
string memtype_name = Convert.ToString(Session["valueName"]);
string rate = Convert.ToString(Session["rate"]);
txtmembtype.Text = Convert.ToString(memtype_name);
txtdscrate.Text = rate;
}
}
protected void Insert_membertype_Click(object sender, EventArgs e)
{
funtions fun = new funtions();
if (mem_typeid == null)
{
if (txtmembtype.Text != "")
{
if (txtdscrate.Text != "")
{
string membetype = txtmembtype.Text;
int dscrate = Convert.ToInt32(txtdscrate.Text);
bool chk = fun.Insert_membertype(membetype, dscrate);
if (chk)
lblInfo.Text = " saving membertype successful";
else
lblInfo.Text = "Error saving membertype";
}
}
}
else
{
if (txtmembtype.Text != "")
{
if (txtdscrate.Text != "")
{
string membetype = txtmembtype.Text;
int dscrate = Convert.ToInt32(txtdscrate.Text);
bool chk = fun.Update_memberType(mem_typeid, membetype, dscrate);
if (chk)
lblInfo.Text = " Updating membertype successful";
else
lblInfo.Text = "Error Updating membertype";
}
}
}
}
here is my update function
public bool Update_memberType(int id, string name, int dsc)
{
string connectionString =
WebConfigurationManager.ConnectionStrings["Spa"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
int memid = id;
string membtype = name;
int dsrate = dsc;
Boolean chk = false;
try
{
myConnection.Open();
SqlCommand cmd = new SqlCommand("Update_Membtype", myConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#mem_typeId", memid);
cmd.Parameters.AddWithValue("#membertype_name", membtype);
cmd.Parameters.AddWithValue("#dsc_rate", dsrate);
cmd.ExecuteNonQuery();
chk = true;
}
catch (Exception err)
{
chk = false;
}
return chk;
}
When I try to update data , it doesn't change nothing. Variable has its original values. Does not change to new data in text boxes. How can I fix these error.Please...

How can I let page fully loaded and show the searching result then go to next loop?

I want to write an windows form application who can do auto data filling in an textbox on the web page and get the corresponding data show on the page one by one. I met a problem that my loop goes too fast and I cannot see the result showing on the page. How can I let the page fully loaded and then go the next loop?
My designer has a textbox which is used to input url, webBrowser to browse the web page, the button is used to lunch the page.
My code are as below. I use "http://finance.yahoo.com/" as testing page. Testing data is in excel format. the data is a row, like " msft, bac, f, aapl".
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Net;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string url = textBox1.Text;
var request = (HttpWebRequest)WebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
string content = sr.ReadToEnd();
webBrowser1.DocumentText = content;
}
public void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlElement tbUserid = webBrowser1.Document.GetElementById("mnp-search_box");
//HtmlElement tbPasswd = webBrowser1.Document.GetElementById("pwdInput");
HtmlElement btnSubmit = webBrowser1.Document.GetElementById("yucs-sprop_button");
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
if (tbUserid == null || btnSubmit == null)
{
return;
}
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='d:\\testing file\\list.xls';Extended Properties= \"Excel 8.0;HDR=Yes;IMEX=1\";");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [List$]", con);
DataTable dt = new DataTable();
da.Fill(dt);
/* int i = 0;
do
{
string str = dt.Rows[i][0].ToString();
tbUserid.SetAttribute("value", str);
//System.Threading.Thread.Sleep(10000);
btnSubmit.InvokeMember("click");
evt.WaitOne();
i++;
}
while (i < dt.Rows.Count);
*/
for (int i = 0; i < dt.Rows.Count; i++)
{
string str = dt.Rows[i][0].ToString();
tbUserid.SetAttribute("value", str);
btnSubmit.InvokeMember("click");
Application.DoEvents();
//System.Threading.Thread.Sleep(100);
}
// ((WebBrowser)sender).Dispose();
}
}
}
Ok, so, let's suppose your target page is http://thisis.my/addres.html and when the page has been used to insert a row it redirects to http://thisis.my/secondaddres.html.
First, let's create a List to hold all the data from the table and two strings to hold the concrete addresses:
List<string> rows = new List<string>();
static string fillAddress = "http://thisis.my/addres.html";
static string sentAddress = "http://thisis.my/secondaddres.html";
Second, when the button is pressed load the data in the list and do your first navigation:
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='d:\\testing file\\list.xls';Extended Properties= \"Excel 8.0;HDR=Yes;IMEX=1\";");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [List$]", con);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
string str = dt.Rows[i][0].ToString();
rows.Add(str);
}
webBrowser1.NavigateTo(fillAddress);
}
Ensure that your DocumentCompleted event is hooked thorugh designer or code.
And finally when a document has been fully loaded the do this sequence:
If page == fillAddress
If rows is not empty
Extract row
Fill row
Submit
else
We have finished
else
Navigate to fillAddress
-
public async void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if(e.Url.ToString() == fillAddress)
{
if(rows.Count > 0)
{
HtmlElement tbUserid = webBrowser1.Document.GetElementById("mnp-search_box");
HtmlElement btnSubmit = webBrowser1.Document.GetElementById("yucs-sprop_button");
if (tbUserid == null || btnSubmit == null)
return;
string str = rows[0];
rows.RemoveAt(0);
tbUserid.SetAttribute("value", str);
btnSubmit.InvokeMember("click");
}
else
return;
}
else if(e.Url.ToString() == sentAddress)
webBrowser1.NavigateTo(fillAddress);
}
I have done tons of assumptions but you will get the general idea: get a list of data, navigate, when the page to fill is loaded fill the row and send the data, when the confirmation is done navigate again to the fill form and repeat until no data is left.

C# Form not included in the project

I am having this strange error/conflict. I have two forms in my application. Both have same namespaces, and when I try to create an object of the next form it doesn't shows up. This is my code in Form1
Form2 form2 = new Form2();
form2.Show();
this.Hide();
And when I add another form in the project (like form3.cs) it shows up. Why is this "form2" missing? Although it is available in the project.
Form 1 code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using UHF_Demo;
namespace UHF_Demo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void submit_Click(object sender, EventArgs e)
{
{
string query = "Select * from login_info where username = '" + username_tb.Text + "' and password = '" + password_tb.Text + "'";
SqlCeConnection conn = new SqlCeConnection();
conn.ConnectionString = #"Data Source =\Program Files\valcan\employeedb.sdf";
SqlCeCommand cmd = new SqlCeCommand(query, conn);
conn.Open();
SqlCeDataReader dr = cmd.ExecuteReader();
int counter = 0;
while (dr.Read())
{
counter = counter + 1;
}
if (counter > 0)
{
Form2 form2 = new Form2();
form2.Show();
this.Hide();
}
else
{
MessageBox.Show("Invalid Login name or Password. Please try again ....");
}
conn.Close();
dr.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'locationds.login_info' table. You can move, or remove it, as needed.
this.login_infoTableAdapter.Fill(this.locationds.login_info);
}
}
}
}}
Form2 code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.Globalization;
using System.IO;
namespace UHF_Demo
{
public partial class MR6651_DEMO : Form
{
public bool BeingId = false;
byte[,] TagBuf = new byte[100, 14];
byte TagCnt = 0;
ComPort Port0 = new ComPort();
private CultureInfo culinfo = CultureInfo.CurrentCulture;
public MR6651_DEMO()
{
InitializeComponent();
double CostomiseFQ = 900.000;
for (int i = 0; i < 60; i++)
{
comboBox1.Items.Add(CostomiseFQ.ToString("#0.000")+"M");
comboBox2.Items.Add(CostomiseFQ.ToString("#0.000") + "M");
CostomiseFQ +=0.5;
}
MEMBANK.SelectedIndex = 1;
WORDPTR.SelectedIndex = 0;
WORDCNT.SelectedIndex = 0;
cmbFreqType.SelectedIndex = 2;
VALUE.Text = "";
//tabPage3.Parent = null;
if (culinfo.ToString() == "zh-CN")
{
this.Text = "UHF¶ÁдÑÝʾ";
TabPage page1 = tabControl1.TabPages[0];
page1.Text = "»¶Ó­";
TabPage page2 = tabControl1.TabPages[1];
page2.Text = "EPC²âÊÔ";
//TabPage page3 = tabControl1.TabPages[2];
//page3.Text = "6B²âÊÔ";
label5.Text = "¹¦ÂÊ";
label8.Text = "ƵÂÊ";
labStatusBar.Text = "×¼±¸¾ÍÐ÷";
btnQueryPower.Text = "²éѯ";
btnSetPower.Text = "ÉèÖÃ";
EXIT.Text = "Í˳ö";
chkAutoClr.Text = "¹ýÂËÖظ´±êÇ©";
ID.Text = "ʶ±ð";
btnEPClist.Text = "Áбí";
button1.Text = "EPC¿é²Ù×÷";
CLEAR.Text = "Çå¿Õ";
label2.Text = "×ÖµØÖ·";
label3.Text = "×Ö³¤¶È";
label4.Text = "Êý¾Ý";
READ.Text = "¶ÁÈ¡";
WRITE.Text = "дÈë";
INIT.Text = "³õʼ»¯";
label10.Text = "×Ö½ÚµØÖ·";
label7.Text = "×Ö½Ú³¤¶È";
label9.Text = "Êý¾Ý";
btn6BID.Text = "ʶ±ð";
btn6BRead.Text = "¶ÁÈ¡";
btn6BWrite.Text = "дÈë";
btn6BLock.Text = "Ëø¶¨";
chkClear6B.Text = "¹ýÂËÖظ´±êÇ©";
btn6BClear.Text = "Çå¿Õ";
btnSaveFile.Text = "±£´æÎļþ";
label1.Text = "Êý¾Ý¿é";
cmbFreqType.Items.Clear();
cmbFreqType.Items.Add("Öйú");
cmbFreqType.Items.Add("±±ÃÀ");
cmbFreqType.Items.Add("Å·ÖÞ");
cmbFreqType.Items.Add("×Ô¶¨Òå");
cmbFreqType.SelectedIndex = 2;
listViewEPC.Columns[0].Text = "EPCÂë";
listViewEPC.Columns[1].Text = "񅧏";
label11.Text = "ÆðʼƵµã";
label12.Text = "ÖÕֹƵµã";
btn_locktid.Text = "ËøTID";
btn_seelocktid.Text = "²é¿´TIDËø";
}
}
private void EPC_DEMO_Load(object sender, EventArgs e)
{
if (Port0.Open() == 0)
{
if (culinfo.ToString() == "zh-CN")
{
labStatusBar.Text = "ͨѶ¶Ë¿Ú´ò¿ª³É¹¦!";
}
else
{
labStatusBar.Text = "Start conmunicate commport success!";
}
//aStatus = Port0.SetRf(10, 2);
Thread.Sleep(500);
btnQueryPower_Click(sender, e);
Sound.PlayWAV(#"\Application Data\Rfid\wav\shutter.wav");
for (int i = 0; i < 223; i++)
ADDR6B.Items.Add(i.ToString());
ADDR6B.SelectedIndex = 0;
ByteCnt6B.SelectedIndex = 0;
}
}
You have no Form2 class. You've got a MR6651_DEMO class. Try creating an instance of that instead. Your compiler should be telling you exactly what's wrong.
The name of a file doesn't have to have anything to do with the class contained within - that they often match is a matter of hygiene and sanity. =)
In your Form 2 Code there is no Class Definition for a Class named Form2. I guess thats the cause why it can't be found.

Updating a database in window form and c#

I am adding records to my database via a windows form. But when ever I add a new record it doesnt update until I close the app and then start again. Even though I think I am telling it to update (Im obv not!!)
Do I need a new varibale to update the database? Im a little stuck.
EDIT: All code on this..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace MediaManagementSystem
{
public partial class AddMedia : Form
{
//database var
OleDbConnection m_cnADONetConnection = new OleDbConnection();
OleDbDataAdapter m_daDataAdapter;
OleDbDataAdapter m_cbCommandBuilder;
DataTable m_dtMedia = new DataTable();
int m_rowPosition = 0;
public AddMedia()
{
InitializeComponent();
}
private void BrowseButton_Click(object sender, EventArgs e)
{
//load up file dialog and find media
if (addFileDialog.ShowDialog() == DialogResult.OK)
{
//add media file name to file path text box
txtFilePath.Text = addFileDialog.FileName;
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void AddButton_Click(object sender, EventArgs e)
{
//add the new record to the database
DataRow drNewRow = m_dtMedia.NewRow();
drNewRow["FilePath"] = txtFilePath.Text;
drNewRow["Subject"] = txtSubject.Text;
drNewRow["Title"] = txtTitle.Text;
drNewRow["Keywords"] = txtKeywords.Text;
drNewRow["MediaType"] = AddComboBox.Text;
m_dtMedia.Rows.Add(drNewRow);
m_daDataAdapter.Update(m_dtMedia);
m_rowPosition = m_dtMedia.Rows.Count - 1;
this.ShowCurrentRecord();
this.Close();
}
private void AddMedia_Load(object sender, EventArgs e)
{
//link to the database and conect to database
m_cnADONetConnection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Max\Documents\Visual Studio 2010\Projects\MediaManagementSystem\MediaManagementSystem\bin\Debug\MediaDB.mdb";
m_cnADONetConnection.Open();
OleDbConnection objConnection = new OleDbConnection(m_cnADONetConnection.ConnectionString);
m_daDataAdapter = new OleDbDataAdapter("Select * From Media", m_cnADONetConnection);
OleDbCommandBuilder m_cbCommandBuilder = new OleDbCommandBuilder(m_daDataAdapter);
m_daDataAdapter.Fill(m_dtMedia);
m_daDataAdapter.Update(m_dtMedia);
}
public void ShowCurrentRecord()
{
m_daDataAdapter.Update(m_dtMedia);
if (m_dtMedia.Rows.Count == 0)
{
txtFilePath.Text = "";
txtSubject.Text = "";
txtTitle.Text = "";
txtKeywords.Text = "";
AddComboBox.Text = "";
return;
}
txtFilePath.Text = m_dtMedia.Rows[m_rowPosition]["FilePath"].ToString();
txtSubject.Text = m_dtMedia.Rows[m_rowPosition]["Subject"].ToString();
txtTitle.Text = m_dtMedia.Rows[m_rowPosition]["Title"].ToString();
txtKeywords.Text = m_dtMedia.Rows[m_rowPosition]["Keywords"].ToString();
AddComboBox.Text = m_dtMedia.Rows[m_rowPosition]["MediaType"].ToString();
}
}
}
It would best if you use DataSet and then update the records in it. Finally you need to call AcceptChanges() after the update() command to commit the changes with dataset something as below also reload the data after to enter to get the recent data info:
dataset.AcceptChanges()
After you open AddMedia form from your MAIN form, you need to RALOAD all your records again. Look how the form is doing it when it opens and do the same AFTER you open your AddMedia form ;)

Categories

Resources