DataGridView add column by code - c#

I need to add columns to my DataGridView dynamically... to do this here is my code:
dgv.Columns.Clear();
dgv.AutoGenerateColumns = false;
for (int i = 0; i < fields.Length; i++)
{
var newColumn = new DataGridViewColumn(new DataGridViewTextBoxCell());
newColumn.Name = fields[i];
newColumn.DataPropertyName = fields[i];
newColumn.HeaderText = fields[i];
dgv.Columns.Add(newColumn);
}
And after, when I link my query to the DataSource I retrieve this error:
The value can't be null.
Parameter name: columnName
And the strange thing is that here is my DataGridView/DataTable situation:
The names seems right...
The other strange thing is that the first row is shown, but the others gives the exception (the query is OK and the data are valid...)
here is the code to create the DataSource for the table:
public DataTable getData()
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(item.Query, db.getConnection());
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
dap.Fill(ds);
return ds.Tables[0];
}
and after:
dgv.DataSource = getData();

Related

C# Add Combobox and Checkbox for DataGridView Combined SQL Table

I have a table as following in SQL Database. Devicereg Table.
No | Parameter | DataTyp | Enable |
1 xxxx Int True
2 yyyy Int True
3 tttt String False
I want to show these data in DataGridView and its DataTyp column want to add Combobox with default value table cell value, Enable column want to add a checkbox with default value table cell value.
Combobox want to add the following list and the default value is one of following value.
Int
String
Floart
Following code, Combobox value adds all columns value in one combo box.
Code:
string connetionString = null;
SqlConnection connection;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
bool st = false;
DataSet ds = new DataSet();
connection = new SqlConnection(connetionString);
sql = "select * from Devicereg";
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand(sql, connection);
adapter.Fill(ds);
connection.Close();
dataGridView1.DataSource = null;
dataGridView1.ColumnCount = 0;
dataGridView1.DataSource = ds.Tables[0];
DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
dc.DataSource = ds.Tables[0];
dc.ValueMember = "Datatyp";
dataGridView1.Columns.Add(dc);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Example Photo:
Edit 1:
I have done it but how to display only defined items in the dropdown.
Code:
DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
dc.DataSource = ds.Tables[0];
dc.DataPropertyName = "Datatyp";
dc.ValueMember = "Datatyp";
dc.DisplayMember = "Datatyp";
I have 36 rows and all rows Datatyp values shows. I want specific items to select like Int, Flort, Strings only.
Output:
Edit 2:
If I set like the following code, I got error message.
DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
dc.DataSource = new List<string> { "Int", "String", "Flort" };
dc.DataPropertyName = "Datatyp";
dc.ValueMember = "Datatyp";
dc.DisplayMember = "Datatyp";
Error:
To import the DataTyp from database to DataGridViewComboBoxColumn, please refer to the following steps.
First, add the columns to datagridview.
Set the DataTyp's columntype to DataGridViewComboBoxColumn, and set its DataSource like:
Next, set Enable columntype to DataGridViewCheckBoxColumn.
Or via code:
var colNo = new DataGridViewTextBoxColumn
{
HeaderText = "No",
Name = "No"
};
var colParameter = new DataGridViewTextBoxColumn
{
HeaderText = "Parameter",
Name = "Parameter"
};
var colDataTyp = new DataGridViewComboBoxColumn
{
HeaderText = "DataTyp",
Name = "DataTyp",
DataSource = new List<string> { "Int", "String", "Float" }
};
var colEnable = new DataGridViewCheckBoxColumn
{
HeaderText = "Enable",
Name = "Enable"
};
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { colNo, colParameter, colDataTyp, colEnable });
Then fill the datagridview via the code below.
DataSet ds;
string connetionString = #"Connection String";
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From Devicereg", conn);
ds = new DataSet();
sda.Fill(ds, "T1");
}
DataGridViewComboBoxCell typeCell;
foreach (DataRow row in ds.Tables[0].Rows)
{
int index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells["No"].Value = row[0];
dataGridView1.Rows[index].Cells["Parameter"].Value = row[1];
typeCell = (DataGridViewComboBoxCell)(dataGridView1.Rows[index].Cells["DataTyp"]);
typeCell.Value = row[2].ToString().Trim();
dataGridView1.Rows[index].Cells["Enable"].Value = row[3];
}
The result,

How to filter DataTable with condition where int ID is null

