At this line of code dr = dt.Rows[k]; I am getting the exception Object reference not set to an instance of an object. where I am going wrong?
public partial class EditEngClgList : Form
{
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);
dt1 = new DataTable();
da.Fill(dt1);
bs = new BindingSource();
bs.DataSource = dt1;
dataGridView1.DataSource = bs;
dataGridView1.Columns[1].Visible = false;
}
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]; //this datatable object I hae created in another function
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();
}
}
}
Thanks for any help
Place a breakpoint on that line - most likely the dt object is null.
To address the comment that k may be larger than Rows.Count, I would think if the problem was with k, you'd get an exception indicating the index is out of bounds (IndexOutOfBoundsException).
Related
I am working a project and i need to display on a form (frmCaterlogs) a list of items. I have successfully implimented a custom list using a user control & FlowLayOutPanel. However now i am stuck on how i can bind my caterlogs that sits on a sql database to my custom list: Here is my code. on the custome_list(CatList), i have 4 controls, Id, Titile, Description, Icon stored in database as binarydata in the sqldb. I am lost on how i can bind data to the custom list control that can look thought all the records in my database. Thanking you all in advace for your kind advices.
private void PopulateCatelog()// This code is triggered when frmcaterlogs loads.
{
int l;
string query = "SELECT * from ServicesCaterlogs";
SqlConnection con = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ListView Items = new ListView()
sda.Fill(dt);
l = dt.Rows.Count;
foreach(DataRow dr in dt.Rows) // This is where i am stuck
{
CatList iList = new CatList(dr["Item"].ToString());
iList.Title = dr;
}
CatList[] ListItem = new CatList[l];
//Loop though to check each item
for (int i = 0; i < ListItem.Length; i++)
{
ListItem[i] = new CatList();
ListItem[i].Title = fetch data for a list;
ListItem[i].Message = "fetch data for a lis";
ListItem[i].icon = Resources.Warning;
ListItem[i].IconBackground1 = Color.DarkGoldenrod;
if (FlowLayoutPanel.Controls.Count < 0)
{
FlowLayoutPanel.Controls.Clear();
}
else
{
FlowLayoutPanel.Controls.Add(ListItem[i]);
}
}
I got the desired result after altering the code as seen below
private void FrmCatalogs_Load(object sender, EventArgs e)
{
PopulateCatelog();
}
private void PopulateCatelog()
{
//Populate your listitem here
int l;
string query = "SELECT * from ServicesCaterlogs";
SqlConnection con = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
l = dt.Rows.Count;
foreach(DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["Item"].ToString());
ListViewItem des = new ListViewItem(dr["Item_Description"].ToString());
CatList[] ListItem = new CatList[l];
for (int i = 0; i < ListItem.Length - l +1 ; i++)
{
ListItem[i] = new CatList();
ListItem[i].Title = item.Text;
ListItem[i].Message = des.Text;
ListItem[i].icon = Resources.Warning;
ListItem[i].IconBackground1 = Color.DarkGoldenrod;
if (FlowLayoutPanel.Controls.Count < 0)
{
FlowLayoutPanel.Controls.Clear();
}
else
{
FlowLayoutPanel.Controls.Add(ListItem[i]);
}
}
}
}
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";
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;
}
I am trying to retrieve all names that was saved at the sql database
then suddenly I got the
nullreferenceexception was unhandled on filling up array - Object
reference not set to an instance of an object.
this was my code:
I got the error at the
imgName[i] = Convert.ToString(dt.Rows[i]["FinalImageName"]);
in that part, I'd like to fill imgName array all the name
how could i fix it?, help please
string c_string = "server=.\\sqlexpress;database=Blue;trusted_connection=true";
public static string ImageToShow;
private int NumOfFiles;
private string[] imgName;
SqlConnection c = new SqlConnection(c_string);
//SqlCommand cm = new SqlCommand(cmd,c);
private void frmMain_Load(object sender, EventArgs e) {
SqlConnection c = new SqlConnection(c_string);
try {
c.Open();
}
catch (SqlException ee) {
MessageBox.Show(ee.Message);
}
finally {
c.Close();
}
updateData();
}
private void updateData() {
SqlConnection c = new SqlConnection(c_string);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM FinalImages", c);
DataTable dt = new DataTable();
da.Fill(dt);
NumOfFiles = dt.Rows.Count;
for (int i = 0; i < dt.Rows.Count; i++) {
imgName[i] = Convert.ToString(dt.Rows[i]["FinalImageName"]);
}
}
You need to instantiate the imgName array .
private void updateData()
{
{
SqlConnection c = new SqlConnection(c_string);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM FinalImages", c);
DataTable dt = new DataTable();
da.Fill(dt);
NumOfFiles = dt.Rows.Count;
imgName = new string[NumOfFiles];
for (int i = 0; i < NumOfFiles; i++)
{
imgName[i] = Convert.ToString(dt.Rows[i]["FinalImageName"]);
}
}
}
That is because you have not specified the size of array... either specify size of array or use arraylist / generic list
Try this:
include namespace : using System.Collections.Generic;
string c_string = "server=.\\sqlexpress;database=Blue;trusted_connection=true";
public static string ImageToShow;
private int NumOfFiles;
//private string[] imgName;
List<string> imgName= new List<string>();
SqlConnection c = new SqlConnection(c_string);
//SqlCommand cm = new SqlCommand(cmd,c);
private void frmMain_Load(object sender, EventArgs e)
{
SqlConnection c = new SqlConnection(c_string);
try
{
c.Open();
}
catch (SqlException ee)
{
MessageBox.Show(ee.Message);
}
finally
{
c.Close();
}
updateData();
}
private void updateData()
{
SqlConnection c = new SqlConnection(c_string);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM FinalImages", c);
DataTable dt = new DataTable();
da.Fill(dt);
NumOfFiles = dt.Rows.Count;
for (int i = 0; i < dt.Rows.Count; i++)
{
// imgName[i] = Convert.ToString(dt.Rows[i]["FinalImageName"]);
imgName.Add(Convert.ToString(dt.Rows[i]["FinalImageName"]));
}
}
You haven't created an array, you have only created the variable that can hold the reference to the array.
Create the array once you know how many rows there are:
imgName = new string[dt.Rows.Count];
I am developing an online exam system project using ASP.NET (C#) & SQL Sever.
This is my code. I have a problem in implementing code for next & previous button. Please suggest me the answer. Thank you.
public partial class Default : Page
{
int count;
string ans;
int[] a=new int[5];
int t;
int ctr;
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
DateTime myDate;
DataTable dt = new DataTable();
DataRow dr;
public void Show()
{
Session["Answered"] = dt;
View v = this.View1;
Label l = default(Label);
l = (Label)v.FindControl("Label1");
l.Text = dt.Rows[ctr]["Serial"] + ".";
l = (Label)v.FindControl("Label2");
l.Text = dt.Rows[ctr]["question"].ToString();
RadioButtonList r = default(RadioButtonList);
r = (RadioButtonList)v.FindControl("RadioButtonList1");
r.Items.Clear();
r.Items.Add(dt.Rows[ctr]["choice1"].ToString());
r.Items.Add(dt.Rows[ctr]["choice2"].ToString());
r.Items.Add(dt.Rows[ctr]["choice3"].ToString());
r.Items.Add(dt.Rows[ctr]["choice4"].ToString());
r.SelectedIndex = Convert.ToInt32(dt.Rows[ctr]["selected"]);
Session["ctr"] = ctr;
}
protected void Timer1_Tick(object sender, System.EventArgs e)
{
DateTime mydate2 = DateTime.Now;
DateTime mydate3 = default(DateTime);
try
{
mydate3 = Convert.ToDateTime((myDate - mydate2).ToString());
this.Label5.Text = "Time Left: " + mydate3.ToShortTimeString();
}
catch (Exception ex)
{
this.Label5.Text = "Error Setting up the Timer. Contact Admin";
}
if (mydate3.ToShortTimeString() == "00:00:00")
{
int marks = 0;
Session["Answered"] = dt;
Response.Redirect("default3.aspx?marks=" + marks);
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
DateTime myDate = new DateTime();
myDate =Convert.ToDateTime(Request.Cookies["start"].Value);
if (!IsPostBack) {
this.MultiView1.ActiveViewIndex = 0;
conn.Open();
cmd.Connection = conn;
Random arbit = new Random();
for (int i = 0; i <= a.GetUpperBound(0); i++) {
t = arbit.Next(1, 10);
if (Array.IndexOf(a, t) == -1) {
a[i] = t;
} else {
goto X;
}
}
for (int i = 0; i <= 4; i++)
{
cmd.CommandText = "select * from test where Serial=" + a[i];
da.SelectCommand = cmd;
da.Fill(ds, "test");
}
conn.Close();
dt = new DataTable("Answered");
dt.Columns.Add("Serial", typeof(int));
dt.Columns.Add("question", typeof(string));
dt.Columns.Add("choice1", typeof(string));
dt.Columns.Add("choice2", typeof(string));
dt.Columns.Add("choice3", typeof(string));
dt.Columns.Add("choice4", typeof(string));
dt.Columns.Add("correct", typeof(string));
dt.Columns.Add("selected", typeof(int));
DataRow r = null;
foreach (DataRow r_loopVariable in ds.Tables["test"].Rows) {
r = r_loopVariable;
dr = dt.NewRow();
dr["Serial"] = dt.Rows.Count + 1;
dr["question"] = r["question"];
dr["choice1"] = r["choice1"];
dr["choice2"] = r["choice2"];
dr["choice3"] = r["choice3"];
dr["choice4"] = r["choice4"];
dr["correct"] = r["correct"];
dr["selected"] = -1;
dt.Rows.Add(dr);
}
Session["Answered"] = dt;
Show();
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
Session["ctr"] = ctr;
Session["Answered"] = dt;
Session["ctr"] = ctr;
ctr += 1;
Show();
if (ctr == 4)
{
this.btnNext.Enabled = false;
}
this.btnPrev.Enabled = true;
}
protected void btnPrev_Click(object sender, EventArgs e)
{
Session["ctr"] = ctr;
Session["Answered"] = dt;
ctr = ctr - 1;
if (ctr == 0)
{
this.btnPrev.Enabled = false;
}
Session["ctr"] = ctr;
this.btnNext.Enabled = true;
Show();
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList1.SelectedIndexChanged += new EventHandler(RadioButtonList1_SelectedIndexChanged);
Session["Answered"] = dt;
}
protected void btnShowMarks_Click(object sender, EventArgs e)
{
int marks = 0;
Session["Answered"] = dt;
Response.Redirect("default3.aspx?marks=" + marks);
Session["marks"] = dt;
int []b=new int[6];
foreach (int c in b)
{
RadioButtonList1.SelectedIndex.ToString();
}
}
}
I would suggest you to use the Wizard control.
Here are some examples:
http://msdn.microsoft.com/en-us/magazine/cc163894.aspx
http://www.codeproject.com/KB/aspnet/Wizard_Control.aspx
Since you seem to develop a wizard-like form did you consider using the Wizard control.
You can Fetch random data from DB and store it in a dataset. Then there you can get questions in usual manner. Then you can fetch questions using a variable which will store the question number to get previous and next questions. If user clicks on Previous then variable - 1 also +1 if next