C# 使用OLEDB连接如何随机化单词
使用OLEDB连接,如何连接Access中包含20个单词的表,然后让它从表中随机选取一个单词并将其存储在表单的标签中C# 使用OLEDB连接如何随机化单词,c#,oledbconnection,C#,Oledbconnection,使用OLEDB连接,如何连接Access中包含20个单词的表,然后让它从表中随机选取一个单词并将其存储在表单的标签中 public partial class MainForm : Form { // Use this connection string if your database has the extension .accdb private const String access7ConnectionString = @"Provider=Micros
public partial class MainForm : Form
{
// Use this connection string if your database has the extension .accdb
private const String access7ConnectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\WordsDB.accdb";
// Data components
private OleDbConnection myConnection;
private DataTable myDataTable;
private OleDbDataAdapter myAdapter;
private OleDbCommandBuilder myCommandBuilder;
// Index of the current record
private int currentRecord = 0;
private void MainForm_Load(object sender, EventArgs e)
{
String command = "SELECT * FROM Words";
try
{
myConnection = new OleDbConnection(access7ConnectionString);
myAdapter = new OleDbDataAdapter(access7ConnectionString, myConnection);
myCommandBuilder = new OleDbCommandBuilder(myAdapter);
myDataTable = new DataTable();
FillDataTable(command);
DisplayRow(currentRecord);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void FillDataTable(String selectCommand)
{
try
{
myConnection.Open();
myAdapter.SelectCommand.CommandText = selectCommand;
// Fill the datatable with the rows reurned by the select command
myAdapter.Fill(myDataTable);
myConnection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error in FillDataTable : \r\n" + ex.Message);
}
}
private void DisplayRow(int rowIndex)
{
// Check that we can retrieve the given row
if (myDataTable.Rows.Count == 0)
return; // nothing to display
if (rowIndex >= myDataTable.Rows.Count)
return; // the index is out of range
// If we get this far then we can retrieve the data
try
{
DataRow row = myDataTable.Rows[rowIndex];
WordsLbl.Text = row["SpellingWords"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("Error in DisplayRow : \r\n" + ex.Message);
}
}
}
正如您所看到的,这是代码,我试图理解的是,如何从数据库的表中获取一个随机单词并将其存储在标签中?另外,我正在使用OleDbConnection来连接数据库 您可以在
数据表
上使用一个可计算的
,然后您可以在其中随机选择一个单词。例如,在填充数据表后:
FillDataTable(command);
var words = myDataTable.AsEnumerable()
.Select(d => d["word"].ToString())
.ToList();
Random rnd = new Random();
int randomNumber = rnd.Next(0, words.Count + 1);
string randomWord = words[randomNumber];
label1.Text = randomWord;
这应该行得通。您只需在数据库中的以下行中使用您的列名更改
word
。选择(d=>d[“word”].ToString())在查看我的答案的“拒绝编辑”后,下面是适用于原始问题的部分:
您可以尝试使用“Random”类生成如下所示的随机数:
// =========== Get a Random Number first, then call DisplayRow() ===============
// Figure out the upper range of numbers to choose from the rows returned
int maxCount = myDataTable.Rows.Count;
// generate a random number to use for "rowIndex" in your 'myDataTable.Rows[rowIndex]'
Random randomNR = new Random();
int myRndNR = randomNR.Next(0, maxCount - 1);
// Execute your DisplayRow(int rowIndex) using myRndNR
DisplayRow(myRndNR);
// ===========
private const String access7ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\inetpub\wwwroot\app_data\WordsDB.accdb";
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 System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
// Use this connection string if your database has the extension .accdb
private const String access7ConnectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\inetpub\wwwroot\app_data\WordsDB.accdb";
// Data components
private OleDbConnection myConnection;
private DataTable myDataTable;
private OleDbDataAdapter myAdapter;
private OleDbCommandBuilder myCommandBuilder;
// Index of the current record
private int currentRecord = 0;
private void MainForm_Load(object sender, EventArgs e)
{
String command = "SELECT * FROM Words";
try
{
myConnection = new OleDbConnection(access7ConnectionString);
myAdapter = new OleDbDataAdapter(access7ConnectionString, myConnection);
myCommandBuilder = new OleDbCommandBuilder(myAdapter);
myDataTable = new DataTable();
FillDataTable(command);
/* Move this "DisplayRow(currentRecord);" down below and use
after you get a random number to pick a random word as shown
below... */
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// =========== Get a Random Number first, then call DisplayRow() ===============
// Figure out the upper range of numbers to choose from the rows returned
int maxCount = myDataTable.Rows.Count;
// generate a random number to use for "rowIndex" in your 'myDataTable.Rows[rowIndex]'
Random randomNR = new Random();
int myRndNR = randomNR.Next(0, maxCount - 1);
// Execute your DisplayRow(int rowIndex) using myRndNR
DisplayRow(myRndNR);
// ===========
}
private void FillDataTable(String selectCommand)
{
try
{
myConnection.Open();
myAdapter.SelectCommand.CommandText = selectCommand;
// Fill the DataTable with the rows returned by the select command
myAdapter.Fill(myDataTable);
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error in FillDataTable : \r\n" + ex.Message);
}
}
private void DisplayRow(int rowIndex)
{
// Check that we can retrieve the given row
if (myDataTable.Rows.Count == 0)
return; // nothing to display
if (rowIndex >= myDataTable.Rows.Count)
return; // the index is out of range
// If we get this far then we can retrieve the data
try
{
DataRow row = myDataTable.Rows[rowIndex];
WordsLbl.Text = row["SpellingWords"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("Error in DisplayRow : \r\n" + ex.Message);
}
}
public Form1()
{
InitializeComponent();
}
}
}
至于为什么你的计划不起作用(在评论中被问及),我建议如下:
我将您的代码复制并粘贴到一个新项目中,并按照您的描述创建了一个Access数据库。。。我认为你面临的问题是:
问题一:您的程序找不到“WordsDB.accdb”
可能的解决办法:
(1) 您可以找出如何在“连接字符串”中创建正确的| DataDirectory |路径,或者
(2) 将“WordsDB.accdb”放在一个文件夹中,您可以使用如下完整路径“Data Source=C:\inetpub\wwwroot\app\u Data\WordsDB.accdb”引用该文件夹,因此“连接字符串”如下所示:
// =========== Get a Random Number first, then call DisplayRow() ===============
// Figure out the upper range of numbers to choose from the rows returned
int maxCount = myDataTable.Rows.Count;
// generate a random number to use for "rowIndex" in your 'myDataTable.Rows[rowIndex]'
Random randomNR = new Random();
int myRndNR = randomNR.Next(0, maxCount - 1);
// Execute your DisplayRow(int rowIndex) using myRndNR
DisplayRow(myRndNR);
// ===========
private const String access7ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\inetpub\wwwroot\app_data\WordsDB.accdb";
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 System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
// Use this connection string if your database has the extension .accdb
private const String access7ConnectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\inetpub\wwwroot\app_data\WordsDB.accdb";
// Data components
private OleDbConnection myConnection;
private DataTable myDataTable;
private OleDbDataAdapter myAdapter;
private OleDbCommandBuilder myCommandBuilder;
// Index of the current record
private int currentRecord = 0;
private void MainForm_Load(object sender, EventArgs e)
{
String command = "SELECT * FROM Words";
try
{
myConnection = new OleDbConnection(access7ConnectionString);
myAdapter = new OleDbDataAdapter(access7ConnectionString, myConnection);
myCommandBuilder = new OleDbCommandBuilder(myAdapter);
myDataTable = new DataTable();
FillDataTable(command);
/* Move this "DisplayRow(currentRecord);" down below and use
after you get a random number to pick a random word as shown
below... */
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// =========== Get a Random Number first, then call DisplayRow() ===============
// Figure out the upper range of numbers to choose from the rows returned
int maxCount = myDataTable.Rows.Count;
// generate a random number to use for "rowIndex" in your 'myDataTable.Rows[rowIndex]'
Random randomNR = new Random();
int myRndNR = randomNR.Next(0, maxCount - 1);
// Execute your DisplayRow(int rowIndex) using myRndNR
DisplayRow(myRndNR);
// ===========
}
private void FillDataTable(String selectCommand)
{
try
{
myConnection.Open();
myAdapter.SelectCommand.CommandText = selectCommand;
// Fill the DataTable with the rows returned by the select command
myAdapter.Fill(myDataTable);
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error in FillDataTable : \r\n" + ex.Message);
}
}
private void DisplayRow(int rowIndex)
{
// Check that we can retrieve the given row
if (myDataTable.Rows.Count == 0)
return; // nothing to display
if (rowIndex >= myDataTable.Rows.Count)
return; // the index is out of range
// If we get this far then we can retrieve the data
try
{
DataRow row = myDataTable.Rows[rowIndex];
WordsLbl.Text = row["SpellingWords"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("Error in DisplayRow : \r\n" + ex.Message);
}
}
public Form1()
{
InitializeComponent();
}
}
}
问题二:您需要将随机代码移出当前位置,以便在填充数据表后执行它
可能的解决办法:
(1) 将Form1.cs更改为如下所示:
// =========== Get a Random Number first, then call DisplayRow() ===============
// Figure out the upper range of numbers to choose from the rows returned
int maxCount = myDataTable.Rows.Count;
// generate a random number to use for "rowIndex" in your 'myDataTable.Rows[rowIndex]'
Random randomNR = new Random();
int myRndNR = randomNR.Next(0, maxCount - 1);
// Execute your DisplayRow(int rowIndex) using myRndNR
DisplayRow(myRndNR);
// ===========
private const String access7ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\inetpub\wwwroot\app_data\WordsDB.accdb";
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 System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
// Use this connection string if your database has the extension .accdb
private const String access7ConnectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\inetpub\wwwroot\app_data\WordsDB.accdb";
// Data components
private OleDbConnection myConnection;
private DataTable myDataTable;
private OleDbDataAdapter myAdapter;
private OleDbCommandBuilder myCommandBuilder;
// Index of the current record
private int currentRecord = 0;
private void MainForm_Load(object sender, EventArgs e)
{
String command = "SELECT * FROM Words";
try
{
myConnection = new OleDbConnection(access7ConnectionString);
myAdapter = new OleDbDataAdapter(access7ConnectionString, myConnection);
myCommandBuilder = new OleDbCommandBuilder(myAdapter);
myDataTable = new DataTable();
FillDataTable(command);
/* Move this "DisplayRow(currentRecord);" down below and use
after you get a random number to pick a random word as shown
below... */
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// =========== Get a Random Number first, then call DisplayRow() ===============
// Figure out the upper range of numbers to choose from the rows returned
int maxCount = myDataTable.Rows.Count;
// generate a random number to use for "rowIndex" in your 'myDataTable.Rows[rowIndex]'
Random randomNR = new Random();
int myRndNR = randomNR.Next(0, maxCount - 1);
// Execute your DisplayRow(int rowIndex) using myRndNR
DisplayRow(myRndNR);
// ===========
}
private void FillDataTable(String selectCommand)
{
try
{
myConnection.Open();
myAdapter.SelectCommand.CommandText = selectCommand;
// Fill the DataTable with the rows returned by the select command
myAdapter.Fill(myDataTable);
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error in FillDataTable : \r\n" + ex.Message);
}
}
private void DisplayRow(int rowIndex)
{
// Check that we can retrieve the given row
if (myDataTable.Rows.Count == 0)
return; // nothing to display
if (rowIndex >= myDataTable.Rows.Count)
return; // the index is out of range
// If we get this far then we can retrieve the data
try
{
DataRow row = myDataTable.Rows[rowIndex];
WordsLbl.Text = row["SpellingWords"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("Error in DisplayRow : \r\n" + ex.Message);
}
}
public Form1()
{
InitializeComponent();
}
}
}
潜在问题:
您的表单可能没有要执行的“事件、行为、加载”集合
MainForm_Load
潜在解决方案:
a。转到Visual Studio中的“设计”视图,然后右键单击表单
b。单击弹出窗口上的“属性”
c。在“属性”窗口(可能在Visual Studio的右下角)中查找“事件”
d。找到“事件”后,查找“行为”(如果按“类别”对属性排序)或“加载”(如果按字母顺序对属性排序)
e。在“加载”框中,确保它显示“MainForm_Load”因为您使用的是access,这是您在数据表中填充行后可以执行的操作。在填充数据表之后,我已经能够测试这一点。我从另一个数据库填充了我的datatable,但这并不重要。我的代码的最后4行帮助您每次从datatable中获得一条随机记录
{
const string query = "SELECT name FROM NewTable";
var command = new SqlCommand(){CommandText = query, CommandType = System.Data.CommandType.Text,Connection=sqlConn};
var dataAdapter = new SqlDataAdapter() { SelectCommand = command };
DataTable dataTable = new DataTable("Names");
dataAdapter.Fill(dataTable);
int count = dataTable.Rows.Count;
int index = new Random().Next(count);
DataRow d = dataTable.Rows[index];
Console.WriteLine(d[0]);
}
你试过什么了吗?当您已经开始时,帮助会更容易。@gunr2171开始了,很抱歉谢谢您的回答它没有错误,但是随机单词没有显示在标签中。表格加载时正在填充,您没有收到任何错误,对吗?表单加载并运行后,实际数据库中的最后一个“拼写单词”是否作为您的“单词BL”出现在表单上?没有。。没有字在工作,你能解释一下你在那里做的一切吗?因为它在工作,我假设你知道如何创建一个有效的连接字符串到你的数据库(WordsDB.accdb),并验证了“MainForm_Load”在你运行程序时被调用。。。我所做的唯一真正的更改是将“DisplayRow(currentRecord);”方法移动到数据集和数据表填充后运行。请看我上面的例子中关于“DisplayRow”的评论。好的,我不明白,谢谢你的回答。顺便说一句,我真的很感激。。也就是说,如果我有一个“go”按钮,你如何让它变成另一个随机单词并存储在标签中?