I am writing a project in ASP.net which I have six text boxes to display the information of the next record in my database. And I also have a search button base on some selected field which will search out my first record in my database. I inserted the code for my first record into the search button event handler. The code is written below:
Using System.Data;
Using System.Data.OleDb;
Using System.IO;
OleDbconnection mycon = new OleDbconnection("");
protected void search_btn_Click(object sender, EventArgs e)
{
int i = 0;
DataTable dt;
String searchme = "select * from student where myclass = '" + txtclass.Text + "' and mytype = '" + txtclasstype.Text + "'";
OleDbCommand cmd = new OleDbCommand (searchme, mycon);
mycon.Open();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
if(dt.Rows.Count > 0)
{
i = 0;
txtsearbox.Text = dt.Rows[i]["Admin_no"].ToString();
txtsurname.Text = dt.Rows[i]["surname"].ToString();
txtfirstname.Text = dt.Rows[i]["firstname"].ToString();
txtothername.Text = dt.Rows[i]["othername"].ToString();
txtsex.Text = dt.Rows[i]["sex"].ToString();
Photo.ImageUrl = dt.Rows[i]["photo"].ToString();
// then I created a session to hold my dt.
Session["dt"] = dt;
}
mycon.Close();
}
The above code is working fine for my first record but where I am having problem is from my next button which is written as shown below:
protected void next_btn_Click(object sender, EventArgs e)
{
int rowIndex = 0;
rowIndex ++;
if(rowIndex <= dt.Rows.Count)
{
txtsearbox.Text = dt.Rows[rowIndex]["Admin_no"].ToString();
txtsurname.Text = dt.Rows[rowIndex]["surname"].ToString();
txtfirstname.Text = dt.Rows[rowIndex]["firstname"].ToString();
txtothername.Text = dt.Rows[rowIndex]["othername"].ToString();
txtsex.Text = dt.Rows[rowIndex]["sex"].ToString();
Photo.ImageUrl = dt.Rows[rowIndex]["photo"].ToString();
}
mycon.Close();
}
The error it shows is: There is no row at position 1.
Related
I'm trying to insert 5 records into a SQL Server database table from DataGridView using C#.
From my code it takes input of several records but insert only first record in database. Can anybody help me to save 5 records in database by a single click of save button?
Here is my code:
DataSet ds = new DataSet();
SqlConnection cs = new SqlConnection(#"Data Source=DELL-PC;Initial Catalog=Image_DB;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
BindingSource Input = new BindingSource();
DataView dview = new DataView();
private void Form1_Load(object sender, EventArgs e)
{
//create a DataGridView Image Column
DataGridViewImageColumn dgvImage = new DataGridViewImageColumn();
//set a header test to DataGridView Image Column
dgvImage.HeaderText = "Images";
dgvImage.ImageLayout = DataGridViewImageCellLayout.Stretch;
DataGridViewTextBoxColumn dgvId = new DataGridViewTextBoxColumn();
dgvId.HeaderText = "ID";
DataGridViewTextBoxColumn dgvName = new DataGridViewTextBoxColumn();
dgvName.HeaderText = "Name";
dataGridView1.Columns.Add(dgvId);
dataGridView1.Columns.Add(dgvName);
dataGridView1.Columns.Add(dgvImage);
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.RowTemplate.Height = 120;
dataGridView1.AllowUserToAddRows = false;
}
// button add data to dataGridView
// insert image from pictureBox to dataGridView
private void btn_Add_Click(object sender, EventArgs e)
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();
dataGridView1.Rows.Add(txt_UserID.Text, txt_Name.Text, img);
}
// browse image in pictureBox1 Click
private void pictureBox1_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
opf.Filter = "Choose Image(*.jpg; *.png; *.gif)|*.jpg; *.png; *.gif";
if (opf.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(opf.FileName);
}
}
private void btn_Save_Click(object sender, EventArgs e)
{
for (int i = 5; i < dataGridView1.Rows.Count; i++)
{
string col1 = dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col2 = dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col3 = dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string insert_sql = "INSERT INTO Input(UserID, UserName, PassImage) VALUES ('" + col1 + "','" + col2 + "','" + col3 + "')";
this.getcom(insert_sql);
}
MessageBox.Show("Record Added");
}
public SqlConnection GetSqlConnection() //connection function
{
string str_sqlcon = "Data Source=DELL-PC;Initial Catalog=Image_DB;Integrated Security=True";
SqlConnection mycon = new SqlConnection(str_sqlcon);
mycon.Open();
return mycon;
}
public void getcom(string sqlstr) //function for adding rows
{
SqlConnection sqlcon = this.GetSqlConnection(); // Watch out same string type as GetSQLConnection function
SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon);
sqlcom.ExecuteNonQuery();
sqlcom.Dispose();
sqlcon.Close();
sqlcon.Dispose();
}
The problem is within this " for " loop, you are not using the i in your for loop.
better try this one.
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string col1 = dataGridView1.Rows[i].Cells[0].Value.ToString();
string col2 = dataGridView1.Rows[i].Cells[1].Value.ToString();
string col3 = dataGridView1.Rows[i].Cells[2].Value.ToString();
string insert_sql = "INSERT INTO Input(UserID, UserName, PassImage) VALUES ('" + col1 + "','" + col2 + "','" + col3 + "')";
this.getcom(insert_sql);
}
change the code logic, if needed.
for (int i = 5; i < dataGridView1.Rows.Count; i++)
change this to for (int i = 0; i < dataGridView1.Rows.Count; i++)
You are assigning 5 to i so after one insert it will come out of the loop because i will become 6.
also include 'i' while specifying the datagridview row..else it will always point to one row and insert 5 rows but of same value
protected void GridviewArchived_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridviewArchived.PageIndex = e.NewPageIndex;
DisplayArchivedNews();
}
private void DisplayArchivedNews()
{
using (SqlConnection Con = new SqlConnection(connection1))
{
SqlCommand Cmd = new SqlCommand("udspGetArchivedNews", Con);
Cmd.CommandType = CommandType.StoredProcedure;
Con.Open();
Cmd.ExecuteNonQuery();
Con.Close();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(Cmd);
da.Fill(ds);
DataTable dt = ds.Tables[0];
int totalrecord = ds.Tables[0].Rows.Count;
GridviewArchived.DataSource = ds;
GridviewArchived.DataBind();
if (totalrecord > 0)
{
for (int i = 0; i < totalrecord; i++)
{
if( File.Exists(Server.MapPath("~//NewsFolder//Page1//" + GridviewArchived.DataKeys[i].Values["News_ID"].ToString().ToString() + (".PDF"))))
{
HyperLink link = new HyperLink();
link.Text = "Page1";
link.Target = "blank";
link.NavigateUrl = "~//NewsFolder//Page1//" + GridviewArchived.DataKeys[i].Values["News_ID"].ToString() + (".pdf");
GridviewArchived.Rows[i].Cells[2].Controls.Add(link);
}
}
}
}
}
Pagesize is 10, but when total record count is greater than pagesize it throws the following exception:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index.
What is the solution so that record will automatic goes to next pageindex?
For showing record of a gridview in paging there are two options for that
One you can add an object datasource with your gridview and show paging through it and the other option is to use jquery Datatable for paging.
My first attempt at performing a search on records in a database; I have a windows form project that upon load event displays a name from an Access database in a textbox. There is more to the form than this, but for practical purposes, I have buttons Previous, Next and a Find. Suppose I have 4 names in the database: 1-Atlas, 2-Benson, 3-Lane & 4-Smith. Form loads and Atlas is displayed. Do a search for Lane and then Lane is displayed on the form. Hit ‘Next’ and instead of Smith, Benson is displayed. I know why it is doing so: the search puts the record in the DataRow ‘returnedRow’ whereas all the records displayed on form load and ‘Previous’ & ‘Next’ are from the DataRow ‘dRow’. How do I retrieve a record from a query that is inside dRow?
OleDbConnection myConn = new OleDbConnection();
DataSet myDS;
int MaxRows = 0
int inc = 0;
private void Form1_Load(object sender, EventArgs e)
{
myConn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\Testing\TestDatabase.accdb";
myConn.Open();
myDS = new DataSet();
string sql = "SELECT * From Test";
OleDbDataAdapter myDA = new OleDbDataAdapter(sql, myConn);
myDA.Fill(myDS, "People");
NavigateRecords();
MaxRows = myDS.Tables["People"].Rows.Count;
myConn.Close();
}
private void NavigateRecords()
{
DataRow dRow = myDS.Tables["People"].Rows[inc];
txtName.Text = dRow.ItemArray.GetValue(1).ToString();
txtAddress.Text = dRow.ItemArray.GetValue(2).ToString();
txtCity.Text = dRow.ItemArray.GetValue(3).ToString();
txtState.Text = dRow.ItemArray.GetValue(4).ToString();
txtZip.Text = dRow.ItemArray.GetValue(5).ToString();
}
private void btnNext_Click(object sender, EventArgs e)
{
if (inc != MaxRows - 1)
{
inc++;
NavigateRecords();
}
else
{
MessageBox.Show("No more rows");
}
}
private void btnFind_Click(object sender, EventArgs e)
{
string searchFor = txtFind.Text;
int results = 0;
if (txtFind.Text.Trim() == "")
{
MessageBox.Show("Nothing to search for");
return;
}
DataRow[] returnedRows;
string expression;
expression = "Name1='" + searchFor + "'";
returnedRows = myDS.Tables["People"].Select(expression);
results = returnedRows.Length;
if (results > 0)
{
DataRow dr1;
dr1 = returnedRows[0];
txtName.Text = dr1[1].ToString();
txtAddress.Text = dr1[2].ToString();
txtCity.Text = dr1[3].ToString();
txtState.Text = dr1[4].ToString();
txtZip.Text = dr1[5].ToString();
}
else
{
MessageBox.Show("No record found");
}
}
You mean this part ... ?
private void NavigateRecords()
{
DataRow dRow = myDS.Tables["People"].Rows[inc];
txtName.Text = dRow[1];
txtAddress.Text = dRow[2];
txtCity.Text = dRow[3];
txtState.Text = dRow[4];
txtZip.Text = dRow[5];
}
i have a simple question
i have a form which contain two related combo boxes but i have problem in updating the second dropdown content
this is the code
private void DiaryForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'expensesDataSet.Item' table. You can move, or remove it, as needed.
// this.itemTableAdapter.Fill(this.expensesDataSet.Item);
using (OleDbConnection con = dbconn.dbconnection())
{
ds1 = new ExpensesDataSet();
string sql = "SELECT * From DiaryView";
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
da.Fill(ds1, "DiaryView");
NavigateRecords();
MaxRows = ds1.Tables["DiaryView"].Rows.Count;
//fill category combobox
string sqlcat = "SELECT * From Category";
catda = new System.Data.OleDb.OleDbDataAdapter(sqlcat, con);
catda.Fill(ds1, "Category");
catda.Update(ds1, "Category");
comboBox2.DataSource=ds1.Tables["Category"];
comboBox2.DisplayMember = "cat_name";
comboBox2.ValueMember="cat_id";
//comboBox1.Enabled = false;
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
using (OleDbConnection con = dbconn.dbconnection())
{
if (comboBox2.Items.Count > 0)
{
{
string cat = comboBox2.SelectedValue.ToString();
comboBox1.Enabled = true;
int catid = int.Parse(comboBox2.SelectedValue.ToString());
string sqlitem = "SELECT * From Item where cat_id = " + catid;
catda = new System.Data.OleDb.OleDbDataAdapter(sqlitem, con);
this.itemBindingSource.EndEdit();
catda.Fill(ds1, "Item");
catda.Update(ds1, "Item");
comboBox1.DataSource = ds1.Tables["Item"];
comboBox1.DisplayMember = "item_name";
comboBox1.ValueMember = "item_id";
}
}
}
}
there is two tables:
category(cat_id,cat_name)
item(item_id,item_name,cat_id)
what can i do??
plz help :)
If you want to clear the combobox, just do:
combobox1.Items.Clear();
It's as easy as that.
Here is my code to load the rbl:
protected void rblContentTypesGetAll_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(Global.conString))
{
using (SqlCommand cmd = new SqlCommand("contentTypeGetAll", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
//Clear Items before reloading
rblContentTypesGetAll.Items.Clear();
//Populate Radio button list
for (int i = 0; i < dt.Rows.Count; i++)
{
rblContentTypesGetAll.Items.Add(new ListItem(dt.Rows[i]["contentType"].ToString() + " - " + dt.Rows[i]["description"].ToString(),
dt.Rows[i]["ID"].ToString()));
}
//Set Default Selected Item by Value
rblContentTypesGetAll.SelectedIndex = rblContentTypesGetAll.Items.IndexOf(rblContentTypesGetAll.Items.FindByValue(((siteParams)Session["myParams"]).DefaultContentType.ToLower()));
}
Here is the HTML:
<asp:RadioButtonList id="rblContentTypesGetAll" OnLoad="rblContentTypesGetAll_Load" runat="server">
</asp:RadioButtonList>
Here is the form taking the submission:
protected void Submit_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(Global.conString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("contentPageInsert", con))
{
cmd.Parameters.Add("#title", SqlDbType.VarChar).Value = Global.SafeSqlLiteral(txtPage.Text, 1);
cmd.Parameters.Add("#contentTypeID", SqlDbType.VarChar).Value = rblContentTypesGetAll.SelectedValue;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
con.Close();
//Update Content Page Repeater
using (SqlCommand cmd = new SqlCommand("contentPageGetAll", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
Session["formProcessed"] = "Page added!";
Response.Redirect(redirectURL);
}
No matter which radio button I select, the value is always the same - first radio button. What am I doing incorrectly?
The reason, I think, is that the method that is populating radio button list clears and rebuilds on every postback so the by the time submit_click fires, the list has been rebuilt and the selection is lost. Try this,
protected void rblContentTypesGetAll_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
return;
}
var dt = new DataTable();
using (var con = new SqlConnection(Global.conString))
using (var cmd = new SqlCommand("contentTypeGetAll", con))
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
//Clear Items before reloading
rblContentTypesGetAll.Items.Clear();
//Populate Radio button list
for (int i = 0; i < dt.Rows.Count; i++)
{
rblContentTypesGetAll.Items.Add(new ListItem(dt.Rows[i]["contentType"].ToString() + " - " + dt.Rows[i]["description"].ToString(),
dt.Rows[i]["ID"].ToString()));
}
//Set Default Selected Item by Value
rblContentTypesGetAll.SelectedIndex = rblContentTypesGetAll.Items.IndexOf(rblContentTypesGetAll.Items.FindByValue(((siteParams)Session["myParams"]).DefaultContentType.ToLower()));
}