The folllowing code is vulnerable to SQL injection and I am trying to correct the code of previous developer; he used DataTable to further use query - how do I use prepare statement along with data table?
string data = "";
int i = 1;
cmd = new SqlCommand("select * from maincategory where isactive=1 and id in (select catid from productmaster where isactive=1)", con);
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
con.Close();
if (dt.Rows.Count > 0)
{
data += "<ul>";
foreach (DataRow DR in dt.Rows)
{
data += "<li><a href='product.aspx?cid="+DR["id"]+"'>" + DR["catname"] + "</a></li>";
}
data += " </ul>";
}
lblpartners.Text = data;
The code that I tried:
public void show()
{
string data = "";
int i = 1;
cmd = new SqlCommand("select * from maincategory where isactive=#val1 and id in (select catid from productmaster where isactive=#val2)", con);
con.Open();
cmd.Parameters.AddWithValue("#val1", 1);
cmd.Parameters.AddWithValue("#val2", 1);
DataTable dt = new DataTable();
dt.Load(cmd.Prepare());
con.Close();
if (dt.Rows.Count > 0)
{
data += "<ul>";
foreach (DataRow DR in dt.Rows)
{
data += "<li><a href='product.aspx?cid="+DR["id"]+"'>" + DR["catname"] + "</a></li>";
}
data += " </ul>";
}
lblpartners.Text = data;
}
SqlCommand.Prepare doesn't return an IDataReader, it's a void method. DataReader.Load() requires an IDataReader object.
Perhaps you meant dt.Load(cmd.ExecuteReader())?
Related
friends
please if you have time to solve my problem
i have many textbox in my form with one button and one datagridview
i use this code to make the search
What if i want to perform a search using values from 2 or more text boxes. what if I typed in "r" in the Name text box then also typed "NY" in the city text box. I want to see the gridview give me the results of that.
that what i try to find and i didn't find anything
the code is working if i search in one textbox only
warm regards
private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (txtCIVILIDD.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from Tabl1 where CIVILIDD = '" + txtCIVILIDD.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (txtName_Arabic.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where Name_Arabic like '%" + txtName_Arabic.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (txtusername.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from Tabl1 where username = '" + txtusername.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBox1.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where status = '" + comboBox1.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBox2.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where confirmation = '" + comboBox2.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (CBgender.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where gender like '%" + CBgender.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (CBNATIONALITY.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where NATIONALITY like '" + CBNATIONALITY.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBoxGovernorate.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where Governorate = '" + comboBoxGovernorate.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBoxCity.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where City = '" + comboBoxCity.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
dataGridView1.DataSource = dt;
i try to solve my problem with this code bout i find "SELECT * FROM tabl1 WHERE 1=1 ";
it return null to me
private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
StringBuilder sqlcommand = "SELECT * FROM tabl1 WHERE 1=1 ";
if (!string.IsNullOrEmpty(CBgender.Text))
{
sqlcommand.Append(" and GENDER LIKE '%");
sqlcommand.Append(CBgender.Text);
sqlcommand.Append("%'");
}
// repeat for other textbox fields
dataGridView1.DataSource = dt;
}
my search form
Here are two possible approaches. The first uses #WelcomeOverflows's suggestion which is to use the RowFilter property of the DataTable. The advantage of doing so is that you only have to perform one database query and the filtering is handled client side. However, it isn't possible to protect RowFilter from SQL injection easily (but while you can still potentially subvert the filtering intention, the damage you can do on a disconnected data source is limited). Also if the dataset is enormous, it might not be desirable to pull back the entire dataset at once and keep it in memory.
// call upon startup to get all the data one time
private void GetData()
{
DataTable dataSource = new DataTable();
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString))
{
connection.Open();
SqlCommand selectCommand = new SqlCommand("SELECT * FROM tabl1", connection);
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
adapter.Fill(dataSource);
dataGridView1.DataSource = dataSource;
}
}
// create a filter for the given field in the database and our control
private string CreateFilter(string fieldName, Control userInputControl, bool exactMatch)
{
string searchValue = null;
if (userInputControl is TextBox) searchValue = ((TextBox)userInputControl).Text;
if (userInputControl is ComboBox) searchValue = ((ComboBox)userInputControl).Text;
if (String.IsNullOrWhiteSpace(searchValue)) return null;
if (exactMatch)
return String.Format("{0}='{1}'", fieldName, searchValue);
return String.Format("{0} LIKE '%{1}%'", fieldName, searchValue);
}
// set the filter on our data grid view
private void button1_Click(object sender, EventArgs e)
{
var filterConditions = new[] {
CreateFilter("Name_Arabic", txtName_Arabic, false),
CreateFilter("gender", CBgender, false),
CreateFilter("CIVILIDD", txtCIVILIDD, true),
CreateFilter("NATIONALITY", cbNationality, false)
// etc.
};
var dataSource = (DataTable)dataGridView1.DataSource;
if (!filterConditions.Any(a => a != null))
{
dataSource.DefaultView.RowFilter = null;
return;
}
dataSource.DefaultView.RowFilter = filterConditions
.Where(a => a != null)
.Aggregate((filter1, filter2) => String.Format("{0} AND {1}", filter1, filter2));
}
Second approach is to filter directly in the database query, using SQL parameters to avoid SQL injection.
private string CreateSqlFilter(string fieldName, Control userInputControl, SqlCommand command, bool exactMatch)
{
string searchValue = null;
if (userInputControl is TextBox) searchValue = ((TextBox)userInputControl).Text;
if (userInputControl is ComboBox) searchValue = ((ComboBox)userInputControl).Text;
if (String.IsNullOrWhiteSpace(searchValue)) return null;
if (exactMatch)
{
command.Parameters.Add(new SqlParameter("#" + fieldName, searchValue));
return fieldName + " = #" + fieldName;
}
else
{
command.Parameters.Add(new SqlParameter("#" + fieldName, "%" + searchValue + "%"));
return fieldName + " LIKE #" + fieldName;
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlCommand selectCommand = new SqlCommand();
var filterConditions = new[] {
CreateSqlFilter("Name_Arabic", txtName_Arabic, selectCommand, false),
CreateSqlFilter("gender", CBgender, selectCommand, false),
CreateSqlFilter("CIVILIDD", txtCIVILIDD, selectCommand, true),
CreateSqlFilter("NATIONALITY", cbNationality, selectCommand, false)
// etc.
};
string filterCondition = filterConditions.Any(a => a != null) ? filterConditions.Where(a => a != null).Aggregate((filter1, filter2) => String.Format("{0} AND {1}", filter1, filter2)) : (string)null;
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString))
{
selectCommand.Connection = connection;
selectCommand.CommandText = filterCondition == null ? "SELECT * FROM tabl1" : "SELECT * FROM tabl1 WHERE " + filterCondition;
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
DataTable dataSource = new DataTable();
adapter.Fill(dataSource);
dataGridView1.DataSource = dataSource;
}
}
Create StringBuilder object:
StringBuilder sqlcommand = new StringBuilder("SELECT * FROM tabl1 WHERE 1=1");
You can create a parametrized query which considers parameters having null values as neutral in search. For example:
SELECT * FROM Product WHERE
(Id = #Id OR Id IS NULL) AND
(Name LIKE '%' + #Name + '%' OR #Name IS NULL) AND
(Price = #Price OR #Price IS NULL)
This way, if you pass NULL for any of the parameters, that parameter will not be considered in search.
Also as a side note, it prevents SQL Injection, by using parameters.
Example
The following example assumes you have a table called Product, having a column named Id as INT, Name as NVARCHAR(100) and Price as INT.
Then to load data, create the following method:
public DataTable GetData(int? id, string name, int? price)
{
DataTable dt = new DataTable();
var commandText = "SELECT * FROM Products WHERE " +
"(Id = #Id OR #Id is NULL) AND " +
"(Name LIKE '%' + #Name + '%' OR #Name IS NULL) AND " +
"(Price = #Price OR #Price IS NULL)";
var connectionString = #"Data Source=.;Initial Catalog=SampleDb;Integrated Security=True";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(commandText, connection))
{
command.Parameters.Add("#Id", SqlDbType.Int).Value =
(object)id ?? DBNull.Value;
command.Parameters.Add("#Name", SqlDbType.NVarChar, 100).Value =
(object)name ?? DBNull.Value;
command.Parameters.Add("#Price", SqlDbType.Int).Value =
(object)price ?? DBNull.Value;
using (var datAdapter = new SqlDataAdapter(command))
datAdapter.Fill(dt);
}
return dt;
}
To get values from TextBox controls and pass to GetData, you can use the following code:
var id = int.TryParse(idTextBox.Text, out var tempId) ? tempId : default(int?);
var name = string.IsNullOrEmpty(nameTextBox.Text)?null:nameTextBox.Text;
var price = int.TryParse(priceTextBox.Text, out var priceId) ? priceId : default(int?);
Then to get data:
var data = GetData(id, name, price);
can somebody tell me why this update procedure doesn't work? I want to read data to dataset from XLS and it works just fine but UPDATE doesn't work at all. No errors, no changes, like it doesn't exist. The file creates but values are just a copy from original xls.
Xls sheet format is pretty simple, one column: id 1 2 3
string string_conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\name.xls;Extended Properties='Excel 8.0;HDR=Yes;'";
OleDbConnection conn = new OleDbConnection(string_conn);
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
comboBox1.DataSource = excelSheets;
string xlsSheet = comboBox1.SelectedItem.ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
adapter.UpdateCommand = new OleDbCommand ("UPDATE " + xlsSheet + " SET id = " + tbox1.Text + " WHERE id = " + tbox2.Text + "", conn);
adapter.UpdateCommand.Parameters.Add("#id", OleDbType.Char, 255).SourceColumn = "id";
adapter.UpdateCommand.Parameters.Add("#Oldid", OleDbType.Char, 255, "id").SourceVersion = DataRowVersion.Original;
adapter.Update(dataset);
dataset.AcceptChanges();
DataTable dtable = new DataTable();
dtable = dataset.Tables[0];
StringBuilder str = new StringBuilder();
foreach (DataRow dr in dtable.Rows)
{
foreach (var field in dr.ItemArray)
{
str.Append(field.ToString());
str.Append(", ");
}
str.Replace(",", str.AppendLine().ToString(), str.Length - 1, 1);
}
MessageBox.Show(str.ToString()); //for test's sake
string pathFile = #"path\filename.csv";
if (!File.Exists(pathFile))
{
File.Create(pathFile).Close();
}
File.AppendAllText(pathFile, str.ToString());
Something is wrong with parameters probably but I tried this way and also no go (I added 2nd column so id stays the same just to find proper row), I get UPDATE command syntax error on execute:
string string_conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\arkusz.xls;Extended Properties='Excel 8.0;HDR=Yes;'";
OleDbConnection conn= new OleDbConnection(string_conn);
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
comboBox1.DataSource = excelSheets;
string xlsSheet = comboBox1.SelectedItem.ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
adapter.UpdateCommand = new OleDbCommand("UPDATE " + xlsSheet + " SET nazwa = #nazwa WHERE id = #id", conn);
adapter.UpdateCommand.Parameters.AddWithValue("#id", tbox1.Text).OleDbType = OleDbType.Integer;
adapter.UpdateCommand.Parameters.AddWithValue("#nazwa", tbox2.Text).OleDbType = OleDbType.VarChar;
adapter.UpdateCommand.ExecuteNonQuery();
adapter.Update(dataset);
dataset.AcceptChanges();
DataTable dtable = new DataTable();
dtable = dataset.Tables[0];
StringBuilder str = new StringBuilder();
foreach (DataRow dr in dtable.Rows)
{
foreach (var field in dr.ItemArray)
{
str.Append(field.ToString());
str.Append(", ");
}
str.Replace(",", str.AppendLine().ToString(), str.Length - 1, 1);
}
MessageBox.Show(str.ToString());
string sciezkaPlik = #"path\filename.csv";
if (!File.Exists(sciezkaPlik))
{
File.Create(sciezkaPlik).Close();
}
File.AppendAllText(sciezkaPlik, str.ToString());
I solved the issue. For future reference it works well like this:
string string_conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\arkusz.xls;Extended Properties='Excel 8.0;HDR=Yes;'";
OleDbConnection conn = new OleDbConnection(string_conn);
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
comboBox1.DataSource = excelSheets;
string xlsSheet = comboBox1.SelectedItem.ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
OleDbCommand odbc = new OleDbCommand("UPDATE ["+xlsSheet+"] SET nazwa = " + txtNewValue.Text + " WHERE id = " + txtID.Text + "", conn);
adapter.UpdateCommand = odbc;
odbc.Parameters.AddWithValue("nazwa", txtNewValue.Text).OleDbType = OleDbType.VarChar;
odbc.Parameters.AddWithValue("id", txtID.Text).OleDbType = OleDbType.Integer;
odbc.ExecuteNonQuery();
dataset.Clear();
adapter.Fill(dataset);
DataTable dtable = new DataTable();
dtable = dataset.Tables[0];
StringBuilder str = new StringBuilder();
foreach (DataRow dr in dtable.Rows)
{
foreach (var field in dr.ItemArray) /
{
str.Append(field.ToString());
str.Append(", ");
}
str = str.Replace(',', '\n');
}
string filePath= #"path\filename.csv";
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
File.WriteAllText(filePath, str.ToString());
EDIT - I think it may be that this line needs to have the parameters put in as a question mark instead of having the actual values passed in, so more like this:
adapter.UpdateCommand = new OleDbCommand ("UPDATE " + xlsSheet + " SET id = ? WHERE id = ?", conn);
Then your next couple of lines are correct, they are clever enough to replace the question marks from the UpdateCommand with the actual values at run time:
adapter.UpdateCommand.Parameters.Add("#id", OleDbType.Char, 255).SourceColumn = "id";
adapter.UpdateCommand.Parameters.Add("#Oldid", OleDbType.Char, 255, "id").SourceVersion = DataRowVersion.Original;
Hare is a very simple method to do an insert into an Excel sheet.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [Sheet1$] (id,name) values('5','e')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}
Under this I am trying to save the cart items chosen by the user into the database, for that I have initially selected the chosen items through Request.Query method now after that I have called those values and formed an SaveCartDetail function in which I have performed insert command into the database,the asp.net shows no error but there is no change in my table the name of my table is cart.
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("itemname");
dt.Columns.Add("quantity");
dt.Columns.Add("price");
dt.Columns.Add("totalprice");
dt.Columns.Add("image");
if (Request.QueryString["itemname"] != null)
{
if (Session["Buyitems"] == null)
{
dr = dt.NewRow();
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);
scon.Open();
String myquery = "select * from food_items where item_name=#items_name";
SqlCommand cmd = new SqlCommand(myquery, scon);
cmd.Parameters.AddWithValue("items_name", Request.QueryString["itemname"].ToString());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
if (ds.Tables[0].Rows.Count > 0)
{
dr["itemname"] = ds.Tables[0].Rows[0]["item_name"].ToString();
dr["image"] = ds.Tables[0].Rows[0]["image"].ToString();
dr["price"] = ds.Tables[0].Rows[0]["price"].ToString();
int price = Convert.ToInt16(ds.Tables[0].Rows[0]["price"].ToString());
int quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
int totalprice = price * quantity;
dr["quantity"] = Request.QueryString["quantity"];
dr["totalprice"] = totalprice;
SaveCartDetail(ds.Tables[0].Rows[0]["item_name"].ToString(), Request.QueryString["quantity"], ds.Tables[0].Rows[0]["price"].ToString(), totalprice.ToString());
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
GridView1.FooterRow.Cells[4].Text = "Total Amount";
GridView1.FooterRow.Cells[5].Text = grandtotal().ToString();
}
}
}
}
private void SaveCartDetail(String itemname, String quantity, String price, String totalprice)
{
String query = "insert into cart(item_name, quantity, price, totalprice, username) values ('" + itemname + "','" + quantity + "','" + price + "','" + totalprice + "','" + Session["username"].ToString() + "')";
SqlConnection scon1 = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);
scon1.Open();
SqlCommand cmd1 = new SqlCommand(query, scon1);
cmd1.ExecuteNonQuery();
scon1.Close();
Response.Write("Items saved in cart");
}
I tried to get 4 names from first table and check how frequent 4 of the names appeared in each of another 20 groups and then update it on groupevenfrequency. However, I have encountered error on this coding. Appreciate if someone can assist. Thanks.
From this coding, why str[1] and str[2] and str[3] and str[4] is same teachername? But the sql command SELECT DISTINCT is already resulted 4 different teachers. Please advice.
dbConnect = new SQLiteConnection("Data Source=school.db;Version=3;");
dbConnect.Open();
cmd = new SQLiteCommand();
cmd = dbConnect.CreateCommand();
cmd.CommandText = "SELECT DISTINCT Teacher_Name from " + myTeacher + " Order by Sum_Weekly_Credit desc LIMIT 4";
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
string[] str = new string[5];
for (int i = 1; i <= 4; i++)
{
foreach (DataRow dr in dt.Rows)
{
str[i] = dr["Teacher_Name"].ToString();
cmd.ExecuteNonQuery();
}
}
dbConnect.Close();
dbConnect = new SQLiteConnection("Data Source=school.db;Version=3;");
dbConnect.Open();
cmd2 = new SQLiteCommand();
cmd2 = dbConnect.CreateCommand();
cmd3 = new SQLiteCommand();
cmd3 = dbConnect.CreateCommand();
for (int j = 1; j <= 20; j++)
{
cmd2.CommandText = "SELECT Subject FROM Group_Even_" + j + " WHERE Teacher_Name = #Teacher_Name1 OR Teacher_Name = #Teacher_Name2 OR Teacher_Name = #Teacher_Name3 OR Teacher_Name = #Teacher_Name4";
cmd2.Parameters.AddWithValue("#Teacher_Name1", str[1]);
cmd2.Parameters.AddWithValue("#Teacher_Name2", str[2]);
cmd2.Parameters.AddWithValue("#Teacher_Name3", str[3]);
cmd2.Parameters.AddWithValue("#Teacher_Name4", str[4]);
DataTable dt2 = new DataTable();
SQLiteDataAdapter da2 = new SQLiteDataAdapter(cmd2);
da2.Fill(dt2);
if (dt2.Rows.Count > 0)
{
int TempCountFrequency = dt2.Rows.Count;
cmd2.CommandText = "UPDATE GroupEvenFrequency SET GroupEven_Frequency = #GroupEven_Frequency WHERE GroupEven_Name = Group_Even_" + j + "";
cmd2.Parameters.AddWithValue("#GroupEven_Frequency", TempCountFrequency);
cmd2.ExecuteNonQuery();
}
else
{
continue;
}
}
The code you have here looks wrong....
for (int i = 1; i <= 4; i++)
{
foreach (DataRow dr in dt.Rows)
{
str[i] = dr["Teacher_Name"].ToString();
cmd.ExecuteNonQuery();
}
}
Surely you are expecting the dt.Rows to contain the 4 names you are interested in? So why have the outer loop.
So shouldn't it be more like...
string[] str = new string[5];
int i = 1;
foreach (DataRow dr in dt.Rows)
{
str[i] = dr["Teacher_Name"].ToString();
i++;
}
But as others have pointed out your overall approach could do with a rethink. The code won't cater for the fact that you might not have 4 distinct teacher names
I am using a SQL Server Compact 3.5 database file (.sdf) in C#; with the code I can read from albums_tbl but I want to create a row for every record of table while by clicking on a specific row I will be able to get its name and id.
albums_tbl table has two columns: id, name
SqlCeDataReader rdr = null;
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM albums_tbl ", cn);
rdr = cm.ExecuteReader();
int n = 0;
while (rdr.Read())
{
// rdr.GetString(0) is id
// rdr.GetString(1) is name
label1.Text = rdr.GetString(1) ;
}
I did this when I used sql conncetion :
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM album_items WHERE name LIKE N'%" + searchItemName.Text + "%' ", con);
searchItemName.Text = "";
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView2.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView2.Rows.Add();
dataGridView2.Rows[n].Cells[0].Value = item["id"].ToString();
dataGridView2.Rows[n].Cells[1].Value = item["name"].ToString();
}
and after that I could get information by clicking on any row by this code :
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
if (dataGridView1.Rows.Count != 0)
{
albumId.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
albumName.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
}
}
I want to do it now using a SqlCeCommand