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";
Related
After searching for a solution for some time, I rely on you because I can't get out of it.
I have a DataGridView with the data source linked to a BindingSource.
The BindingSource data source is a DataTable object.
The dgv has the "Allow insertion" option enabled and my goal is to allow the user to enter by adding with submission on the last line and validate the data with RowValidate method.
I want to check, before insert, that a column is filled with data.
To allow insertion, I use the AddingNew method of BindingSource like this:
private void bsAnalisi_AddingNew(object sender, AddingNewEventArgs e)
{
DataGridViewRow dgvRow;
ANALISI_DL AnalisiDL;
//
if (dgvAnalisi.CurrentRow != null)
{
dgvRow = dgvAnalisi.CurrentRow;
//if ((Convert.ToInt32(dgvRow.Cells["ID"].Value) == 0))
if (dgvRow.Cells["ID"].Value == DBNull.Value)
{
Analisi = new ANALISI();
AnalisiDL = new ANALISI_DL();
Analisi.LOTTO = dgvRow.Cells["LOTTO"].Value == null ? string.Empty : dgvRow.Cells["LOTTO"].Value.ToString();
//some other columns
//I call a stored procedure
Analisi.ID = AnalisiDL.InsertAnalisi(Analisi);
//refresh the bindingsource
dgvDataBindings();
}
}
To refresh I use this method :
private void dgvDataBindings()
{
ANALISI_DL AnalisiDL;
//
AnalisiDL = new ANALISI_DL();
bsAnalisi.DataSource = AnalisiDL.GetAllAnalisi();
}
The insert operation goes well but I view a blank row at the bottom of the grid(under the new row).
In addition when I try to refresh the grid with the dgvDataBindings method (by a button) I get the error
System.InvalidOperationException: 'Operation failed. The cell value cannot be committed or uncommitted.'
Is it the correct way to insert a new row ?
I also tried with the CellEndEdit method of the DataGridView but the event fire before of RowValidation event.
EDIT
These are the methods i use to get and insert data and validate :
public DataTable GetAllAnalisi()
{
SqlConnection conn;
SqlDataAdapter sqlDa;
DataTable dt;
//
using (conn = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
conn.Open();
sqlDa = new SqlDataAdapter("SELECT * FROM ANALISI ORDER BY ID", conn);
dt = new DataTable();
sqlDa.Fill(dt);
}
return dt;
}
public int InsertAnalisi(ANALISI pAnalisi)
{
SqlConnection conn;
SqlCommand cmd;
string SQLString;
int result;
//
SQLString = "dbo.SP_INSERT_ANALISI";
using (conn = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
conn.Open();
using (cmd = new SqlCommand(SQLString, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#LOTTO", pAnalisi.LOTTO);
//some other columns
var returnParameter = cmd.Parameters.Add("#ReturnVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
result = Convert.ToInt32(returnParameter.Value);
}
}
return result;
}
private void dgvAnalisi_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
DataGridViewRow row;
row = dgvAnalisi.Rows[e.RowIndex];
if (row.IsNewRow) { return; }
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.OwningColumn.Name == "FK_SEDE")
{
if (cell.Value == null || string.IsNullOrEmpty(cell.Value.ToString()))
{
row.ErrorText = "Error";
e.Cancel = true;
}
}
}
}
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
I'm trying to make a windows application for Library Management.
I'm trying to bind the data generated by SQLQuery to comboBoxBranch, but its only showing --Select-- in the options. Is there anything wrong with following code?
private void Form1_Load(object sender, EventArgs e)
{
bindBranch();
}
private void bindBranch()
{
OleDbCommand SQLQuery = new OleDbCommand();
string sqlQueryString = "Select br_id from branch";
DataTable data = null;
SQLQuery.Connection = null;
OleDbDataAdapter dataAdapter = null;
try
{
SQLQuery.CommandText = sqlQueryString;
SQLQuery.Connection = database;
data = new DataTable();
dataAdapter = new OleDbDataAdapter(SQLQuery);
dataAdapter.Fill(data);
comboBoxBranch.DisplayMember = "br_id";
DataRow dr = data.NewRow();
dr[0] = "--Select--";
data.Rows.InsertAt(dr, 0);
comboBoxBranch.DataSource = data;
}
catch (Exception ex)
{
}
}
Is there anything else I need to add to some other pages to make this work?
You can bind data like this.
comboBoxBranch.DataSource = new BindingSource { DataSource = data };
comboBoxBranch.DisplayMember = "br_id";
comboBoxBranch.ValueMember = //> something else
my problem is like that: I have a C# application having datagridview which has some textboxes and comboboxes in its columns. All the columns get the data from a database. Textboxes are readonly. When i ask for values in each row, i get the last selected component's value (i.e. combobox' value because textboxes are readonly) as null.
For example:
I have 10 cells in a row. The comboboxes are at 7th, 8th and 9th indexes in a row, where indexes from 0 to 6 are texboxes. When i select 3 of them (in order of 7, 8, 9) i cannot get the cell value of 9.
row.Cells[7].Value is OK,
row.Cells[8].Value is OK, and
row.Cells[9].Value is null
When i select any two of them let say first 8 and then 7, i cannot get the cell value of 7.
row.Cells[8].Value is OK and
row.Cells[7].Value is null
When i select only one item let say 9, i got the cell value again null.
As a result i get the last selected DataGridViewComboBoxCell as null.
Can anyone help me in my problem please? Thanks for all your help.
Here is my code:
private void cmbVariable_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = sender as ComboBox;
BringQuery(cmb.SelectedItem.ToString());
}
private void BringQuery(string option)
{
SqlConnection conn = new SqlConnection("Server = 10.2.6.14; Database = TTS; uid = myuser; password = mypassword");
DataTable dt1 = new DataTable();
SqlCommand cmd1 = new SqlCommand("select Track_Number, Parking_Area, Mission_Number, Track_Info, Time, Direction, Explanation from Traffic_Run_Table where Op_Type=#myType", conn);
SqlCommand cmd2 = new SqlCommand("select * from Traffic_Track_Table", conn);
SqlCommand cmd3 = new SqlCommand("select * from Traffic_Driver order by Id_Number", conn);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
cmd1.Parameters.Add(new SqlParameter("myType", option));
try
{
conn.Open();
sda1.Fill(dt1);
dataGridView2.AutoGenerateColumns = false;
foreach (DataGridViewColumn col in dataGridView2.Columns)
{
col.DataPropertyName = col.Name;
}
dataGridView2.DataSource = dt1;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
DataGridViewComboBoxColumn cmbCol1, cmbCol2, cmbCol3;
SqlDataAdapter sda2 = new SqlDataAdapter(cmd2);
DataTable dt2 = new DataTable();
try
{
cmbCol1 = new DataGridViewComboBoxColumn();
cmbCol1.HeaderText = "Track 1";
cmbCol1.Name = "Track1";
cmbCol1.DataPropertyName = cmbCol1.Name;
cmbCol1.ValueType = typeof(int);
cmbCol1.Width = 50;
cmbCol2 = new DataGridViewComboBoxColumn();
cmbCol2.HeaderText = "Track 2";
cmbCol2.Name = "Track2";
cmbCol2.DataPropertyName = cmbCol2.Name;
cmbCol2.ValueType = typeof(int);
cmbCol2.Width = 50;
sda2.Fill(dt2);
dt2.Columns[0].ColumnName = "Track";
foreach (DataRow dr in dt2.Rows)
{
cmbCol1.Items.Add(Convert.ToInt32(dr["Track"]));
cmbCol2.Items.Add(Convert.ToInt32(dr["Track"]));
}
dataGridView2.Columns.Add(cmbCol1);
dataGridView2.Columns.Add(cmbCol2);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
SqlDataAdapter sda3 = new SqlDataAdapter(cmd3);
DataTable dt3 = new DataTable();
try
{
cmbCol3 = new DataGridViewComboBoxColumn();
cmbCol3.HeaderText = "Driver";
cmbCol3.Name = "Driver";
cmbCol3.DataPropertyName = cmbCol3.Name;
cmbCol3.ValueType = typeof(string);
cmbCol3.Width = 260;
sda3.Fill(dt3);
dt3.Columns[0].ColumnName = "Id";
dt3.Columns[1].ColumnName = "Driver";
dt3.Columns[2].ColumnName = "Mission";
foreach (DataRow dr in dt3.Rows)
{
cmbCol3.Items.Add(Convert.ToString(dr["Id"]).Trim() + " - " + Convert.ToString(dr["Dirver"]).Trim() + " - " + Convert.ToString(dr["Mission"]).Trim());
}
dataGridView2.Columns.Add(cmbCol3);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
public string CheckNull(object value, Type objType)
{
string retVal = string.Empty;
if (value == null || value.ToString() == " " || value.ToString() == "")
{
if (objType == typeof(int))
{
retVal = "0";
}
if (objType == typeof(string))
{
retVal = "-";
}
}
else
{
retVal = value.ToString();
}
return retVal;
}
private void Save_Click(object sender, EventArgs e)
{
SqlConnection connForSave = new SqlConnection("Server = 10.2.6.14; Database = TTS; uid = myuser; password = mypassword");
SqlCommand cmdForSave = new SqlCommand("insert into Traffic_Records values (#type, #trackNumber, #parkingArea, #missionNmb, #trackInfo, #time, #direction, #explanation, #track1, #track2, #driverId, #driverName, #driverMission, #date)", connForSave);
foreach (DataGridViewRow row in dataGridView2.Rows)
{
try
{
dataGridView2[7, row.Index].Selected = false;
dataGridView2[8, row.Index].Selected = false;
dataGridView2[9, row.Index].Selected = false;
connForSave.Open();
cmdForSave.Parameters.AddWithValue("type", CheckNull(cmbVairable.SelectedItem.ToString(), typeof(string)));
cmdForSave.Parameters.AddWithValue("trackNumber", Convert.ToInt16(CheckNull(row.Cells[0].Value, typeof(int))));
cmdForSave.Parameters.AddWithValue("parkingArea", CheckNull(row.Cells[1].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("missionNmb", Convert.ToInt16(CheckNull(row.Cells[2].Value, typeof(int))));
cmdForSave.Parameters.AddWithValue("trackInfo", CheckNull(row.Cells[3].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("time", CheckNull(row.Cells[4].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("direction", CheckNull(row.Cells[5].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("explanation", CheckNull(row.Cells[6].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("track1", Convert.ToInt16(CheckNull(row.Cells[7].Value, typeof(int))));
cmdForSave.Parameters.AddWithValue("track2", Convert.ToInt16(CheckNull(row.Cells[8].Value, typeof(int))));
string[] sArray = null;
if (string.Compare(CheckNull(row.Cells[9].Value, typeof(string)), "0") != 0 && string.Compare(CheckNull(row.Cells[9].Value, typeof(string)), "-") != 0)
{
sArray = row.Cells[9].Value.ToString().Split('-');
sArray[0] = sArray[0].Remove(sArray[0].Length - 2, 1);
sArray[1] = sArray[1].Remove(0, 1);
sArray[1] = sArray[1].Remove(sArray[1].Length - 2, 1);
sArray[2] = sArray[2].Remove(0, 1);
}
else
{
string temp = "0 - -";
sArray = temp.Split(' ');
}
cmdForSave.Parameters.AddWithValue("driverId", Convert.ToInt16(sArray[0]));
cmdForSave.Parameters.AddWithValue("driverName", sArray[1]);
cmdForSave.Parameters.AddWithValue("driverMission", sArray[2]);
cmdForSave.Parameters.AddWithValue("date", DateTime.Now);
cmdForSave.ExecuteNonQuery();
cmdForSave.Parameters.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n Line Number: " + ex.LineNumber());
}
connForSave.Close();
}
}
This happens because DataGridView does not commit user made changes instantly but only after row is validated (I think, may be wrong here). So after you selected last value and did not change row (so validate event has not fired) the value in combo box is still null.
To fix this add CurrentCellDirtyStateChanged (more info here MSDN event to your grid:
private void GridCurrentCellDirtyStateChanged(object sender, EventArgs e)
{
dgvAssignedProperties.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
and this why new values are committed right away.
How to display text on combo box in a DataGridView at run time from database?
For example, if am updating my text in database from combo box in DataGridView next time I want to display that text in combobox column.
sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
selectQueryString = "SELECT Code,CompanyName,FinancialYearStart,FinancialYearEnd,UserName,RoleP FROM CompanyInformation";
sqlDataAdapter = new SqlDataAdapter(selectQueryString, sqlConnection);
sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);
dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
dataGridView3.DataSource = bindingSource;
dataGridView3.Controls.Clear();
DataGridViewComboBoxColumn comboboxColumn = new DataGridViewComboBoxColumn();
comboboxColumn.Items.AddRange("Protected", "UnProtected");
comboboxColumn.HeaderText = "RoleP";
dataGridView3.Columns.Add(comboboxColumn);
private void button10_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
con.Open();
// if (dataGridView3.Columns.Count >= 4 && dataGridView3.Columns.Count < 10)
// {
int i = dataGridView3.Rows.Count;
int r = 0;
for (int s = 0; s < i; s++)
{
try
{
string Role = dataGridView3.Rows[s].Cells[0].Value.ToString();
int Cod = Convert.ToInt32(dataGridView3.Rows[s].Cells[1].Value.ToString());
if (Role != "")
{
SqlCommand cmd = new SqlCommand("update CompanyInformation SET RoleP=#Role where Code=#Cod", con);
cmd.Parameters.AddWithValue("#Cod", Cod);
cmd.Parameters.AddWithValue("#Role", Role);
r = cmd.ExecuteNonQuery();
}
}
catch
{
}
}
if (r >= 1)
{
MessageBox.Show("Update Successful");
SuperUser obj = new SuperUser();
this.Hide();
this.ParentForm.Hide();
}
You can go with this:
DataGridViewComboBoxColumn comboboxColumn = new DataGridViewComboBoxColumn();
comboboxColumn.Items.AddRange("Protected", "UnProtected");
comboboxColumn.HeaderText = "RoleP";
dataGridView3.Columns.Add(comboboxColumn);
After that check
foreach (DataGridViewRow row in dataGridView3.Rows)
{
(row.Cells[1] as DataGridViewComboBoxCell).Value = yourvalue;
}