DataGridView BindingSource BindNavigator

代码
private void button1_Click(object sender, EventArgs e)
{
bindingNavigator1.BindingSource
= bindingSource1;
LoadData();
}

private void LoadData()
{
// The xml to bind to.
string xml = @"<US><states>"
+ @"<state><name>Washington</name><capital>Olympia</capital></state>"
+ @"<state><name>Oregon</name><capital>Salem</capital></state>"
+ @"<state><name>California</name><capital>Sacramento</capital></state>"
+ @"<state><name>Nevada</name><capital>Carson City</capital></state>"
+ @"</states></US>";

// Convert the xml string to bytes and load into a memory stream.
byte[] xmlBytes = Encoding.UTF8.GetBytes(xml);
MemoryStream stream
= new MemoryStream(xmlBytes, false);

// Create a DataSet and load the xml into it.
DataSet set = new DataSet();
set.ReadXml(stream);

// Set the DataSource to the DataSet, and the DataMember
// to state.
bindingSource1.DataSource = set;
bindingSource1.DataMember
= "state";


textBox1.DataBindings.Add(
"Text", bindingSource1, "name");
textBox2.DataBindings.Add(
"Text", bindingSource1, "capital");

}


//------------------------------------------------------


//DataGridView BindingSource绑定更新示例.txt.cs
//根据selectCommand生成增、删、改 命令 SqlCommandBuilder

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

public class Form1 : System.Windows.Forms.Form
{
private DataGridView dataGridView1 = new DataGridView();
private BindingSource bindingSource1 = new BindingSource();
private SqlDataAdapter dataAdapter = new SqlDataAdapter();
private Button reloadButton = new Button();
private Button submitButton = new Button();

[STAThreadAttribute()]
public static void Main()
{
Application.Run(
new Form1());
}

// Initialize the form.
public Form1()
{
dataGridView1.Dock
= DockStyle.Fill;

reloadButton.Text
= "reload";
submitButton.Text
= "submit";
reloadButton.Click
+= new System.EventHandler(reloadButton_Click);
submitButton.Click
+= new System.EventHandler(submitButton_Click);

FlowLayoutPanel panel
= new FlowLayoutPanel();
panel.Dock
= DockStyle.Top;
panel.AutoSize
= true;
panel.Controls.AddRange(
new Control[] { reloadButton, submitButton });

this.Controls.AddRange(new Control[] { dataGridView1, panel });
this.Load += new System.EventHandler(Form1_Load);
this.Text = "DataGridView databinding and updating demo";

//处理数据异常事件
this.dataGridView1.DataError += new DataGridViewDataErrorEventHandler(dataGridView1_DataError);

}

void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
MessageBox.Show(e.Exception.Message);
e.Cancel
= true;
}

private void Form1_Load(object sender, System.EventArgs e)
{
// Bind the DataGridView to the BindingSource
// and load the data from the database.
dataGridView1.DataSource = bindingSource1;
GetData(
"select * from tuser");
}

private void reloadButton_Click(object sender, System.EventArgs e)
{
// Reload the data from the database.
GetData(dataAdapter.SelectCommand.CommandText);
}

private void submitButton_Click(object sender, System.EventArgs e)
{
// Update the database with the user's changes.
dataAdapter.Update((DataTable)bindingSource1.DataSource);
}

private void GetData(string selectCommand)
{
try
{
// Specify a connection string. Replace the given value with a
// valid connection string for a Northwind SQL Server sample
// database accessible to your system.
String connectionString =
"Integrated Security=SSPI;Persist Security Info=False;" +
@"Initial Catalog=Migrate;Data Source=.\SQLSERVER2005";

// Create a new data adapter based on the specified query.
dataAdapter = new SqlDataAdapter(selectCommand, connectionString);

// Create a command builder to generate SQL update, insert, and
// delete commands based on selectCommand. These are used to
// update the database.
//根据selectCommand生成增、删、改 命令
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

// Populate a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
table.Locale
= System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource
= table;

// Resize the DataGridView columns to fit the newly loaded content.
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
//隐藏ID列
this.dataGridView1.Columns[0].Visible = false;
}
catch (SqlException)
{
MessageBox.Show(
"To run this example, replace the value of the " +
"connectionString variable with a connection string that is " +
"valid for your system.");
}
}

}

//------------------------------------------------------------------

//dataGridView1_CellFormatting
// if (Int32.TryParse((String)e.Value, out intValue) &&
// (intValue < 0))
//经典转换

using System;
using System.Drawing;
using System.Windows.Forms;

namespace ns2
{
public class Form1 : Form
{
private DataGridView dataGridView1 = new DataGridView();
private Bitmap highPriImage;
private Bitmap mediumPriImage;
private Bitmap lowPriImage;

public Form1()
{
// Initialize the images.
try
{
highPriImage
= new Bitmap("red.bmp");
mediumPriImage
= new Bitmap("green.bmp");
lowPriImage
= new Bitmap("brown.bmp");
}
catch (ArgumentException)
{
MessageBox.Show(
"The Priority column requires Bitmap images " +
"named highPri.bmp, mediumPri.bmp, and lowPri.bmp " +
"residing in the same directory as the executable file.");
}

// Initialize the DataGridView.
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.AllowUserToAddRows
= false;
dataGridView1.Columns.AddRange(
new DataGridViewTextBoxColumn(),
new DataGridViewImageColumn());
dataGridView1.Columns[
0].Name = "Balance";
dataGridView1.Columns[
1].Name = "Priority";
dataGridView1.Rows.Add(
"-100", "high");
dataGridView1.Rows.Add(
"0", "medium");
dataGridView1.Rows.Add(
"100", "low");
dataGridView1.CellFormatting
+=
new System.Windows.Forms.DataGridViewCellFormattingEventHandler(
this.dataGridView1_CellFormatting);
this.Controls.Add(dataGridView1);
}

// Changes how cells are displayed depending on their columns and values.
private void dataGridView1_CellFormatting(object sender,
System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
// Set the background to red for negative values in the Balance column.
if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("Balance"))
{
Int32 intValue;
if (Int32.TryParse((String)e.Value, out intValue) &&
(intValue
< 0))
{
e.CellStyle.BackColor
= Color.Red;
e.CellStyle.SelectionBackColor
= Color.DarkRed;
}
}

// Replace string values in the Priority column with images.
if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("Priority"))
{
// Ensure that the value is a string.
String stringValue = e.Value as string;
if (stringValue == null) return;

// Set the cell ToolTip to the text value.
DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
cell.ToolTipText
= stringValue;

// Replace the string value with the image value.
switch (stringValue)
{
case "high":
e.Value
= highPriImage;
break;
case "medium":
e.Value
= mediumPriImage;
break;
case "low":
e.Value
= lowPriImage;
break;
}
}
}

public static void Main()
{
Application.Run(
new Form1());
}

}
}
原文地址:https://www.cnblogs.com/wucg/p/1758863.html