I first added a column to the datagridview, and then I want to add a row, but it says no such columnName was found, but it exists.
I can't find how to do this, can you help me?
Datagridviewe önce column ekledim sonrada satır eklemek istiyorum ama böyle bir columnName bulunumadı diyor ama var
this is the column i added;
public void dilkodlariaktar()
{
baglanti.Open();
SqlCommand komut = new SqlCommand("Select *from tablekolon where frame=#frame ", baglanti);
komut.Parameters.AddWithValue("#frame", "order_enter");
SqlDataReader oku = komut.ExecuteReader();
while (oku.Read())
{
DataGridViewColumn kolon = new DataGridViewColumn();
int index = Convert.ToInt32(oku["sirano"]);
string baslik = oku["kolonad"].ToString();
string name = oku["kolonname"].ToString();
kolon.HeaderText = baslik;
kolon.Name = baslik;
kolon.DataPropertyName = baslik;
kolon.DisplayIndex = index;
detaydatagridview.Columns.Add(kolon);
}
baglanti.Close();
}
this is the line I want to add but it gives an error;
public void modeldetaygetirmerenk()
{
baglanti.Open();
SqlCommand komuts = new SqlCommand("select DISTINCT renkRow FROM barkodModelKarti where modelNo=#modelNo", baglanti);
komuts.Parameters.AddWithValue("#modelNo", model);
SqlDataReader okus = komuts.ExecuteReader();
while (okus.Read())
{
DataGridViewRow dataGridViewRow = new DataGridViewRow();
string deneme = detaydatagridview.Columns["Renk"].Name;
string renksatir = okus["renkRow"].ToString();
dataGridViewRow.Cells[deneme].Value = renksatir;
detaydatagridview.Rows.Add(dataGridViewRow);
}
detaydatagridview.Columns[0].ReadOnly = true;
baglanti.Close();
}
the problem looks simple. you are selecting column renkRow in the query but accessing the column Renk which is not present in the resultset.
so you need to correct it and safe way is to first check whether the column exists or not and then access it. you will not get an exception.
you can use the detaydatagridview.Columns.Contains("YourColumnName") to check whether column exists or not.
A few other suggestions, please avoid using the AddWithValue, you can use Parameters.Add method. also use the parameterized query to avoid SQL injection. you can also avoid select *, you should use only the required columns in the select.
Related
private void ProdutoCB(ComboBox cb)
{
ConnectarDB();
var listaProdutos = new List<string>();
SQLiteCommand com = new SQLiteCommand("PRAGMA table_info('Produtos');", Conn);
SQLiteDataReader reader = com.ExecuteReader();
while (reader.Read())
{
listaProdutos.Add(reader.GetString(0));
// cb.Items.Add(GetString(0));
}
// cb.DataSource = listaProdutos ;
//cb.Items.Add(listaProdutos);
reader.Close();
Conn.Close();
}
I tried in several ways but I could not, I think the value is coming from CHAR type not STRING
The first column of the result of PRAGMA table_info is the column index number.
To get the column name, read the second column (GetString(1)), or the column named name.
EDIT: I am not able to format my code below, if any one can fix it.
I am new to sql queries and still learning.
Table Name: CommissionSetupTable.
I want to display #Paisa if gross_amount is between the range of #FromRate and #ToRate
Below is my code:
string paisa;
private void load_commission_setup()
{
SqlCeConnection conn = null;
SqlCeCommand cmd = null;
SqlCeDataReader rdr = null;
try
{
conn =
new SqlCeConnection(
#"Data Source=|DataDirectory|\Database.sdf;Persist Security Info=False");
conn.Open();
int rowindex = purchaseBillTableDataGridView.Rows.Count - 1;
gross_amount = double.Parse(purchaseBillTableDataGridView[10, rowindex].Value.ToString());
// Gross Amount is between the ranges of FromRate and ToRate.
cmd = new SqlCeCommand("SELECT Paisa FROM CommissionSetupTable WHERE='" + gross_amount.ToString() + "' BETWEEN #FromRate AND #ToRate;", conn);
rdr = cmd.ExecuteReader();
if (rdr == null)
{
}
else
{
while (rdr.Read())
{
paisa = rdr["Paisa"].ToString();
}
rdr.Close();
cmd.Dispose();
}
}
finally
{
conn.Close();
int rowindex = purchaseBillTableDataGridView.Rows.Count - 1;
purchaseBillTableDataGridView[11, rowindex].Value = paisa;
}
}
The correct syntax to use here is the following
cmd = new SqlCeCommand(#"SELECT Paisa FROM CommissionSetupTable
WHERE #gross BETWEEN FromRate AND ToRate;", conn);
Notice that the two field names should not be prefixed with #, otherwise they will be considered parameters placeholders.
And now, before executing the command, add the parameter for the #gross placeholder
cmd.Parameters.Add("#gross", SqlDbType.Decimal).Value = gross_amount;
I don't know what is the exact datatype of the columns FromRate and EndRate, but
note that you should use the correct datatype for your parameter. Do not pass a string and expect the database engine do the conversion for you. (or worse concatenate your value to the rest of the sql using ToString()). This is always wrong also if sometime the database engine could understand your values.
EDIT
Also, following your comments below, it appears that this line is wrong
int rowindex = purchaseBillTableDataGridView.Rows.Count - 1;
If your DataGridView has the property AllowUserToAddRow set to True then you want to use
int rowindex = purchaseBillTableDataGridView.Rows.Count - 2;
because the first line points to the empty row added to the DataGridView for inserting a new record.
I have a DB table (which is empty in this example)
create table words
(
id int not null,
word nvarchar(50) not null
)
and a DataGridView which I'm filling like that:
private SqlConnection _conn;
private SqlDataAdapter _wordsAdapter;
private DataTable _wordsDataTable = new DataTable();
private DataGridView _tblWords;
private void FillWords()
{
_wordsAdapter = new SqlDataAdapter(new SqlCommand("select id, word from words", _conn));
_wordsAdapter.Fill(_wordsDataTable);
DataGridViewColumn column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "id";
column.Name = "id";
_tblWords.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "word";
column.Name = "word";
_tblWords.Columns.Add(column);
_tblWords.DataSource = _wordsDataTable;
}
private void Update()
{
_wordsAdapter.InsertCommand = new SqlCommand("insert into words (id, word) values (#id, #word)", _conn);
SqlParameter p = _wordsAdapter.InsertCommand.Parameters.Add("#id", SqlDbType.Int);
p.SourceColumn = "id";
p.SourceVersion = DataRowVersion.Original;
p = _wordsAdapter.InsertCommand.Parameters.Add("#word", SqlDbType.NVarChar);
p.SourceColumn = "word";
p.SourceVersion = DataRowVersion.Original;
_wordsAdapter.Update(_wordsDataTable);
}
Then I fill a single row of _tblWords with some values and call Update(). And get this message:
Exception thrown: 'System.Data.SqlClient.SqlException' in
System.Data.dll
Additional information: Cannot insert the value NULL into column 'id', table 'DB.MDF.dbo.words'; column does not allow nulls. INSERT
fails.
Why the value for 'id' is not taken from DataTable? What am I doing wrong?
UPDATE:
After inserting this code in the beginning of Update() function, everything works fine:
private void Update()
{
_wordsDataTable.Rows.Clear();
_wordsDataTable.Rows.Add(0, "xxx");
...
So the problem only appears when I fill the DataTable through DataGridView. Why?!
I am guessing that the problem is related to the last empty row in the DataGridView.
You can try something like this instead of the last _wordsAdapter.Update(_wordsDataTable); line
var haveDbNull = _wordsDataTable.Rows.Cast<DataRow>().ToLookup(r => r.ItemArray.Contains(DBNull.Value));
Debug.Print("have DbNull values: " + haveDbNull[true].Count()); // check this number in the Debug Output window
Debug.Print("don't have DbNull values: " + haveDbNull[false].Count());
_wordsAdapter.Update(haveDbNull[false].ToArray()); // to update just the rows that dont have DBNull values
I found some solution. I just remove the added row and add the same values programmatically.
object[] rowValues = dt.Rows[row].ItemArray;
dt.Rows.RemoveAt(row);
dt.Rows.Add(rowValues);
Does anyone know any less ugly way to do it?
The solution is very simple as always...
_dtWords.EndInit();
cmd1.CommandText = "SELECT distinct MbrBtch from Member where MbrStrm='"+DrpDwnStrm .SelectedItem .Text +"'";
cmd1.Connection = con;
DataTable Table1;
Table1 = new DataTable("mbr");
DataRow Row1;
DataColumn MbrBatch = new DataColumn("MbrBatch");
MbrBatch.DataType = System.Type.GetType("System.Int32");
Table1.Columns.Add(MbrBatch);
try
{
con.Open();
SqlDataReader RdrMbr = cmd1.ExecuteReader();
while (RdrMbr.Read())
{
Row1 = Table1.NewRow();
Row1["MbrBatch"] = Convert.ToInt32(RdrMbr.GetInt32(0));
Table1.Rows.Add(Row1);
}
RdrMbr.Close();
}
finally
{
con.Close();
}
DrpDwnBtch.DataSource = Table1;
this.DrpDwnBtch.DataTextField = "MbrBatch";
DrpDwnBtch.DataBind();
//here MbrBtch is numeric type attribute of sql server.
My guess would be the below line gives you an error.
Change the line
Row1["MbrBatch"] = Convert.ToInt32(RdrMbr.GetInt32(0));
with
int mbr = 0;
if (Int32.TryParse(RdrMbr[0], out mbr))
Row1["MbrBatch"] = mbr;
Is it possible that there are null values in the MbrBtch column? If so, you need to check for null like this:
if (!RdrMbr.IsDBNull(0))
Row1["MbrBatch"] = Convert.ToInt32(RdrMbr.GetInt32(0));
else
// Set value to what it should be if null, perhaps a -1 or 0
this is my code but this is giving last record only. but i need all records one by one
string query = "select * from tbl_users;";
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
for (int x = 0; x <= total; x++)
{
dataGridView1.Rows.Add();
while (reader.Read())
{
dataGridView1.Rows[x].Cells["colNic"].Value = reader["NIC"].ToString();
dataGridView1.Rows[x].Cells["colName"].Value = reader["name"].ToString();
dataGridView1.Rows[x].Cells["colAge"].Value = reader["age"].ToString();
dataGridView1.Rows[x].Cells["colCity"].Value = reader["city"].ToString();
}
}
con.Close();
What i undestand from the above is that you actually want to add each record in datagridview as row, so the following should be the code for that:
string query = "select * from tbl_users;";
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
int x = dataGridView1.Rows.Add(); // add new row for each db row in grid
// and use index returned by it
DataGridViewRow currentRow = dataGridView1.Rows[x];
currentRow.Cells["colNic"].Value = reader["NIC"].ToString();
currentRow.Cells["colName"].Value = reader["name"].ToString();
currentRow.Cells["colAge"].Value = reader["age"].ToString();
currentRow .Cells["colCity"].Value = reader["city"].ToString();
}
dataGridView1.Rows.Add() will return the index back for the newly created row, so you should be using that, you actually do not need that for loop, just iterate all the returned row using while and keep adding row in grid one by one.
Another suggestion here is that do not use * when selecting records from the table if you only need specific columns, always specify the columns that you need in the query like:
SELECT NIC,name,age,city FROM tbl_users
Hope it helps.