我是Silverlight,C#,visualstudio初学者,我正在寻找解决方案。我想将combobox绑定到SQL server表中的数据。表中有ID和Name。另外当组合框将成功绑定我想,在应用程序中从组合框中选择一些东西并用“OK”按钮插入到Sql server表中作为值int(我正在使用sql过程)。
插入:
public ObservableCollection<ComboboxPW> ReadComboboxPW(int ID_pw)
{
ObservableCollection<ComboboxPW> result = new ObservableCollection<ComboboxPW>();
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 = "COMBOBOX_PW";
cmd.Parameters.AddWithValue("ID_pw", ID_pw);
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
ComboboxPW lista = new ComboboxPW();
lista.PW = dr.GetString(0);
lista.IDPW = dr.GetString(0);
result.Add(lista);
}
dr.Close();
return result;
}
catch (SqlException e)
{
ComboboxPW lista = new ComboboxPW();
lista.PW = e.Message;
result.Add(lista);
return result;
}
finally
{
conn.Close();
};
}
MY CLASS:
public class ComboboxPW
{
public string PW { get; set; }
public string IDPW { get; set; }
}
XAML:
<ComboBox x:Name="comboBoxPW" HorizontalAlignment="Left" Margin="40,117,0,0" VerticalAlignment="Top" Width="366"
SelectedItem="{Binding ReadComboboxPW}" DisplayMemberPath="PW" SelectedValuePath="IDPW" SelectionChanged="comboBoxPW_SelectionChanged" />
BUTTON OK:
private void OKButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
ServiceReference1.Service1Client webService = new ServiceReference1.Service1Client();
webService.InsertPWAsync(comboBoxPW.SelectedValue);
以上是错误,低于图片:
SQL中的程序:
PROCEDURE [dbo].[COMBOBOX_PW]
@ID_pw int
AS
BEGIN
SET NOCOUNT ON;
Select
Nazwa_PW, ID_PW
FROM [dbo].[DOSTEPNE_PW]
where (ID_PW = @ID_pw or @ID_pw = 0)
END
public int InsertPW(int PW)
{
string nwConn = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(nwConn);
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.CommandText = "Zapisz_PW";
cmd.Parameters.AddWithValue("PW", PW);
conn.Open();
int result = cmd.ExecuteNonQuery();
conn.Close();
if (result > 0)
{
return result;
}
else
{
return 0;
}
}
catch (SqlException e)
{
int result = 0;
return result;
}
finally
{
conn.Close();
};
插入sql表:
public int InsertPW(int PW)
{
string nwConn = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(nwConn);
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.CommandText = "Zapisz_PW";
cmd.Parameters.AddWithValue("PW", PW);
conn.Open();
int result = cmd.ExecuteNonQuery();
conn.Close();
if (result > 0)
{
return result;
}
else
{
return 0;
}
}
catch (SqlException e)
{
int result = 0;
return result;
}
finally
{
conn.Close();
};