I have gridview and
GridViewName.DataSource = table;
table values:
string myConnection = ConfigurationManager.ConnectionStrings["vizitka"].ToString();
string Query_sel = MySqlString;
MySqlConnection conDataBase = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase_sel = new MySqlCommand(Query_sel, conDataBase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase_sel;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
TableName.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I get Values:
then, I'm adding new row to table:
DataRow newRow = table.NewRow();
table.Rows.Add(newRow);
and getting values with empty cells (also ID is empty and it's good for me):
then:
GridViewName.DataSource = table;
all is good, but then if I want to delete from table this new created row, I cannot. I'm trying to filter and bind again GridViewName.
DataView view = new DataView(table);
view.RowFilter = "CONVERT(id, System.String) = null or CONVERT(id, System.String) = ''";
Console.WriteLine(view);
but I'm getting empty table. Why?
I assume the ID is numeric. You don't want = null, you want IS NULL, which is how you check for nulls in both DataView (and also in SQL).
view.RowFilter = "ID IS NULL";

how to update GridView row at once in sql database

I have DLL class to call the table
public DataTable GetTemTableValue(string TableName)
{
SqlConnection conn = new SqlConnection(sConnectionString);
conn.Open();
string query = "select * from " + TableName + "";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
DataTable ds = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
return ds;
}
and i am binding the table to grid view
private void LoadData()
{
clsDataAccess objDAL = new clsDataAccess();
DataTable DS = new DataTable();
string objBLL = DDLTemTableList.SelectedValue.ToString();
DS = objDAL.GetTemTableValue(objBLL);
if (DS != null && DS.Rows.Count != 0)
{
lblNoRecord.Visible = false;
foreach (DataColumn col in DS.Columns)
{
//Declare the bound field and allocate memory for the bound field.
BoundField bfield = new BoundField();
//Initalize the DataField value.
bfield.DataField = col.ColumnName;
//Initialize the HeaderText field value.
bfield.HeaderText = col.ColumnName;
//Add the newly created bound field to the GridView.
GVDataEntry.Columns.Add(bfield);
}
GVDataEntry.DataSource = DS;
GVDataEntry.DataBind();
GVDataEntry.Visible = true;
}
else
{
lblNoRecord.Visible = true;
GVDataEntry.DataSource = null;
GVDataEntry.DataBind();
//GVDataEntry.EmptyDataText = "No recorddata found";
}
so Table is loading to Grid View. every time when i change the tables in dropdownbox and press search button columns will change dynamically so how can i update data in Grid view through using RowEditing,RowUpdating function and i need to store the date in database?

data is not getting deleted from database

In windows desktop application form I am using this code for deleting data from datagridview and database ,I have taken one checkbox column in dataridview ,If I click on checkbox row is getting deleted at that moment from datagridview ,but not from the database therefore when i reload form i can see that row again ,where I am going wrong?
public partial class EditEngClgList : Form
{
private OleDbConnection acccon = null;
private OleDbDataAdapter da = null;
private DataTable dt = null;
private BindingSource bs = null;
private OleDbCommandBuilder cmdb = null;
public EditEngClgList()
{
InitializeComponent();
try
{
acccon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb");
acccon.Open();
}
catch (Exception err)
{
MessageBox.Show("Error:" + err);
}
string sql = "Select * From EngColeges order by EngClgID";
da = new OleDbDataAdapter(sql, acccon);
cmdb = new OleDbCommandBuilder(da);
dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
dataGridView1.Columns[1].Visible = false;
dataGridView1.Columns[2].HeaderText = "Engineering College Name";
dataGridView1.Columns[3].HeaderText = "Adress";
dataGridView1.Columns[4].HeaderText = "Entrance Type";
dataGridView1.Columns[2].Width = 400;
}
private void button4_Click(object sender, EventArgs e)
{
List<int> checkedclg = new List<int>();
DataRow dr;
List<int> checkedclgid = new List<int>();
for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Delete"].Value) == true)
{
checkedclg.Add(i);
checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value));
}
}
foreach (int k in checkedclg)
{
dr = dt.Rows[k];
dt.Rows[k].Delete();
foreach (int j in checkedclgid)
{
OleDbCommand oleDbCommand = new OleDbCommand("DELETE FROM EngColeges WHERE EngClgID = #clgID", acccon);
oleDbCommand.Parameters.Add("#clgID", OleDbType.Integer).Value = j;
oleDbCommand.Prepare();
oleDbCommand.ExecuteNonQuery();
}
}
}
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Delete"].Value) == true)
{
checkedclg.Add(i);
checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value));
}
Looks like the wrong cell value is being passed to Convert.ToInt16? It's using the "Deleted" column instead of your ID column.
Also you can delete all the rows in one sql statement using the where in clause, for example:
DELETE FROM table WHERE id IN (1, 2, 3, 4)
Insted of storing value of Delete like this
checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value));
storing The values of primary key column like this deletes data properly from database Also
checkedclgid.Add(Convert.ToInt32(dataGridView1.Rows[i].Cells["EngClgID"].Value));
You must change this line:
checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value));
to the following:
checkedclgid.Add(Convert.ToInt32(dataGridView1.Rows[i].Cells["CellInTheInvisible‌​Column"].Value));
Because you're converted a boolean type to Int16 and then you're used it in your query for checking with ID in your related table.
OleDbCommand oleDbCommand = new OleDbCommand("DELETE FROM EngColeges WHERE EngClgID = #clgID", acccon);
So, you must store ID of rows that you want to delete them.
I think first of all you are deleting the row and then you are attempting to delete it from database. First of all you delete the row from database and then again call the select query for that table.
All you have right now is a command. You need your OleDbDataAdapter, and pass the command to it:
...
da = new OleDbDataAdapter(sql, acccon);
da.DeleteCommand = oleDbCommand;
More Info: http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter.deletecommand.aspx
Just replace these two lines:
oleDbCommand.Prepare();
oleDbCommand.ExecuteNonQuery();
With:
da.DeleteCommand = oleDbCommand;
References:
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter.deletecommand.aspx

