[英]Retrieving data from a Datatable in C#
我有一個包含三列的數據功能:用戶名密碼和名稱。 我有一個登錄屏幕,該屏幕檢查是否檢查用戶名和密碼是否允許訪問。 我正在嘗試在另一個表單上顯示用戶名,但是我無法使用。
該程序一直運行到我按登錄鍵,然后顯示IndexOutOfRangeException為止。 我覺得我沒有調用數據所在的正確單元格,但無法弄清楚。 我對數據表很陌生。
登錄表單:
namespace Inventory_Program
{
public partial class Login : Form
{
public string name;
public Login()
{
InitializeComponent();
}
/*
* Used when user accepts to login. username and password must be correct or error message will display
* Using a table in sql form.
*/
private void loginButton_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\brand\Documents\Data.mdf; Integrated Security = True;");
SqlDataAdapter adapter = new SqlDataAdapter("Select Count(*) From Login where Username='" + usernameTextfield.Text + "' and Password = '" + passwordTextfield.Text + "'", connection);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
name = dt.Rows[0][3].ToString();
this.Hide();
MainGUIPanel mainview = new MainGUIPanel();
mainview.Show();
}
else
{
MessageBox.Show("Username or Password Incorrect! Try Again!");
}
} //end of login button
//can canel out of login in screen, closes window.
private void cancelButton_Click(object sender, EventArgs e)
{
this.Close();
} //end of cancel button
public string getName()
{
return name;
}
}
}
MainGuiView:
namespace Inventory_Program
{
public partial class MainGUIPanel : Form
{
Login login = new Login();
public MainGUIPanel()
{
InitializeComponent();
//runs the current time and data
currentTime.Start();
}
//Method is adding a horizontal line to the top panel
private void topControlPanel_Paint(object sender, PaintEventArgs e)
{
Graphics graphics = e.Graphics;
Pen pen = new Pen(Color.Black, 1);
graphics.DrawLine(pen, 1091, 93, 00, 93);
graphics.Dispose();
nameLabel.Text = login.getName();
}
//allows for the current time and date to be displayed in the top panel
private void currentTime_Tick(object sender, EventArgs e)
{
DateTime dateTime = DateTime.Now;
}
private void inventoryButton_Click(object sender, EventArgs e)
{
}
}
}
Select Count(*) From Login where Username='" + usernameTextfield.Text + "' and Password = '" + passwordTextfield.Text + "'"
僅在適配器中放入一個項目:其中的表不過是一個數字(來自dt.Rows [0] [0]處的Count(*))。
您會想要類似:
Select UserName From Login where Username='" + usernameTextfield.Text + "' and Password = '" + passwordTextfield.Text + "'"
見下文! 這對所有這些黑客都很脆弱!
和
name = dt.Rows[0][0].ToString();
請注意,這很重要:我真的鼓勵您查找sql服務器注入攻擊。 您的代碼很容易受到此攻擊。 經驗不足的程序員只需在用戶名或密碼字段中鍵入一些代碼,即可登錄您的應用程序或在沒有憑據的情況下清除數據庫。
該錯誤位於:name = dt.Rows [0] [3] .ToString();。
您選擇:count(*),僅返回1列。
您需要選擇要顯示的列。 您無需計算結果,因為where子句應選擇不同的結果。 相反,請檢查數據表的rows.count是否大於1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.