how to update GridView row at once in sql database - c#

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?

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,

DataGridView add column by code

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();

How to show all the rows in datagridview?

DataTable dt = db.getProductIdFromCategoriesId(categories_id);
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
show_products.ItemsSource = dt5.DefaultView;
}
this code show one by one rows in datagridview
but i want to show all the product rows having categories_id in datagridview in one go
this is the function FillDataGridfromTree in databasecore class and its object is db
public DataTable FillDataGridfromTree(int product_Id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products.product_id as ID, products.remote_products_id as Remote_ID, products_description.products_name as name,products.products_model as model,products.manufacturers_id as manufacturersId,products.products_image as Image,products.products_price as Price,products.products_weight as Weight,products.products_date_added as dateAdded,products.products_last_modified as lastModified,products.products_date_available as dateAvailable,products.products_status as status,products.products_tax_class_id as taxClass FROM products INNER JOIN products_description ON products.product_id=products_description.products_id where products_description.language_id=1 and products_description.products_id=" + product_Id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
DataTable dt = new DataTable("products");
adapter.Fill(dt);
//show_products.ItemsSource = dt.DefaultView;
return dt;
}
}
this is the function through which i get product_id
public DataTable getProductIdFromCategoriesId(int categories_id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products_id FROM products_to_categories where categories_id=" + categories_id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
DataTable dt = new DataTable();
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
adapter.Fill(dt);
return dt;
}
}
how to show all the rows instead of one row in datagridview
CHANGED Try changing your foreach loop to:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
DataTable dt5 = new Datatable();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
dt5.Merge(db.FillDataGridfromTree(int.Parse(products_id)));
}
show_products.ItemsSource = dt5.DefaultView;
You code is always going to display the last row for a category_id, this is because you're assigning an ItemsSource inside a loop. I've changed the top part to do what you looking for:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
List<DataRow> ProductList = new List<DataRow>();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
if(dt5.Rows.Count > 0)
{
ProductList.AddRange(dt5.Select().ToList());
}
}
show_products.ItemsSource = ProductList.CopyToDataTable().DefaultView;

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();

Data does not display when making loop statement in datagridview control

I had datagridview control which retrieves data from database. I had my code to do that, but no data apeared in gridview. I made a break point in the loop but when on DataGridViewTextBoxCell Number = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l];
datagrid view apeared with no data
private void getcategory()
{
for (int i = 0; i < DGCategory.Rows.Count; i++)
{
for (int l = 0; l < DGCategory.Rows[i].Cells.Count; l++)
{
DataGridViewTextBoxCell Number = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l];
DataGridViewTextBoxCell Category = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l];
DataGridViewTextBoxCell Parent = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l];
DataGridViewCheckBoxCell Active = (DataGridViewCheckBoxCell)DGCategory.Rows[i].Cells[l];
DataGridViewTextBoxCell AddDate = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l];
using (SqlConnection Con = GetConnection())
{
SqlCommand cmd = new SqlCommand("SP_GetAllCategories", Con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.Read())
{
Number.Value = dr["Number"].ToString();
Category.Value = dr["Category"].ToString();
Parent.Value = dr["Parent"].ToString();
Active.Value = dr["Active"].ToString();
AddDate.Value = dr["AddDate"].ToString();
}
}
}
}
}
If u want to get values from your database into a grid view .. use the following:
write your query in a String called "selectCommand" for example then use a dataset to get the results:
public DataSet GetSearchEmpResults(string emp_fn)
{
string selectCommand = #"select
emp.first_name as 'First Name',
emp.last_name as 'Last Name'
from Employees emp
where emp.first_name = '" + emp_fn + "';";
SqlCommand command = new SqlCommand(selectCommand, this.Connection);
DataSet ds = new DataSet("Results");
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds, "Results");
return ds;
}
then in the data gridview code:
DataSet results = db.GetSearchEmpResults(fristName, lastName); //this depends on your results
dataGridViewResults.DataSource = results;
dataGridViewResults.DataMember = "Results";
the dataGridViewResults is the name of the data gridview you want your results yo appear in.
Note that you should provide the connection to your database in order to receive the results.

Categories