Error: System.NullReferenceException - c#

I have this code, but when I click on one of the record in listbox I have this error:
System.NullReferenceException
This is my code:
namespace CestovniPrikaz
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=(Loca..Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{ InitializeComponent();
loadlist(); }
private void Form2_Load(object sender, EventArgs e)
{ cmd.Connection = cn;
loadlist(); }
private void loadlist()
{ listBox1.Items.Clear();
cmd.Connection = cn;
cn.Open();
cmd.CommandText = "select Name from Person";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while(dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
} }
cn.Close(); }
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{ListBox l = sender as ListBox;
if (l.SelectedIndex != -1)
{
listBox1.SelectedValue = l.SelectedIndex;
txtName.Text = listBox1.SelectedValue.ToString();
}} } }
The problem is probably in this line:
txtName.Text = listBox1.SelectedValue.ToString();
Have you any idea please?

Try this:
txtName.Text = l.SelectedItem.ToString();

This seems to be the issue.
listBox1.SelectedValue = l.SelectedIndex;
txtName.Text = listBox1.SelectedValue.ToString();
SelectedValue is null and you're calling ToString which throws the exception. Why not just do
txtName.Text = l.SelectedIndex.ToString();
Also, you're calling listBox1 directly as well as using l (listBox1.SelectedValue = l.SelectedIndex;). They both reference the same ListBox.

Related

c# Ask to save changes before selecting another item in listbox

