Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Thursday, October 16, 2014 8:22 PM
Hi All,
Thanks for reading this post. The problem I have is that I need to display an item in a second array from a selection made
from a combobox containing a array of text items.
Here is my code so far:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace combox2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string[] Cereal = new string[] { "All Bran (UK/Aus)" , "All Bran(US)", "Oat Bran" , "Rolled Oats" , "Special K(UK/Aus)" , "Natural Muesli" , "Porridge" , "Bran Buds" , "Mini Wheats" , "Nutrigrain" , "Shredded Wheat" , "Porridge Oats" , "Special K(US)" , "Cornflakes" , "Sultana Bran" , "Branflakes" , "Coco Pops" , "Puffed Wheat" , "Oats in Honey Bake" , "Team" , "Total" , "Cheerios" , "Rice Krispies" , "Weetabix" };
int[] CerealGI = new int[] { 30, 50, 50, 51, 54, 40, 58, 58, 58, 66, 67, 63, 69, 80, 73, 74, 77, 80, 77, 82, 76, 74, 82, 74, };
ComboBox1.ItemsSource = Cereal;
}
private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int selectedIndex = ComboBox1.SelectedIndex;
Object selectedItem = ComboBox1.SelectedItem;
MessageBox.Show( "You Selected:- " + selectedItem.ToString() + "\n" + selectedIndex.ToString());
When run the user is presented with comboBox and can make a selection of items.
What I require is using selectedIndex to select the corresponding number from the CerealGI array.
So if I select "Oat Bran" I need to display the third number in CerealGI array (50).
If I select a different item (Porridge) I would get a different number (58) and so on.
This result would then be displayed by MessageBox.Show();
Any help would be gratefully received.
Thanks in advance.
All replies (3)
Thursday, October 16, 2014 9:45 PM âś…Answered | 1 vote
Did you try
MessageBox.Show("You Selected:- " + selectedItem.ToString() + "\n" + CerealGI[selectedIndex].ToString());
Also modified your code to work ..
public partial class MainWindow : Window
{
string[] Cereal = new string[] { "All Bran (UK/Aus)", "All Bran(US)", "Oat Bran", "Rolled Oats", "Special K(UK/Aus)", "Natural Muesli", "Porridge", "Bran Buds", "Mini Wheats", "Nutrigrain", "Shredded Wheat", "Porridge Oats", "Special K(US)", "Cornflakes", "Sultana Bran", "Branflakes", "Coco Pops", "Puffed Wheat", "Oats in Honey Bake", "Team", "Total", "Cheerios", "Rice Krispies", "Weetabix" };
int[] CerealGI = new int[] { 30, 50, 50, 51, 54, 40, 58, 58, 58, 66, 67, 63, 69, 80, 73, 74, 77, 80, 77, 82, 76, 74, 82, 74, };
public MainWindow()
{
InitializeComponent();
comboBox1.ItemsSource = Cereal;
}
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;
MessageBox.Show("You Selected:- " + selectedItem.ToString() + "\n" + CerealGI[selectedIndex].ToString());
}
}
Thursday, October 16, 2014 9:43 PM
Hello,
I would suggest using a BindingSource as shown below
public partial class Form1 : Form
{
private int[] CerealGI = new int[]
{
30, 50, 50, 51, 54, 40, 58, 58, 58,
66, 67, 63, 69, 80, 73, 74, 77,
80, 77, 82, 76, 74, 82, 74,
};
private BindingSource bs = new BindingSource();
public Form1()
{
InitializeComponent();
bs.PositionChanged += bs_PositionChanged;
}
private void Form1_Load(object sender, EventArgs e)
{
string[] Cereal = new string[]
{
"All Bran (UK/Aus)", "All Bran(US)", "Oat Bran",
"Rolled Oats", "Special K(UK/Aus)", "Natural Muesli",
"Porridge", "Bran Buds", "Mini Wheats", "Nutrigrain",
"Shredded Wheat", "Porridge Oats", "Special K(US)",
"Cornflakes", "Sultana Bran", "Branflakes", "Coco Pops",
"Puffed Wheat", "Oats in Honey Bake", "Team", "Total",
"Cheerios", "Rice Krispies", "Weetabix"
};
bs.DataSource = Cereal;
comboBox1.DataSource = bs;
}
private void cmdGetData_Click(object sender, EventArgs e)
{
MessageBox.Show(CerealGI[bs.Position].ToString());
}
}
using (OleDbConnection cn = new OleDbConnection { ConnectionString = ""TODO })
{
cn.Open();
using (OleDbCommand cmd = new OleDbCommand { CommandText = "TODO", Connection = cn })
{
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
// do what we came to do
}
}
else
{
Console.WriteLine("No rows!!!");
}
}
}
public static class DataGridViewMethods
{
public static List<DataGridViewRow> GetChecked(this DataGridView GridView, string ColumnName)
{
return (
from Rows in GridView.Rows.Cast<DataGridViewRow>()
where Convert.ToBoolean(Rows.Cells[ColumnName].Value) == true
select Rows).ToList();
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
pictureBox1.Click += pictureBox1_Click;
}
void pictureBox1_Click(object sender, EventArgs e)
{
button1.PerformClick();
this.ActiveControl = button1;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello");
}
}
foreach (var tb in TextboxList)
{
tb.Text = "";
}
using System;
using System.Windows.Forms;
namespace Demo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
deceasedBindingSource.Add(
new Deceased
{
FirstName = "Jane",
Phone1 = "555-333-1234",
BirthDate = new DateTime(1987, 3, 1)
}
);
deceasedBindingSource.Add(
new Deceased
{
FirstName = "Mary",
Phone1 = "444-666-8888",
BirthDate = new DateTime(1990, 5, 7)
}
);
}
}
}
string items = "D.R.`Dr.,D R`D-R-`D,R,";
string FieldName = "Your field name";
string Temp = string.Join(" ", ( from T in items.Split('`') select FieldName + " like '%" + T + "%' OR ").ToArray());
int LastIndex = Temp.LastIndexOf(" OR");
string result = Temp.Substring(0, LastIndex);
Console.WriteLine("[{0}]", result);
<a href="http://redpanel.bugged.ro/profile/SoFt"><img src="http://redpanel.bugged.ro/userbar/SoFt" alt="profilul lui SoFt pe serverul bugged.ro" /></a>
string myNumer = "1";
textBox1.Text = myNumer.PadLeft(5, '0');
List<string> Items = Enumerable.Range(1, 101)
.Select((item) => item.ToString()
.PadLeft(5,'0')).ToList();
foreach (string item in Items)
{
Console.WriteLine("[{0}]", item);
}
public partial class Form1 : Form
{
private BindingSource bs = new BindingSource();
private OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
Builder.Provider = "Microsoft.ACE.OLEDB.12.0";
Builder.DataSource = Path.Combine(Application.StartupPath, "Database1.accdb");
using (OleDbConnection cn = new OleDbConnection { ConnectionString = Builder.ToString() })
{
using (OleDbCommand cmd = new OleDbCommand
{
CommandText = "SELECT Identifier, UserName, UserRole FROM Users",
Connection = cn
})
{
cn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
dt.Load(dr);
}
}
bs.DataSource = dt;
DataGridView1.DataSource = bs;
DataGridView1.CellValidating += DataGridView1_CellValidating;
DataTable dtClone = dt.Copy();
dtClone.Columns.Remove("Identifier");
multiColumnCombo1.DisplayMember = "UserName";
multiColumnCombo1.ColumnWidths = "50;100";
multiColumnCombo1.DataSource = dtClone;
}
}
http://tech.pro/tutorial/1266/advanced-programming-with-c
DataTable dt = new DataTable();
using (OleDbConnection cn = new OleDbConnection { ConnectionString = "Your connection string" })
{
using (OleDbCommand cmd = new OleDbCommand
{
CommandText = "SELECT Identifier, UserName, UserRole FROM Users",
Connection = cn
})
{
cn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
dt.Load(dr);
}
}
bs.DataSource = dt;
DataGridView1.DataSource = bs;
public DataTable SimpleExample()
{
string ConnectionString = "datasource=xxxxxxxxx;DefaultCollection=yyyyyyyy;";
DataTable dtProducts = new DataTable();
using (iDB2Connection cn = new iDB2Connection(ConnectionString))
{
using (iDB2Command cmd = new iDB2Command
{
Connection = cn,
CommandText = @"
SELECT
productid As Identifier,
productname As Product
FROM products
ORDER BY productname"
}
)
{
cn.Open();
dtProducts.Load(cmd.ExecuteReader());
}
}
return dtProducts;
}
BindingSource bs = new BindingSource();
private void button1_Click(object sender, EventArgs e)
{
bs.DataSource = SimpleExample();
bs.Sort = "Product";
dataGridView1.DataSource = bs;
}
public partial class Form1 : Form
{
public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using (OleDbConnection cn = new OleDbConnection { ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb" })
{
using (OleDbCommand cmd = new OleDbCommand
{
CommandText = "SELECT Identifier, UserName, UserRole FROM Users ORDER BY UserName",
Connection = cn
})
{
cn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
dt.Load(dr);
}
}
DataGridView1.DataSource = dt;
}
}
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.ApplicationServices;
using Microsoft.VisualBasic.CompilerServices;
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using WindowsApplication1;
namespace WindowsApplication1.My
{
[GeneratedCode("MyTemplate", "10.0.0.0")]
[HideModuleName]
[StandardModule]
internal sealed class MyProject
{
private readonly static MyProject.ThreadSafeObjectProvider<MyApplication> m_AppObjectProvider;
private readonly static MyProject.ThreadSafeObjectProvider<MyComputer> m_ComputerObjectProvider;
private static MyProject.ThreadSafeObjectProvider<MyProject.MyForms> m_MyFormsObjectProvider;
private readonly static MyProject.ThreadSafeObjectProvider<MyProject.MyWebServices> m_MyWebServicesObjectProvider;
private readonly static MyProject.ThreadSafeObjectProvider<User> m_UserObjectProvider;
[HelpKeyword("My.Application")]
internal static MyApplication Application
{
[DebuggerHidden]
get
{
return MyProject.m_AppObjectProvider.GetInstance;
}
}
[HelpKeyword("My.Computer")]
internal static MyComputer Computer
{
[DebuggerHidden]
get
{
return MyProject.m_ComputerObjectProvider.GetInstance;
}
}
[HelpKeyword("My.Forms")]
internal static MyProject.MyForms Forms
{
[DebuggerHidden]
get
{
return MyProject.m_MyFormsObjectProvider.GetInstance;
}
}
[HelpKeyword("My.User")]
internal static User User
{
[DebuggerHidden]
get
{
return MyProject.m_UserObjectProvider.GetInstance;
}
}
[HelpKeyword("My.WebServices")]
internal static MyProject.MyWebServices WebServices
{
[DebuggerHidden]
get
{
return MyProject.m_MyWebServicesObjectProvider.GetInstance;
}
}
static MyProject()
{
MyProject.m_ComputerObjectProvider = new MyProject.ThreadSafeObjectProvider<MyComputer>();
MyProject.m_AppObjectProvider = new MyProject.ThreadSafeObjectProvider<MyApplication>();
MyProject.m_UserObjectProvider = new MyProject.ThreadSafeObjectProvider<User>();
MyProject.m_MyFormsObjectProvider = new MyProject.ThreadSafeObjectProvider<MyProject.MyForms>();
MyProject.m_MyWebServicesObjectProvider = new MyProject.ThreadSafeObjectProvider<MyProject.MyWebServices>();
}
[EditorBrowsable(EditorBrowsableState.Never)]
[MyGroupCollection("System.Windows.Forms.Form", "Create__Instance__", "Dispose__Instance__", "My.MyProject.Forms")]
internal sealed class MyForms
{
public Form1 m_Form1;
[ThreadStatic]
private static Hashtable m_FormBeingCreated;
public Form1 Form1
{
get
{
this.m_Form1 = MyProject.MyForms.Create__Instance__<Form1>(this.m_Form1);
return this.m_Form1;
}
set
{
if (Value != this.m_Form1)
{
if (Value == null)
{
this.Form1(ref this.m_Form1);
return;
}
else
{
throw new ArgumentException("Property can only be set to Nothing");
}
}
else
{
return;
}
}
}
[DebuggerHidden]
[EditorBrowsable(EditorBrowsableState.Never)]
public MyForms()
{
}
[DebuggerHidden]
private static Form1 Create__Instance__<T>(T Instance)
{
T t;
TargetInvocationException targetInvocationException = null;
if (Instance == null || Instance.IsDisposed)
{
if (MyProject.MyForms.m_FormBeingCreated == null)
{
MyProject.MyForms.m_FormBeingCreated = new Hashtable();
}
else
{
if (MyProject.MyForms.m_FormBeingCreated.ContainsKey(typeof(T)))
{
throw new InvalidOperationException(Utils.GetResourceString("WinForms_RecursiveFormCreate", new string[0]));
}
}
MyProject.MyForms.m_FormBeingCreated.Add(typeof(T), null);
try
{
try
{
t = Activator.CreateInstance<T>();
}
catch(DebuggerHidden)
private void Dispose__Instance__<T>{ref T instance}
{
instance.Dispose();
T t = default(T);
instance = t;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object o)
{
return this.Equals(RuntimeHelpers.GetObjectValue(o));
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return this.GetHashCode();
}
[EditorBrowsable(EditorBrowsableState.Never)]
internal Type GetType()
{
return typeof(MyForms);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString()
{
return this.ToString();
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
[MyGroupCollection("System.Web.Services.Protocols.SoapHttpClientProtocol", "Create__Instance__", "Dispose__Instance__", "")]
internal sealed class MyWebServices
{
[DebuggerHidden]
[EditorBrowsable(EditorBrowsableState.Never)]
public MyWebServices()
{
}
[DebuggerHidden]
private static T Create__Instance__<T>(T instance)
{
if (instance != null)
{
return instance;
}
else
{
return Activator.CreateInstance<T>();
}
}
[DebuggerHidden]
private void Dispose__Instance__<T>(ref T instance)
{
T t = default(T);
instance = t;
}
[DebuggerHidden]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object o)
{
return this.Equals(RuntimeHelpers.GetObjectValue(o));
}
[DebuggerHidden]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return this.GetHashCode();
}
[DebuggerHidden]
[EditorBrowsable(EditorBrowsableState.Never)]
internal Type GetType()
{
return typeof(MyWebServices);
}
[DebuggerHidden]
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString()
{
return this.ToString();
}
}
[ComVisible(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
internal sealed class ThreadSafeObjectProvider<T>
{
internal T GetInstance
{
[DebuggerHidden]
get
{
if (MyProject.ThreadSafeObjectProvider<T>.m_ThreadStaticValue == null)
{
MyProject.ThreadSafeObjectProvider<T>.m_ThreadStaticValue = Activator.CreateInstance<T>();
}
return MyProject.ThreadSafeObjectProvider<T>.m_ThreadStaticValue;
}
}
[DebuggerHidden]
[EditorBrowsable(EditorBrowsableState.Never)]
public ThreadSafeObjectProvider()
{
}
}
}
}
/// <summary>
/// Search for a variable field name containing an value
/// where we search on lowercase.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cmdSimpleFind_Click(object sender, EventArgs e)
{
string FieldName = "UserName";
string SearchFor = "bill";
DataTable dt = (DataTable)DataGridView1.DataSource;
var Result = (
from T in dt.AsEnumerable()
where T[FieldName].ToString().ToLower().Equals(SearchFor)
select T).FirstOrDefault();
if (Result != null)
{
MessageBox.Show(string.Join(",", Result.ItemArray));
}
else
{
MessageBox.Show(string.Format("Failed to locate {0} in {1}", SearchFor, FieldName));
}
}
<System.Diagnostics.DebuggerStepThrough()> _
<Runtime.CompilerServices.Extension()> _
Public Function ExportRows(ByVal sender As DataGridView) As String()
Dim DashLine As String = Environment.NewLine & New String("-"c, 50)
Return _
(
From row In sender.Rows.OfType(Of DataGridViewRow)()
Where Not DirectCast(row, DataGridViewRow).IsNewRow
Let RowItem = String.Join(Environment.NewLine,
Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, _
Function(c As DataGridViewCell)
Dim ColName As String = sender.Columns(c.ColumnIndex).Name
Return ColName & ": " & If(c.Value Is Nothing, "", c.Value.ToString)
End Function)) & DashLine
Select RowItem).ToArray
End Function
<Runtime.CompilerServices.Extension()> _
Public Function ExportRows(ByVal sender As DataTable) As String()
Dim DashLine As String = New String("-"c, 50)
Dim sb As New System.Text.StringBuilder
Return (From row In sender.Rows.OfType(Of DataRow).Select( _
Function(item)
sb.Length = 0
For Each col As DataColumn In sender.Columns
If Not col.ColumnMapping = MappingType.Hidden Then
sb.AppendLine(String.Format("{0}: {1}", col.ColumnName,
If(IsDBNull(item.Item(col.ColumnName)),
"",
item.Item(col.ColumnName))))
End If
Next
Return sb.ToString & DashLine
End Function)).ToArray
End Function
private void button1_Click(object sender, EventArgs e)
{
DataGridViewRow test =
(
from T in dataGridView1.Rows.OfType<DataGridViewRow>()
where !T.IsNewRow && T.Cells["Column1"].Value.ToString().ToLower() == textBox1.Text.ToLower()
select T
).FirstOrDefault();
if (test == null)
{
dataGridView1.Rows.Add(new object[] { textBox1.Text });
}
else
{
dataGridView1.CurrentCell = dataGridView1[0, test.Index];
MessageBox.Show("Name exists already");
}
}
/// <summary>
/// The code accepts an Excel file to open, iterates thru the
/// WorkSheets collection checking the name passed in parameter 2
/// to see if it matches and if so sets a boolean so after the for-next
/// we can know if the sheet is there and safe to work on.
/// </summary>
/// <param name="FileName"></param>
/// <param name="SheetName"></param>
public void OpenExcel(string FileName, string SheetName)
{
List<string> SheetNames = new List<string>();
bool Proceed = false;
Excel.Application xlApp = null;
Excel.Workbooks xlWorkBooks = null;
Excel.Workbook xlWorkBook = null;
Excel.Worksheet xlWorkSheet = null;
Excel.Sheets xlWorkSheets = null;
xlApp = new Excel.Application();
xlApp.DisplayAlerts = false;
xlWorkBooks = xlApp.Workbooks;
xlWorkBook = xlWorkBooks.Open(FileName);
xlApp.Visible = false;
xlWorkSheets = xlWorkBook.Sheets;
for (int x = 1; x <= xlWorkSheets.Count; x++)
{
xlWorkSheet = (Excel.Worksheet)xlWorkSheets[x];
SheetNames.Add(xlWorkSheet.Name);
if (xlWorkSheet.Name == SheetName)
{
Proceed = true;
break;
}
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet);
xlWorkSheet = null;
}
xlWorkBook.Close();
xlApp.Quit();
ReleaseComObject(xlWorkSheets);
ReleaseComObject(xlWorkSheet);
ReleaseComObject(xlWorkBook);
ReleaseComObject(xlWorkBooks);
ReleaseComObject(xlApp);
if (Proceed)
{
MessageBox.Show("Found sheet, do your work here.");
}
else
{
MessageBox.Show("Sheet not located");
}
MessageBox.Show("Sheets available \n" + String.Join("\n", SheetNames.ToArray()));
}
private void ReleaseComObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
}
}
public static void ExportRows(this DataGridView sender, string fileName)
{
if (sender.RowCount > 0)
{
var sb = new StringBuilder();
var headers = sender.Columns.Cast<DataGridViewColumn>();
sb.AppendLine(string.Join("\t", headers.Select(column => column.HeaderText )));
foreach (DataGridViewRow row in sender.Rows)
{
if (!row.IsNewRow == true)
{
var cells = row.Cells.Cast<DataGridViewCell>();
sb.AppendLine(string.Join("\t", cells.Select(cell => cell.Value)));
}
}
System.IO.File.WriteAllText(fileName,sb.ToString());
}
else
{
// decide what to do here
}
}
public void DemoGetChanges()
{
DataTable dtChanges = new DataTable();
DataTable dt = new DataTable { TableName = "MyTable" };
dt.Columns.Add(new DataColumn { ColumnName = "Identifier", DataType = typeof(Int32),
AutoIncrement = true, AutoIncrementSeed = 1 });
dt.Columns.Add(new DataColumn { ColumnName = "LastName", DataType = typeof(string) });
dt.Columns.Add(new DataColumn { ColumnName = "Amount", DataType = typeof(decimal) });
dt.Rows.Add(new object[] { null, "Jones", 5.5M });
dtChanges = dt.GetChanges(DataRowState.Added);
if (dtChanges != null)
{
Console.WriteLine("Insert these rows");
foreach (DataRow row in dtChanges.Rows)
{
Console.WriteLine(string.Join(",", row.ItemArray));
}
}
else
{
Console.WriteLine("Nothing added");
}
dt.AcceptChanges();
dt.Rows[0].SetField<decimal>("Amount", 10.99M);
dtChanges = dt.GetChanges(DataRowState.Added);
Console.WriteLine();
if (dtChanges != null)
{
Console.WriteLine("Insert these rows");
foreach (DataRow row in dtChanges.Rows)
{
Console.WriteLine(string.Join(",", row.ItemArray));
}
}
else
{
Console.WriteLine("Nothing to insert");
}
Console.WriteLine();
dt.Rows.Add(new object[] { null, "Smith", 15.5M });
dt.Rows.Add(new object[] { null, "Adams", 1M });
dtChanges = dt.GetChanges(DataRowState.Added);
if (dtChanges != null)
{
Console.WriteLine("Insert these rows");
foreach (DataRow row in dtChanges.Rows)
{
Console.WriteLine(string.Join(",", row.ItemArray));
}
}
else
{
Console.WriteLine("Nothing to insert");
}
}
<script type="text/javascript">
"use strict";
function button1Click(mouseEvent)
{
if (typeof console == "undefined")
{
window.console =
{
log: function () { }
};
}
console.log("Log something");
}
</script>
<p>
<input id="Button1" type="button" value="button" onclick=button1Click() />
</p>
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
e.SuppressKeyPress = true;
SelectNextControl(textBox1, true, true, true, true);
}
}
============================
if (dt.Rows.Count > 7)
{
DataTable dt1 = (from T in dt.AsEnumerable() select T).Skip(8).CopyToDataTable();
DataGridView1.DataSource = dt1;
}
else
{
DataGridView1.DataSource = dt;
}
System.IO.File.WriteAllText("MyData.txt", results);
Dim MachineName As String = "Some_PC_Name" '<<< Put the PC name or IP here that you want to connect to
Dim Admins As New DirectoryEntry("WinNT://" & MachineName & "/Administrators") 'Connect to machine
Dim Members As Object = Admins.Invoke("Members", Nothing) 'Get members
For Each Member As Object In CType(Members, IEnumerable) 'loop through members
Dim CurrentMember As New DirectoryEntry(Member) 'Get directoryentry for user
MessageBox.Show(CurrentMember.Name) 'Show the user's name in a messagebox
Next
public static string ExportRows(this DataGridView sender)
{
if (sender.RowCount > 0)
{
var sb = new StringBuilder();
var headers = sender.Columns.Cast<DataGridViewColumn>();
sb.AppendLine(string.Join(",", headers.Select(column => "\"" + column.HeaderText + "\"")));
foreach (DataGridViewRow row in sender.Rows)
{
var cells = row.Cells.Cast<DataGridViewCell>();
sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"")));
}
return sb.ToString();
}
else
{
return "";
}
}
Private Sub parentAdapter_RowUpdated(sender As Object, e As OleDbRowUpdatedEventArgs)
'We are only interested in new records.
If e.StatementType = StatementType.Insert Then
'Get the last ID auto-generated by the database.
Dim lastAutoNumber = Me.parentAdapter.GetLastAutoNumber().Value
'Update the ID of the local row.
DirectCast(e.Row, ParentChildDataSet.ParentRow).ParentID = lastAutoNumber
End If
End Sub
Private ReadOnly imageA As Image = My.Resources.Car_A
Private ReadOnly imageB As Image = My.Resources.Car_B
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.PictureBox1.Image = Me.imageA
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
If Me.PictureBox1.Image Is Me.imageA Then
Me.PictureBox1.Image = Me.imageB
Else
Me.PictureBox1.Image = Me.imageA
End If
End Sub
Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
Me.imageA.Dispose()
Me.imageB.Dispose()
End Sub
private void cmdChangeFirstName_Click(object sender, EventArgs e)
{
if (bsData.DataSource != null)
{
bsData.CurrentRow().SetField<string>("FirstNameColumn", txtFirstName.Text);
Console.WriteLine("", bsData.CurrentRow().Field<int>("Identifier"), bsData.CurrentRow().Field<string>("FirstNameColumn"));
}
else
{
MessageBox.Show("bsData.DataSource has not be set.") ;
}
}
public partial class frmDemo : Form
{
public frmForm2()
{
InitializeComponent();
bsData.PositionChanged += new EventHandler(this.bsData_PositionChanged);
dataGridView1.DataError += new DataGridViewDataErrorEventHandler(this.dataGridView1_DataError1);
dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(this.dataGridView1_CellFormatting1);
}
private void button2_Click(object sender, EventArgs e)
{
List<String> NameList = new List<String>(new string[] {"Jane", "Bob", "Anne", "Mary", "bill", "Carol"}) ;
var Test = (from T in NameList where T.ToUpper().StartsWith("B") select T).ToList();
}
private void button3_Click(object sender, EventArgs e)
{
List<string> NameList = new List<string>() { "Jane", "Bob", "Anne", "Mary", "bill", "Carol" };
var Test = (from T in NameList where T.ToUpper().StartsWith("B") select T).ToList();
foreach (var Item in Test)
{
Console.WriteLine(Item);
}
}
private void button2_Click(object sender, EventArgs e)
{
List<String> NameList = new List<String>(new string[] {"Jane", "Bob", "Anne", "Mary", "bill", "Carol"}) ;
//List<String> Test = (from t in NameList let w = t.ToUpper from x in w select w).ToList;
//List<String> Test = from t in NameList let w = t.ToUpper select t;
string[] NameArray = NameList.ToArray();
var Test = NameArray.Select(p => p.ToUpper());
foreach (String v in Test)
{
Console.WriteLine(v);
}
//List<String> Result = (from TT in NameArray where TT.StartsWith("B") select TT );
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WorkingWithExtensionMethods;
namespace WorkingWithExtensionMethods.Forms
{
public partial class frmForm2 : Form
{
public frmForm2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Class2 c1 = new Class2(20) ;
}
private void button2_Click(object sender, EventArgs e)
{
List<String> NameList = new List<String>(new string[] {"Jane", "Bob", "Anne", "Mary", "bill", "Carol"}) ;
foreach (String FirstName in NameList)
{
Console.WriteLine(FirstName);
}
Console.WriteLine() ;
//List<String> Test = (from t in NameList let w = t.ToUpper from x in w select w).ToList;
//List<String> Test = from t in NameList let w = t.ToUpper select t;
string[] NameArray = NameList.ToArray();
List<String> Test = NameArray.Select(p => new { Upper = p.ToUpper() });
//List<String> Result = (from TT in NameArray where TT.StartsWith("B") select TT );
string[] strings =
{
"A penny saved is a penny earned.",
"The early bird catches the worm.",
"The pen is mightier than the sword."
};
// Split the sentence into an array of words
// and select those whose first letter is a vowel.
var earlyBirdQuery =
from sentence in strings
let words = sentence.Split(' ')
from word in words
let w = word.ToLower()
where w[0] == 'a' || w[0] == 'e'
|| w[0] == 'i' || w[0] == 'o'
|| w[0] == 'u'
select word;
// Execute the query.
foreach (var v in earlyBirdQuery)
{
Console.WriteLine("\"{0}\" starts with a vowel", v);
}
}
}
}
OverView:
This solutions for the moment is a playground to learn syntax differences between VB.NET and C in regards
to LINQ/Lambda but first stop is to create several language extensions first as they will be part of
the LINQ experience.
WorkingWithExtensionMethods
* Used to work with language extension methods
* Will serve as a base for LINQ/Lambda
MyAdditions
Is VB.NET - used to marry C and VB together
OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder();
Builder.Provider = "Microsoft.ACE.OLEDB.12.0";
Builder.DataSource = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb");
using (OleDbConnection cn = new OleDbConnection { ConnectionString = Builder.ConnectionString })
{
using (OleDbCommand cmd = new OleDbCommand { Connection = cn })
{
cn.Open();
cmd.CommandText = "INSERT INTO USERS (UserName,UserRole) VALUES ('Mary','Sales Agent')";
int Affected = Convert.ToInt32(cmd.ExecuteNonQuery());
Console.WriteLine("Inserted {0} row", Affected);
if (Affected == 1)
{
cmd.CommandText = "Select @@Identity";
long Identifier = Convert.ToInt64(cmd.ExecuteScalar());
Console.WriteLine("New identifier is {0}", Identifier);
}
}
}
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.
Thursday, October 16, 2014 9:44 PM
Try this example using a BindingSouirce
public partial class Form1 : Form
{
private int[] CerealGI = new int[]
{
30, 50, 50, 51, 54, 40, 58, 58, 58,
66, 67, 63, 69, 80, 73, 74, 77,
80, 77, 82, 76, 74, 82, 74,
};
private BindingSource bs = new BindingSource();
public Form1()
{
InitializeComponent();
bs.PositionChanged += bs_PositionChanged;
}
private void Form1_Load(object sender, EventArgs e)
{
string[] Cereal = new string[]
{
"All Bran (UK/Aus)", "All Bran(US)", "Oat Bran",
"Rolled Oats", "Special K(UK/Aus)", "Natural Muesli",
"Porridge", "Bran Buds", "Mini Wheats", "Nutrigrain",
"Shredded Wheat", "Porridge Oats", "Special K(US)",
"Cornflakes", "Sultana Bran", "Branflakes", "Coco Pops",
"Puffed Wheat", "Oats in Honey Bake", "Team", "Total",
"Cheerios", "Rice Krispies", "Weetabix"
};
bs.DataSource = Cereal;
comboBox1.DataSource = bs;
}
private void cmdGetData_Click(object sender, EventArgs e)
{
MessageBox.Show(CerealGI[bs.Position].ToString() );
}
}
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.