How to save changes to DataView to Database on button click? - c#

I'm new to Asp.net and I'm trying to figure out how to update a value in a SqlDataSource programmatically. Here's my button click listener:
protected void ApproveLoanButton_Click(object sender, EventArgs e)
{
DataView dv = (DataView)DetailsSqlDataSource.Select(DataSourceSelectArguments.Empty);
dv.AllowEdit = true;
using (var dt = dv.ToTable())
{
var oldValue = dt.Rows[0]["IsApproved"].ToString();
dt.Rows[0]["IsApproved"] = true;
var newValue = dt.Rows[0]["IsApproved"].ToString();
dt.AcceptChanges();
GridView1.DataBind();
DetailsView1.DataBind();
}
}
The oldValue is false and the newValue is true so I am changing the value but it doesn't save to the database when I call AcceptChanges(). What am I doing wrong here? I've already spent hours on this. Thanks for your help!

I do not have what your DetailsSqlDataSource is, or what your database structure is like, but you would obviously need to write a few Save and Read methods.
If you did that, you would have something like this:
protected void ApproveLoanButton_Click(object sender, EventArgs e)
{
DataView dv = (DataView)DetailsSqlDataSource.Select(DataSourceSelectArguments.Empty);
dv.AllowEdit = true;
using (var dt = dv.ToTable())
{
var oldValue = dt.Rows[0]["IsApproved"].ToString();
if (-1 < SaveApproved((int)dt.Rows[0]["ID"], true))
{
dt.Rows[0]["IsApproved"] = true;
var newValue = dt.Rows[0]["IsApproved"].ToString();
dt.AcceptChanges();
DetailsSqlDataSource = GetTable();
GridView1.DataBind();
DetailsView1.DataBind();
}
}
}
You will need to modify these to work, but here is a sample:
private const string SQL_CONNECTION = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
private DataTable GetTable()
{
var table = new DataTable();
using (var con = new System.Data.SqlClient.SqlConnection(SQL_CONNECTION))
{
con.Open();
using (var cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM MyTable;", con))
{
table.Load(cmd.ExecuteReader());
}
}
return table;
}
private int SaveApproved(int rowID, bool approved)
{
using (var con = new System.Data.SqlClient.SqlConnection(SQL_CONNECTION))
{
con.Open();
using (var cmd = new System.Data.SqlClient.SqlCommand("UPDATE MyTable SET IsApproved=#IsApproved WHERE ID=#ID;", con))
{
cmd.Parameters.Add("#IsApproved", SqlDbType.Bit).Value = approved;
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = rowID;
return cmd.ExecuteNonQuery();
}
}
}

Related

Why do I get the value System.Data.DataRowView? c#

Why do I get the value System.Data.DataRowView? c# + sqlserver
I'm trying to add data to my table but ne system.Data.rowview and I don't know how to do it so that it doesn't come out
Why do I get the value System.Data.DataRowView? c# + sqlserver
This is where I load the items inside the Checklixbox
public void Cargar_Requerimientos(string Id_CR)
{
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT Id_CR, Requisitos, Id_RS FROM Requerimientos WHERE Id_CR =#Id_CR ", cn);
cmd.Parameters.AddWithValue("Id_CR", Id_CR);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cn.Close();
//DataRow dr = dt.NewRow();
//dr["Requisitos"] = "Seleciona un Requisitos";
// dt.Rows.InsertAt(dr, 0);
///////////////////////////////////////
checkedListBox1.ValueMember = "Id_RS";
checkedListBox1.DisplayMember = "Requisitos";
checkedListBox1.DataSource = dt;
//bool state = true;
// for (int i = 0; i < checkedListBox1.Items.Count; i++)
// checkedListBox1.SetItemCheckState(i, (state ? CheckState.Checked : CheckState.Unchecked));
//dr = dt.NewRow();
enter code here
try
{
//checkedListBox1.DataSource = dt.Columns[0].ToString();
//dt.Columns[0].ToString();
//checkedListBox1.DataSource = dt.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
here I upload the data from combobox1 to checklistbox1
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// checkedListBox1.Enabled = false;
{
if (comboBox1.SelectedItem.ToString() == null)
{
checkedListBox1.Enabled = true;
}
}
if (comboBox1.SelectedValue.ToString() != null)
{
string Id_CR = comboBox1.SelectedValue.ToString();
Cargar_Requerimientos(Id_CR);
}
Result:
The CheckListBox does not directly support a DataSource, which is why the property is hidden from intellisence.
Usually it is correct to set the DataSource after setting the DisplayMember and ValueMember properties, to avoid multiple refresh calls, but to avoid your issue, you have to set the DataSource property first:
checkedListBox1.DataSource = dt;
checkedListBox1.ValueMember = "Id_RS";
checkedListBox1.DisplayMember = "Requisitos";

refreshing DataSource Master-Detail XtraGrid

i have this code that create Master-Detail XtraGrid at runtime
public partial class FRM_Reserved : DevExpress.XtraEditors.XtraForm
{
DataTable Table1 = new DataTable("Table1");
DataTable Table2 = new DataTable("Table2");
DataSet dataSet = new DataSet();
public FRM_Reserved()
{
InitializeComponent();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
dataSet.Relations.Add("OrderDetails",
dataSet.Tables["Table1"].Columns["Bon N"],
dataSet.Tables["Table2"].Columns["Bon N"]);
gridControl3.DataSource = dataSet.Tables["Table1"];
}
I want to refreshing DataSource on a click of button so I added this code
private void btnRefresh_Click(object sender, EventArgs e)
{
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.ForceInitialize();
}
but the code does not work ,can you help me please.
Try below code. Hope it works
private void btnRefresh_Click(object sender, EventArgs e)
{
gridControl3.DataSource=null;
gridControl3.Items.Clear();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.ForceInitialize();
}
the problem was in the name of the tables it change every time
dataSet.Tables[(Table1.TableName)]
dataSet.Tables[(Table2.TableName)]
so I made this changes
private void simpleButton1_Click(object sender, EventArgs e)
{
dataSet.Relations.Clear();
dataSet.Tables["Table2"].Clear();
dataSet.Tables["Table1"].Clear();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
dataSet.Relations.Add("OrderDetails",
dataSet.Tables[(Table1.TableName)].Columns["Bon N"],
dataSet.Tables[(Table2.TableName)].Columns["Bon N"]);
gridControl3.DataSource = dataSet.Tables[(Table1.TableName)];
gridControl3.ForceInitialize();
}
Thanks for helping me
Use the following code
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.RefreshDataSource();
Try this one
private void button1_Click(object sender, EventArgs e)
{
var ds = new DataSet();
var dt1 = GetTable1Data();
var dt2 = GetTable2Data();
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
ds.Relations.Add("RelationTable",
ds.Tables["Table1"].Columns["col1"],
ds.Tables["Table2"].Columns["col1"]);
gridControl1.DataSource = ds.Tables["Table1"];
gridControl1.RefreshDataSource();
}
private DataTable GetTable1Data()
{
using (var conn = new SqlConnection("Conneciton string goes here"))
{
conn.Open();
using (var cmd = new SqlCommand("Stored procedure name goes here", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}
private DataTable GetTable2Data()
{
using (var conn = new SqlConnection("Conneciton string goes here"))
{
conn.Open();
const string sql = "SELECT * FROM Table2";
using (var cmd = new SqlCommand(sql, conn))
{
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}

Delete the single selected row from a grid view at run time

I have a table having 2 columns viz ID and DETAILS.Data in a table is like
id=01 details="pritam=123 sourav=263" like this
i am working on a windows for application ..when the application will run the output comes what i am going to tell.. 1.in my application one combobox is there.when the application will run all the id will be bind in a combobox from the table. 2.when user will choose any id suddenly the details column data will be shown in a datagrid view in a splitted format like this.
NAME KEY
PRITAM 123
SOURAV 263
in this data grid view user can delete ant row by selecting the and click on the below delete button. insert any row by clickng the add new row button at the end ,modify any existing data and finally click on the update button and all the data are going to be stored in that data base like in previous format.. for that i have written the code in c# like this..
namespace windows_csharpp
{
public partial class Form5 : Form
{
SqlConnection cc = new SqlConnection("Integrated Security=true;database=EDIXfer");
SqlDataAdapter da;
DataTable dt;
public Form5()
{
InitializeComponent();
}
private void Form5_Load(object sender, EventArgs e)
{
string sql="select EDIScheduleID from ETAProcessSchedule";
da= new SqlDataAdapter(sql, cc);
dt = new System.Data.DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
comboBox1.Items.Add(dt.Rows[x][0].ToString());
}
}
ArrayList ls = new ArrayList();
int ss = 0;
int ss1 = 0;
int ssp = 1;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sql = "select * from ETAProcessSchedule where EDIScheduleID='" + comboBox1.SelectedItem.ToString() + "'";
SqlDataAdapter adp = new SqlDataAdapter(sql, cc);
DataTable dt = new System.Data.DataTable();
adp.Fill(dt);
string stp = dt.Rows[0][21].ToString();
string[] stp1 = stp.Split(' ');
List<Class1> lst = new List<Class1>();
ls.Clear();
for (int x = 0; x < stp1.Length; x++)
{
ls.Add(stp1[x].ToString());
}
for (int x = 0; x < ls.Count; x++)
{
string ssttt = ls[x].ToString();
string[] sssp = ssttt.Split('=');
for (int x1 = 1; x1 < sssp.Length; x1++)
{
ss = 0;
ss1 = ssp;
Class1 cs = new Class1()
{
Value = sssp[ss], Key= sssp[x1].ToString()
};
lst.Add(cs);
}
}
dataGridView1.DataSource = lst;
}
private void Update_Click(object sender, EventArgs e)
{
string value = null;
string keys = null;
string query = null;
string str = null;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
value = dataGridView1.Rows[i].Cells[0].Value.ToString();
keys = dataGridView1.Rows[i].Cells[1].Value.ToString();
string ss = value + '=' + keys;
str += ss + ' ';
}
query = "update ETAProcessSchedule set ProcParameters='"+str+"' where EDIScheduleID='"+comboBox1.SelectedItem.ToString()+"'";
da = new SqlDataAdapter(query, cc);
dt = new DataTable();
da.Fill(dt);
MessageBox.Show("Data Updated In Database Successfully");
}
and one class file is also there ..
class Class1
{
public string Value { get; set; }
public string Key { get; set; }
}
kindly help me in delete the selected row ,add the new row and update the all data in database like in previous format..
I think you already have working approach. If I understand right you need only two functions:
- Load Schedule details in the DataGridView (one key-value pair per row)
- Save edited/added/deleted key-value pairs to the database
Be sure next properties of DataGridView set to true:
this.YourDataGridView.AllowUserToAddRows = true;
this.YourDataGridView.AllowUserToDeleteRows = true;
And of course columns must be editable
In the methods was used const variables which was created in your Form (Form1)
private const string DETAILSDELIMITER = ' ';
private const string NAMEKEYDELIMITER = '=';
Method for loading schedule details in the DataGridView
//Use SqlParameters in the query,
//if not your application vulnerable for sql injection
private void LoadScheduleDetails(string scheduleID)
{
//You working only with one column, do not use '*' in SELECT statement if not nessesary
string query = "SELECT EDIScheduleID, ProcParameters FROM ETAProcessSchedule WHERE EDIScheduleID = #ScheduleID";
DataTable details = new DataTable();
//Get data from database
using (SqlConnection yourConnection = new SqlConnection(_YourConnectionString))
{
using(SqlCommand detailsCommand = new SqlCommand(query, yourConnection))
{
//Adding parameter
SqlParameter id = new SqlParameter { ParameterName = "#ScheduleID", SqlDbType = SqlDbType.NVarChar, Value = scheduleID };
detailsCommand.Parameters.Add(id);
using (SqlDataAdapter yourAdapter = new SqlDataAdapter(detailsCommand ))
{
yourAdapter.Fill(details);
}
}
}
this.YourDataGridView.Rows.Clear();
if (details.Rows.Count > 0)
{
DataRow temp = details.Rows[0];
//get column by name.
string[] pairs = temp.Field<String>("ProcParameters").Split(Form1.DETAILSDELIMITER);
//Adding rows manually without DataSource
foreach(string pair in pairs)
{
this.YourDataGridView.Rows.Add(pair.Split(Form1.NAMEKEYDELIMITER));
}
}
}
Method for saving data
I think better if you create columns already in the designer
Then you can access columns by it's name without hardcoding indexes
private void SaveDetails(string scheduleID)
{
StringBuilder details = new StringBuilder();
foreach(DataGridViewRow dgvr in this.YourDataGridView.Rows)
{
string name = dgvr.Cells[this.dgvColumn_Name.Name].Value.ToString();
string key = dgvr.Cells[this.dgvColumn_Key.Name].Value.ToString();
//Here you can check if values are ok(not empty or something else)
//Create pair
details.Append(Form1.DETAILSDELIMITER);
details.Append(name);
details.Append(Form1.NAMEKEYDELIMITER);
details.Append(key);
}
//remove first space character
if (details.Length > 0)
details.Remove(0, 1);
//Save data to database
string query = "UPDATE ETAProcessSchedule SET ProcParameters=#Details WHERE EDIScheduleID=#ScheduleID";
using (SqlConnection yourConnection = new SqlConnection(_YourConnectionString))
{
using (SqlCommand saveCommand = new SqlCommand(query, yourConnection))
{
//Adding parameters
SqlParameter id = new SqlParameter { ParameterName = "#ScheduleID", SqlDbType = SqlDbType.NVarChar, Value = scheduleID };
SqlParameter procParams = new SqlParameter { ParameterName = "#Details", SqlDbType = SqlDbType.NVarChar, Value = details.ToString() };
saveCommand.Parameters.Add(id);
saveCommand.Parameters.Add(procParams);
saveCommand.ExecuteNonQuery();
MessageBox.Show("Data Updated In Database Successfully");
}
}
}
Then use LoadScheduleDetails in the comboBox1_SelectedIndexChanged eventhandler
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string scheduleID = comboBox1.SelectedItem.ToString();
if(String.IsNullOrEmpty(scheduleID) == false)
{
this.LoadScheduleDetails(scheduleID);
}
}
After data loaded, user can change it, add rows, delete rows
When user pressed "Update" button then use SaveDetails method,
where we collect data from all rows and update database with it
private void Update_Click(object sender, EventArgs e)
{
string scheduleID = comboBox1.SelectedItem.ToString();
if(String.IsNullOrEmpty(scheduleID) == false)
{
this.SaveDetails(scheduleID);
}
}
On your form load bind data:-
EDIT : -
private void Form5_Load(object sender, EventArgs e)
{
comboBox1.DataSource = loadddltable();
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
}
public DataTable loadddl()
{
OleDbDataReader obj = null;
DataTable dt = new DataTable();
try
{
obj_dbconnection.CommandText = "Select * from TableName";
obj = obj_dbconnection.ExecuteReader();
if (obj != null)
{
if (obj.HasRows)
{
dt.Load(obj);
}
}
}
catch (Exception)
{
}
finally
{
if (obj != null)
{
obj.Close();
obj_dbconnection.Close();
}
}
return dt;
}
/*Code for Execute Reader*/
public OleDbDataReader ExecuteReader()
{
OleDbDataReader dr = null;
try
{
Open();
dr = cmd.ExecuteReader();
}
catch(Exception)
{ }
return dr;
}
/*Code for binding grid data*/
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataSource= getDataForSelectedId(comboBox1.SelectedValue);
}
And then insert,edit,delete buttons as template fields to dataGridView and use dataGridView1_CellClick event to insert edit delete

Cancel/insert/update not saving to the DB

I am working on Northwind database reproducing this demo. The code is not showing any error but all operations insert/update/delete are only temporary. If I add a record or cancel or update the next time I run the code, the content of the table is still the original one without any of the modification I did saved inthe db.
private static DataTable GetDataTable(string queryString)
{
String connString = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString;
SqlConnection mySqlConnection = new SqlConnection(connString);
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = new SqlCommand(queryString, mySqlConnection);
DataTable myDataTable = new DataTable();
mySqlConnection.Open();
try
{
mySqlDataAdapter.Fill(myDataTable);
}
finally
{
mySqlConnection.Close();
}
return myDataTable;
}
private DataTable Employees
{
get
{
object obj = this.Session["Employees"];
if ((!(obj == null)))
{
return ((DataTable)(obj));
}
DataTable myDataTable = new DataTable();
myDataTable = GetDataTable("SELECT * FROM Employees");
this.Session["Employees"] = myDataTable;
return myDataTable;
}
}
protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
this.RadGrid1.DataSource = this.Employees;
this.Employees.PrimaryKey = new DataColumn[] { this.Employees.Columns["EmployeeID"] };
}
protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
//Prepare new row to add it in the DataSource
DataRow[] changedRows = this.Employees.Select("EmployeeID = " + editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["EmployeeID"]);
if (changedRows.Length != 1)
{
RadGrid1.Controls.Add(new LiteralControl("Unable to locate the Employee for updating."));
e.Canceled = true;
return;
}
//Update new values
Hashtable newValues = new Hashtable();
newValues["Country"] = (userControl.FindControl("TextBox7") as TextBox).Text;
newValues["City"] = (userControl.FindControl("TextBox8") as TextBox).Text;
newValues["Region"] = (userControl.FindControl("TextBox9") as TextBox).Text;
newValues["HomePhone"] = (userControl.FindControl("HomePhoneBox") as RadMaskedTextBox).Text;
newValues["BirthDate"] = (userControl.FindControl("BirthDatePicker") as RadDatePicker).SelectedDate.ToString();
newValues["TitleOfCourtesy"] = (userControl.FindControl("ddlTOC") as DropDownList).SelectedItem.Value;
newValues["Notes"] = (userControl.FindControl("TextBox1") as TextBox).Text;
newValues["Address"] = (userControl.FindControl("TextBox6") as TextBox).Text;
newValues["FirstName"] = (userControl.FindControl("TextBox2") as TextBox).Text;
newValues["LastName"] = (userControl.FindControl("TextBox3") as TextBox).Text;
newValues["HireDate"] = (userControl.FindControl("HireDatePicker") as RadDatePicker).SelectedDate.ToString();
newValues["Title"] = (userControl.FindControl("TextBox4") as TextBox).Text;
changedRows[0].BeginEdit();
try
{
foreach (DictionaryEntry entry in newValues)
{
changedRows[0][(string)entry.Key] = entry.Value;
}
changedRows[0].EndEdit();
this.Employees.AcceptChanges();
}
catch (Exception ex)
{
changedRows[0].CancelEdit();
Label lblError = new Label();
lblError.Text = "Unable to update Employees. Reason: " + ex.Message;
lblError.ForeColor = System.Drawing.Color.Red;
RadGrid1.Controls.Add(lblError);
e.Canceled = true;
}
}
protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
{
UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
//Create new row in the DataSource
DataRow newRow = this.Employees.NewRow();
//Insert new values
Hashtable newValues = new Hashtable();
newValues["Country"] = (userControl.FindControl("TextBox7") as TextBox).Text;
newValues["City"] = (userControl.FindControl("TextBox8") as TextBox).Text;
newValues["Region"] = (userControl.FindControl("TextBox9") as TextBox).Text;
newValues["HomePhone"] = (userControl.FindControl("HomePhoneBox") as RadMaskedTextBox).Text;
newValues["BirthDate"] = (userControl.FindControl("BirthDatePicker") as RadDatePicker).SelectedDate.ToString();
newValues["TitleOfCourtesy"] = (userControl.FindControl("ddlTOC") as DropDownList).SelectedItem.Value;
newValues["Notes"] = (userControl.FindControl("TextBox1") as TextBox).Text;
newValues["Address"] = (userControl.FindControl("TextBox6") as TextBox).Text;
newValues["FirstName"] = (userControl.FindControl("TextBox2") as TextBox).Text;
newValues["LastName"] = (userControl.FindControl("TextBox3") as TextBox).Text;
newValues["HireDate"] = (userControl.FindControl("HireDatePicker") as RadDatePicker).SelectedDate.ToString();
newValues["Title"] = (userControl.FindControl("TextBox4") as TextBox).Text;
//make sure that unique primary key value is generated for the inserted row
newValues["EmployeeID"] = (int)this.Employees.Rows[this.Employees.Rows.Count - 1]["EmployeeID"] + 1;
try
{
foreach (DictionaryEntry entry in newValues)
{
newRow[(string)entry.Key] = entry.Value;
}
this.Employees.Rows.Add(newRow);
this.Employees.AcceptChanges();
}
catch (Exception ex)
{
Label lblError = new Label();
lblError.Text = "Unable to insert Employees. Reason: " + ex.Message;
lblError.ForeColor = System.Drawing.Color.Red;
RadGrid1.Controls.Add(lblError);
e.Canceled = true;
}
}
protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
{
string iD = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["EmployeeID"].ToString();
DataTable employeeTable = this.Employees;
if (employeeTable.Rows.Find(iD) != null)
{
employeeTable.Rows.Find(iD).Delete();
employeeTable.AcceptChanges();
}
}
Why my insert/delete/update are only temporary and visible in the current session? How can I fix this to get insert/update/delete changing the data in the database?
Acknowledge that Rows.Add() or AcceptChanges() do NOT write anything to the underlying database. They only operate on the in-memory data structures such as DataTables and DataSets. To actually save changes, you must:
Either use TableAdapter.Update() method and supply your modified DataTable to it.
Use SqlCommand and manually execute UPDATE, INSERT and DELETE commands.
You must NOT call AcceptChanges() before sending your changes back to the database.

datagridview not showing numbers from MS Access

I have a datagrid view and it's datasource is MS Access(which have a datatype, currency, date/time, and numbers), It shows data in the database but doesn't show other data types, only words or any string, here is my code for adding rows
string[] rowData = new string[columnCount];
while (dr.Read())
{
for (int k = 0; k < columnCount; k++)
{
if (dr.GetFieldType(k).ToString() == "System.int32")
{
rowData[k] = dr.GetInt32(k).ToString();
}
if (dr.GetFieldType(k).ToString() == "System.String")
{
rowData[k] = dr.GetString(k);
}
}
dataGridView1.Rows.Add(rowData);
}
can you help me with this? thanks
Instead of using the code above, I use this code, and it works
private void Form6_Load(object sender, EventArgs e)
{
loadData();
}
private void loadData()
{
str = new OleDbConnectionStringBuilder();
str.Provider = "Microsoft.ace.Oledb.12.0";
str.DataSource = #"\\sisc-erelim\4_Printing\VTDB\DB\VirginiTEADB2.accdb";
con = new OleDbConnection(str.ConnectionString);
dataGridView1.DataSource = fillTable("Select* from Accountstbl");
dataGridView1.Columns["Password"].Visible = false;
dataGridView1.Columns["Picture"].Visible = false;
}
private DataTable fillTable(string sql)
{
DataTable datatable = new DataTable();
using (OleDbDataAdapter da = new OleDbDataAdapter(sql, con))
{
da.Fill(datatable);
}
return datatable;
}

Categories