I'd like to integrate an autocheck that prevent user to forget to save changes with a textbox 'Do you want to save change' Yes-No
If yes - > save
if no - > returns
Here's my code without the checking
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
OleDbConnection conn;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
conn = new
OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data
Source=" + #Application.StartupPath + "\\Database1.mdb");
fill_lb();
}
private void fill_lb()
{
listBox1.Items.Clear();
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [table1] ORDER BY firstn";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
listBox1.Items.Add(dr["firstn"].ToString());
}
conn.Close();
}
private void listBox1_SelectedIndexChanged(object sender,
EventArgs e)
{
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [table1] WHERE firstn='" +
listBox1.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
textBox_fn.Text = dr["firstn"].ToString();
textBox_ln.Text = dr["lastn"].ToString();
}
conn.Close();
}
private void button_savenew_Click(object sender, EventArgs e)
{
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO [table1] ([firstn],[lastn])
values ([#firstn],[#lastn])";
cmd.Parameters.AddWithValue("#firstn", textBox_fn.Text);
cmd.Parameters.AddWithValue("#lastn", textBox_ln.Text);
cmd.ExecuteNonQuery();
fill_lb();
conn.Close();
}
private void button_modify_Click(object sender, EventArgs e)
{
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "UPDATE [Table1] SET [firstn]=[#firstn],
[lastn]=[#lastn] WHERE firstn = '" +
listBox1.SelectedItem.ToString() + "'";
cmd.Parameters.AddWithValue("#firstn", textBox_fn.Text);
cmd.Parameters.AddWithValue("#lastn", textBox_ln.Text);
cmd.ExecuteNonQuery();
fill_lb();
conn.Close();
}
private void button_new_Click(object sender, EventArgs e)
{
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
}
}
}
What I've done with no success :
Bool modified = false
private void textBox_fn_TextChanged(object sender, EventArgs e)
{
modified = true;
}
private void textBox_ln_TextChanged(object sender, EventArgs e)
{
modified = true;
}
private void listBox1_SelectedIndexChanged(object sender,
EventArgs e)
{
if (modified.Equals(true))
{
DialogResult dialogr = MessageBox.Show("Do you want to
save change ?","", MessageBoxButtons.YesNo);
switch (dialogr)
{
case DialogResult.Yes:
button_savenew.PerformClick();
modifie = false;
break;
case DialogResult.No:
return;
}
}
modified = false;
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
}
This is not working because it ask to save everytime I click on listbox
What Can I do ?
I would look into using a MessageBox. It would greatly simplify what you are trying to do. Perform the check in the background, and if they didn't save do this:
string message = "Are you sure you don't want to save?";
string caption = "Error Detected in Input";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(message, "Are you Sure", buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
// Save file
}
if (result == System.Windows.Forms.DialogResult.No){
this.Close();
}
Remove the the associate code from listBox1_SelectedIndexChanged event and add to it the end of button_modify_Click. Try like:
private void Check()
{
if (modified.Equals(true))
{
DialogResult dialogr = MessageBox.Show("Do you want to
save change ?","", MessageBoxButtons.YesNo);
switch (dialogr)
{
case DialogResult.Yes:
button_savenew.PerformClick();
modifie = false;
break;
case DialogResult.No:
return;
}
}
modified = false;
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
}
private void button_modify_Click(object sender, EventArgs e)
{
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "UPDATE [Table1] SET [firstn]=[#firstn],
[lastn]=[#lastn] WHERE firstn = '" +
listBox1.SelectedItem.ToString() + "'";
cmd.Parameters.AddWithValue("#firstn", textBox_fn.Text);
cmd.Parameters.AddWithValue("#lastn", textBox_ln.Text);
cmd.ExecuteNonQuery();
fill_lb();
Check(); //<--added here
conn.Close();
}
Try resetting modified after DB update, at the end of button_modify_Click
I think I found the right way to do the job using the tag property.
first I add a new boolean that will check if I leave a textbox
bool left_txtbox = false; //when leaving textbox
then I add this code the the Leave property of textboxes
private void textBox_fn_Leave(object sender, EventArgs e)
{
name = listBox1.SelectedItem.ToString();
textBox_fn.Tag = textBox_fn.Text;
left_txtbox = true;
}
private void textBox_ln_Leave(object sender, EventArgs e)
{
name = listBox1.SelectedItem.ToString();
textBox_ln.Tag = textBox_ln.Text;
left_txtbox = true;
}
on listbox selected index change I add the check when leaving textbox
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (left_txtbox == true) Check(); // if txtbox has been left, do the check
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
if (conn.State != ConnectionState.Open) { conn.Close(); conn.Open(); }
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [table1] WHERE firstn='" + listBox1.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
textBox_fn.Text = dr["firstn"].ToString();
textBox_ln.Text = dr["lastn"].ToString();
}
conn.Close();
}
finally the check itself, it will compare the Tag with the value stored in DB
private void Check()
{
if (conn.State != ConnectionState.Open) { conn.Close(); conn.Open(); }
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [table1] WHERE firstn='" + name + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
try // ignore null values
{
if (textBox_fn.Tag.ToString() != dr["firstn"].ToString()) { modified = true; }
if (textBox_ln.Tag.ToString() != dr["lastn"].ToString()) { modified = true; }
}
catch { }
if (modified.Equals(true))
{
DialogResult dialogr = MessageBox.Show("Do you want to save change ? ", "", MessageBoxButtons.YesNo);
switch (dialogr)
{
case DialogResult.Yes:
button_savenew.PerformClick();
modified = false;
break;
case DialogResult.No:
modified = false;
return;
}
}
modified = false;
}
I think the code can be optimized

C# loading data from MS Access database to listbox

public partial class Form1 : Form
{
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AsusK450c\documents\visual studio 2010\Projects\ADD\ADD\testing.accdb;Persist Security Info=True";
cmd.Connection = cn;
loaddata();
}
private void loaddata()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
try
{
string q = "select * from info";
cmd.CommandText = q;
cn.Open();
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
dr.Close();
cn.Close();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
}
This is an image of the database:
I added 2 list boxes. Those two should display the data i put in the database but It doesn't. I don't know which is wrong, the path, the code or the database
There is nothing wrong with you code. Check if you are getting any exceptions or pointed to the right database.
Also check if you have assigned the function Form1_Load() to form's load event
I'm not sure what your problem is, but you can change the connectionString by this way:
System.Data.OleDb.OleDbConnectionStringBuilder builder = new System.Data.OleDb.OleDbConnectionStringBuilder();
builder.Provider = "Microsoft.ACE.OLEDB.12.0";
builder.OleDbServices = -1;
builder.DataSource = #"C:\Users\AsusK450c\documents\visual studio 2010\Projects\ADD\ADD\testing.accdb";
cn.ConnectionString = builder.ConnectionString;
OleDbServices = -1 can help you.

updated values are not getting stored in the textbox

protected void Page_Load(object sender, EventArgs e)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
//Button click function
protected void Button1_Click(object sender, EventArgs e)
{
cn.Open();
st = "update patient_db set address ='" + TextBox1.Text + "' ,phone=" + TextBox2.Text+"where unique_id=123";
cmd = new SqlCommand(st, cn);
int result2 = cmd.ExecuteNonQuery();
if (Convert.ToBoolean(result2))
{
result1.Text = "details updated successfully";
}
cn.Close();
}
After assigning the value to textbox from the database,if I type some other new value in the text box,it is not taking the new value,it still persists with the old value.May i know the reason and solution for this? thanks in advance
Write a method LoadData, move the code from page_load into this method. Then call this method from page_load wrapped in a if(!IsPostBack)-check. Call this method also from the button-click event handler after you've updated the values.
private void LoadData()
{
using (var cn = new SqlConnection("Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True"))
{
cn.Open();
using(var cmd = new SqlCommand("select * from patient_db where unique_id = 123", cn))
using (var dr = cmd.ExecuteReader())
{
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
LoadData();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// ... update
LoadData();
}
Important notes:
Also use the using-statement for every object implementing IDisposable like the connection or the datareader. On that way all unmanaged resources are disposed properly. Even in case of an error.
If 123 is just an example and actually is a value provided by the user use sql-parameters to prevent sql-injection. No, use them always.
Add IsPostBack control at Page_Load method. Because before Button_Click event Page_Load event firing.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
}
You need to check page.Ispostback property in your page Load.
Here is your code.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
}
When you click on button then it will first call PageLoad event. So it will again set your old value to textbox and then it will call update method. So Update method will update old value to database.

Data doesn't get updated when an item is chosen from drop down list

I would like ask if you could help me with my codes as I don't get the result that I want which is to load the details of a particular paper from drop down list.
Currently, when the page loads, the details of the selected item will load up. But when I try to choose another item from the drop down list, corresponding details won't show up, the previous one still remains instead.
Under the properties of drop down list, I also set autopostback to yes so that it will automatically load the corresponding details of the item selected.
Please see codes below
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetPaper();
GetInk();
GetPaperDetails(ddlPaperName.SelectedItem.Value);
//pnlPrinting.Visible = true;
}
}
protected void btnCompute_Click(object sender, EventArgs e)
{
}
protected void btnCancel_Click(object sender, EventArgs e)
{
}
private void GetPaper()
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Papers";
SqlDataReader data = com.ExecuteReader();
ddlPaperName.DataSource = data;
ddlPaperName.DataValueField = "PaperID";
ddlPaperName.DataTextField = "PaperName";
ddlPaperName.DataBind();
data.Close();
con.Close();
}
private void GetPaperDetails(string paper)
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Papers WHERE PaperID=" + paper;
SqlDataReader data = com.ExecuteReader();
while (data.Read())
{
lblPaperPrice.Text = data["PaperPrice"].ToString();
lblDescription.Text = data["PaperDescription"].ToString();
lblSpecification.Text = data["PaperSpecification"].ToString();
imgPaper.ImageUrl = "../" + data["PaperImage"].ToString();
}
data.Close();
con.Close();
}
private void GetInk()
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Inks";
SqlDataReader data = com.ExecuteReader();
ddlPaperName.DataSource = data;
ddlPaperName.DataValueField = "InkID";
ddlPaperName.DataTextField = "InkName";
ddlPaperName.DataBind();
while (data.Read())
{
lblInkPrice.Text = data["InkPrice"].ToString();
}
data.Close();
con.Close();
}
protected void ddlPaperName_SelectedIndexChanged(object sender, EventArgs e)
{
GetPaperDetails(ddlPaperName.SelectedItem.Value);
}
Looking forward to your feedback here. Thanks!
Set AutoPostBack property to true of your drop down list.
us this code, for that,
if (!IsPostBack == true)
{
drpdownaccountnamebind();
drpdowncountrynamebind();
}
i hope this will be helpful,

Autocomplete for domain users

Is there any way to do autocomplete for domain users in .net?
Meaning, I want a textbox that when I will start and type Admin, it will complete it to \Administrator
Thanks.
Sure, you can hold a list of all valid domain account names and use an autocomplete (winforms example) with that data source.
Of course, this means you are exposing some sensitive information.
you can try like this for displaying domain user names ......
namespace AutoCompleteTextBox
{
public partial class frmAuto : Form
{
public string strConnection = ConfigurationManager.AppSettings["ConnString"];
AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
public frmAuto()
{
InitializeComponent();
}
private void frmAuto_Load(object sender, EventArgs e)
{
SqlDataReader dReader;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strConnection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText ="Select distinct [Name] from [Names]" + " order by [Name] asc";
conn.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader["Name"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtName.AutoCompleteCustomSource = namesCollection;
}
private void btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnOk_Click(object sender, EventArgs e)
{
MessageBox.Show(" this is autocomplete text box example");
}
}
}

Categories

Resources