Adding row by row in GridView in runtime

I am new in C#.I want to add rows in a GridView in runtime. I collect a data from 2 or 3 tables. But whenever I am going to
bind() it with GridView, the last inserted row is overwritten by current one. And GridView shows only the current row.
Is it possible to show both rows one bellow the other? Or Is there any code for doing so.Please suggest me code for that so that i can use it in my project.Thanks.
Answer::First you have to declare a static datatable.And a boolean variable having value initially "true".
And then execute following code--->>>
Here is My code::
protected void btnAdd_Click(object sender, EventArgs e)
{
int coursemasterid = Convert.ToInt32(dlAdmissionCourses.SelectedItem.Value);
int batchmasterid = Convert.ToInt32(dlAssignBatch.SelectedItem.Value);
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
DataTable otable = new DataTable();
otable = DbHelper.ExecuteTable(DbHelper.CONSTRING, CommandType.Text, SQL1, null);
DataRow dr1 = otable.Rows[0];
string coursename = dr1["coursename"].ToString();
int coursefees = Convert.ToInt32(dr1["coursefees"]);
string batchname = dr1["batchname"].ToString();
if (chkadd == true)
{
dtglb = new DataTable(); //here dtglb is a global datatable
dtglb.Columns.Add("coursename", typeof(string));
dtglb.Columns.Add("coursefees", typeof(int));
dtglb.Columns.Add("batchname", typeof(string));
}
foreach (DataRow dr in otable.Rows)
{
dtglb.NewRow();
dtglb.Rows.Add(coursename,coursefees,batchname);
}
chkadd = false;
GridView1.DataSource = dtglb;
GridView1.DataBind();
}
//declaring a datatable global in form
DataTable dtglb=new DataTable();
//In click event
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=EMS;User ID=sa;Password=sa123");
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
SqlCommand cmd = new SqlCommand(SQL1, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
//DataColumn faculty = new DataColumn();
da.Fill(ds);
GridView1.DataSourceID = null;
//New Code Added Here
DataRow row = ds.NewRow();
//your columns
row["columnOne"] = valueofone;
row["columnTwo"] = valueoftwo;
dtglb.Rows.Add(row);
foreach(DataRow dr in dtglb.Rows)
{
ds.Rows.Add(dr);
}
//=========
GridView1.DataSource = ds;
GridView1.DataBind();
add rows to DataGridView itself
DataGridViewRow row = new DataGridViewRow();
dataGridView1.BeginEdit();
//your columns
row.Cells["columnOne"] = valueofone;
row.Cells["columnTwo"] = valueoftwo;
dataGridView1.Rows.Add(row);
dataGridView1.EndEdit();

Categories