Principales respuestas
como hacer una consulta usando linq to sql

Pregunta
-
hola amigos,
tengo una base de datos y estoy usando linq to sql para conectarme a ella, y todo me funciona.
asi es como lleno la base de datos:
public partial class NUEVOARTICULO : UserControl { public NUEVOARTICULO() { this.InitializeComponent(); } private void UserControlART_Loaded(object sender, RoutedEventArgs e) { Keyboard.Focus(textcodigo); using (puente1DataContext _contexto = new puente1DataContext()) { cbocategorias.ItemsSource = _contexto.CATEGORIAS.ToList(); cbocategorias.SelectedValuePath = "NOMBRE_CATEGORIA"; cbocategorias.DisplayMemberPath = "NOMBRE_CATEGORIA"; } } private void cboiva_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (cboiva.SelectedIndex > 0) { texnogravable.IsEnabled = true; texgravable.IsEnabled = true; } else { texnogravable.IsEnabled = false; texgravable.IsEnabled = false; } } private void Button_Click(object sender, RoutedEventArgs e) { if (textcodigo.Text.Trim() == string.Empty) { MessageBox.Show("El codigo es obligatorio.", "NUEVO ARTICULO", MessageBoxButton.OK, MessageBoxImage.Warning); Keyboard.Focus(textcodigo); return; } if (texnombre.Text.Trim() == string.Empty) { MessageBox.Show("El NOMBRE es obligatorio.", "NUEVO ARTICULO", MessageBoxButton.OK, MessageBoxImage.Warning); Keyboard.Focus(texnombre); return; } puente1DataContext _contexto = new puente1DataContext(); try { var ARTICULOS = new ARTICULOS { CODIGO = Int32.Parse(textcodigo.Text.ToString()), NOMBRE = texnombre.Text, IVA = double.Parse(cboiva.Text), PRECIO_COSTO_NOGRAVABLE = double.Parse(texnogravable.Text), PRECIO_COSTO_GRAVABLE = double.Parse(texgravable.Text), IMPUESTO = (double.Parse(texgravable.Text) * double.Parse(cboiva.Text))/100, TOTAL_PRECIO_COSTO = double.Parse(texpreciocosto.Text), PRECIO_VENTA = double.Parse(texprecioventa.Text), INCREMENTO_VENTA = ((double.Parse(texprecioventa.Text) - double.Parse(texpreciocosto.Text)) / double.Parse(texpreciocosto.Text)) * 100, EXISTENCIA = Int32.Parse(texexistencia.Text.ToString()), EXISTENCIA_MINIMA = Int32.Parse(texminimo.Text.ToString()), CATEGORIA = cbocategorias.Text, FECHA_VENCIMIENTO = DateTime.Parse(datePicker1.Text), FECHA_INGRESO = DateTime.Now, }; _contexto.ARTICULOS.InsertOnSubmit(ARTICULOS); _contexto.SubmitChanges(); MessageBox.Show("REGISTRO AGREGADO CORRECTAMENTE"); } catch (Exception ex) { MessageBox.Show(ex.Message, "NUEVO ARTICULO", MessageBoxButton.OK, MessageBoxImage.Error); } finally { textcodigo.Text = string.Empty; texnombre.Text = string.Empty; datePicker1.Text = string.Empty; cbocategorias.SelectedIndex = -1; } } private void button1_Click(object sender, RoutedEventArgs e) { AGREGARCATEGORIA AGREGAR = new AGREGARCATEGORIA(); AGREGAR.ShowDialog(); using (puente1DataContext _contexto = new puente1DataContext()) { cbocategorias.ItemsSource = _contexto.CATEGORIAS.ToList(); cbocategorias.SelectedValuePath = "NOMBRE_CATEGORIA"; cbocategorias.DisplayMemberPath = "NOMBRE_CATEGORIA"; } } }
pero ahora quiero hacer una consulta de esa misma base de datos, pero usando texbox para mostrar los resultados;
ademas tengo un texbox que llame teximpuesto y quiero que el texto en el sea la suma de otros dos texbox donde voy a insertar valores numericos.
Respuestas
-
Hola ciberastro.
Para hacer lo que quieres, la posible mejor opcion es realizar un multibinding (Solo si usas WPF, para silverlight tienes que hacer algo parecido ya que no esta disponible esta caracteristica).
para ello pongo un ejemplo:
codigo xaml:
<Window.Resources> <my:SumConverter x:Key="SumConverter" /> </Window.Resources> <StackPanel> <TextBlock Text="Numeros a sumar:"></TextBlock> <TextBox Height="23" HorizontalAlignment="Left" Name="textBox1" VerticalAlignment="Top" Width="120" /> <TextBox Height="23" HorizontalAlignment="Left" Name="textBox2" VerticalAlignment="Top" Width="120" /> <TextBox Height="23" HorizontalAlignment="Left" Name="textBox3" VerticalAlignment="Top" Width="120" /> <TextBlock Text="Resultado:"></TextBlock> <TextBox Height="23" HorizontalAlignment="Left" Name="textBoxResult" VerticalAlignment="Top" Width="120" > <TextBox.Text> <MultiBinding Converter="{StaticResource SumConverter}"> <Binding ElementName="textBox1" Path="Text" /> <Binding ElementName="textBox2" Path="Text" /> <Binding ElementName="textBox3" Path="Text" /> </MultiBinding> </TextBox.Text> </TextBox> </StackPanel>
codigo c#:
/// <summary> /// Clase conversora para sumar multiples valores enlazados /// </summary> public class SumConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { try { // sumar todos los valores (haciendo un cast a decimal, puede usarse cualquier otro valor mas adecuado) return values.Sum((item) => System.Convert.ToDecimal(item)).ToString(); } catch (Exception) { // retornar 0 en caso de error return "0"; } } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }
En el codigo xaml he puesto un miltibinding y esta clase es la que define el comportamiento, el cual suma todos los valores, como puedes ver, puedes añadir tantos textbox como quieras y seran todos sumados, en el ejemplo he puesto 3 pero pueden ser mas o menos.
Saludos
David González
MCP, MCTS
Visita mi Blog en: http://www.dgzornoza.com/- Propuesto como respuesta CorsarioVasco miércoles, 2 de mayo de 2012 7:21
- Marcado como respuesta ciberastro viernes, 4 de mayo de 2012 13:29
Todas las respuestas
-
¡Hola!
¿Puedes decir que dato quieres mostrar en el TextBox?, En principio sólo debes de extraer del contexto mediante una select y con los criterios de búsqueda (where) el dato a mostrar en el textbox.
Respecto a la segunda pregunta te agradecería que la desarrollaras un poco más porque no llego a intuir lo que deseas realizar. No la has construido correctamente y es complicado entenderte.
Un saludo,
-
¡Hola!
¿Puedes decir que dato quieres mostrar en el TextBox?, En principio sólo debes de extraer del contexto mediante una select y con los criterios de búsqueda (where) el dato a mostrar en el textbox.
Respecto a la segunda pregunta te agradecería que la desarrollaras un poco más porque no llego a intuir lo que deseas realizar. No la has construido correctamente y es complicado entenderte.
Un saludo,
gracias me la primer pregunta ya la solucione por mi cuenta a partir de este ejemplo:
lo desarrole viendo un viseotutorial
public static class Admin { #region Student public static void UpdateStudent(Student student) { using (SchoolDataDataContext data = new SchoolDataDataContext()) { Student stu = (from s in data.Student where s.StudentID == student.StudentID select s).FirstOrDefault(); stu.FirstName = student.FirstName; stu.LastName = student.LastName; stu.Gender = student.Gender; stu.GPA = student.GPA; data.SubmitChanges(); } } #endregion } public partial class UpdateStudent : Window { private Student student; public UpdateStudent(Student student) { InitializeComponent(); this.student = student; } private void Window_Loaded(object sender, RoutedEventArgs e) { texFirstName.Text = student.FirstName.Trim(); texLastName.Text = student.LastName.Trim(); if (student.Gender == "M") { radioMale.IsChecked = true; } else { radioFemale.IsChecked = true; } texGPA.Text = student.GPA.ToString(); }
la segunda pregunta es asi:
tengo un formulario con 3 texbox, los dos primeros reciben solo valores numericos, y el tercero debe llenarse automaticamente con la suma de los 2 primeros asi:
----------------------
texbox1=4
texbox2=5
texbox3=9
---------------------
texbox1="vacio"
texbox2=5
texbox3=5
---------------------
como lo hago, teniendo en cuenta que debe hacerlo en ejecucion y sin botones, osea debe ser automaticamente
-
Hola ciberastro.
Para hacer lo que quieres, la posible mejor opcion es realizar un multibinding (Solo si usas WPF, para silverlight tienes que hacer algo parecido ya que no esta disponible esta caracteristica).
para ello pongo un ejemplo:
codigo xaml:
<Window.Resources> <my:SumConverter x:Key="SumConverter" /> </Window.Resources> <StackPanel> <TextBlock Text="Numeros a sumar:"></TextBlock> <TextBox Height="23" HorizontalAlignment="Left" Name="textBox1" VerticalAlignment="Top" Width="120" /> <TextBox Height="23" HorizontalAlignment="Left" Name="textBox2" VerticalAlignment="Top" Width="120" /> <TextBox Height="23" HorizontalAlignment="Left" Name="textBox3" VerticalAlignment="Top" Width="120" /> <TextBlock Text="Resultado:"></TextBlock> <TextBox Height="23" HorizontalAlignment="Left" Name="textBoxResult" VerticalAlignment="Top" Width="120" > <TextBox.Text> <MultiBinding Converter="{StaticResource SumConverter}"> <Binding ElementName="textBox1" Path="Text" /> <Binding ElementName="textBox2" Path="Text" /> <Binding ElementName="textBox3" Path="Text" /> </MultiBinding> </TextBox.Text> </TextBox> </StackPanel>
codigo c#:
/// <summary> /// Clase conversora para sumar multiples valores enlazados /// </summary> public class SumConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { try { // sumar todos los valores (haciendo un cast a decimal, puede usarse cualquier otro valor mas adecuado) return values.Sum((item) => System.Convert.ToDecimal(item)).ToString(); } catch (Exception) { // retornar 0 en caso de error return "0"; } } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }
En el codigo xaml he puesto un miltibinding y esta clase es la que define el comportamiento, el cual suma todos los valores, como puedes ver, puedes añadir tantos textbox como quieras y seran todos sumados, en el ejemplo he puesto 3 pero pueden ser mas o menos.
Saludos
David González
MCP, MCTS
Visita mi Blog en: http://www.dgzornoza.com/- Propuesto como respuesta CorsarioVasco miércoles, 2 de mayo de 2012 7:21
- Marcado como respuesta ciberastro viernes, 4 de mayo de 2012 13:29
-
Para Silverlight te aconsejo la lectura de este interesante artículo:http://www.codeproject.com/Articles/286171/MultiBinding-in-Silverlight-5