0

Hi I have some method which send me data from sql table and I want that - when I click button in datagridview - that send parameter to the method and parameter will have ID value(like on picture 107 or 106). Below on the picture is datagridview with 2 buttons and ID column.

enter image description here

public ObservableCollection<MyClass> ReadUpdate(int id_update)
{
ObservableCollection<MyClass> result = new ObservableCollection<MyClass>();
string nwConn = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
SqlDataReader dr;
SqlConnection conn = new SqlConnection(nwConn);
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.CommandText = "Insert_Update";
cmd.Parameters.AddWithValue("@id_update", id_update);
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
MyClass lin = new MyClass();

lin.id = dr.GetInt32(1);
if (!dr.IsDBNull(2)) lin.other = dr.GetString(2);
if (!dr.IsDBNull(3)) lin.barkod = dr.GetString(3);
if (!dr.IsDBNull(4)) lin.pw = dr.GetInt32(4);

result.Add(lin);
}
dr.Close();
return result;

}
catch (SqlException e)
{
MyClass lin = new MyClass();
lin.other = e.Message;

result.Add(lin);
return result;

}
finally
{
conn.Close();

};
}

My class:

 public class PIS
{
public int ID { get; set; } 
 }

And my button:

private void btnUpdate_Click(object sender, System.Windows.RoutedEventArgs e)
{
pis_update = (PIS)((Button)sender).DataContext;
ChildWindow_Update childWindow_update = new ChildWindow_Update();
childWindow_update.DataContext = ((Pismo)((Button)sender).DataContext).Id_Pismo;
childWindow_update.Closed += ChildWindow_Update_Closed;
childWindow_update.Show();
} 

public ChildWindow_Update()
{
InitializeComponent();
ServiceReference1.Service1Client webService = new ServiceReference1.Service1Client();
webService.ReadUpdateAsync((int)this.DataContext);
webService.ReadUpdateCompleted += WebService_ReadUpdateCompleted; 

private void WebService_ReadUpdateCompleted(object sender, ServiceReference1.ReadUpdateCompletedEventArgs e)
{
if (e.Result != null)
{
//do something

}
} 

I have error in webService.ReadUpdateAsync((int)this.DataContext); "Null REference Exception".

nvoigt
  • 75,013
  • 26
  • 93
  • 142
Alan
  • 23
  • 3
  • Please [read this SO question about NullReferenceException](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it). – Markus Weninger Feb 19 '16 at 15:28

1 Answers1

1

At the time of your constructor call, your DataContext has not been set yet. You should make the id a constructor parameter if you need it in the constructor.

Generally speaking, you should use MVVM and the command pattern, where you can specify your id data as the command parameter in your XAML.

nvoigt
  • 75,013
  • 26
  • 93
  • 142