index was out of range. must be nonnegative and less than the size of the collection. parameter name: index [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Guys I really need for your help. I am getting an error for the above title. All trying to do is when datagridview is click it should display selected record into the text box as well as open it new form. Here is my code.
using System.Data;
using System.Data.SqlClient;
namespace DataGridview
{
public partial class FrmDataGrid : Form
{
SqlConnection con = new SqlConnection("ConnectionString");
public FrmDataGrid()
{
InitializeComponent();
}
private void FrmDataGrid_Load(object sender, EventArgs e)
{
try {
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM UserData";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
textBox1.Text = dataGridView1.SelectedRows[0].Cells["UserID"].Value.ToString();
textBox2.Text = dataGridView1.SelectedRows[1].Cells["FullName"].Value.ToString();
textBox3.Text = dataGridView1.SelectedRows[2].Cells["Username"].Value.ToString();
textBox4.Text = dataGridView1.SelectedRows[3].Cells["UserPassword"].Value.ToString();
textBox5.Text = dataGridView1.SelectedRows[4].Cells["UserRole"].Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
FrmUpdate FormUpdate = new FrmUpdate();
FormUpdate.ShowDialog();
}
}
}

You're trying to fetch 5 rows without even checking that 5 rows exists in the result of your db query. I think you're trying to fetch 5 columns of a row, so use the following code for your requirement:
textBox1.Text = dataGridView1.SelectedRows[0].Cells["UserID"].Value.ToString();
textBox2.Text = dataGridView1.SelectedRows[0].Cells["FullName"].Value.ToString();
textBox3.Text = dataGridView1.SelectedRows[0].Cells["Username"].Value.ToString();
textBox4.Text = dataGridView1.SelectedRows[0].Cells["UserPassword"].Value.ToString();
textBox5.Text = dataGridView1.SelectedRows[0].Cells["UserRole"].Value.ToString();

You are most likely selecting a row that is out of range, during one of these calls:
dataGridView1.SelectedRows[0]

Related

C# datagridview shound not change until there is a result

Recently i developed a search function, but i want when a user inputs something on the textbox the datagridview to not go blank but instead to show the data that it already has and when the result is found than only show the result. Because now when i type anything on the search textbox the dgv immediately goes blank.
Here is my code:
private void txtBarkod_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtBarkod.Text)) {
resetTxTboxes();
}
MySqlConnection connection = Connection.prevzemiKonekcija();
try {
connection.Open();
MySqlCommand command;
MySqlDataAdapter adapter;
DataTable tabela;
string query = "SELECT * FROM artikli WHERE barcode like '%" + txtBarkod.Text + "%'";
command = new MySqlCommand(query, connection);
adapter = new MySqlDataAdapter(command);
tabela = new DataTable();
adapter.Fill(tabela);
dataGridView1.DataSource = tabela;
if (txtBarkod.Text == "") {
ShowDgV();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
}
Reset/Rebind the datasource of your datagridview only if you found something in your db.
if(tabela.Rows.Count > 0)
{
dataGridView1.DataSource = tabela;
}

Displaying results from a database using a dropdownmenu

This is a question about how to retrieve data from a database using a dropdownlist in ASP.NET .(I apologize for the spaghetti code that I have posted here, however it is the easiest to write and this is just a concept I'm trying to understand).
I'm always a little queasy about asking questions here, but, this is something I just can't solve for some reason. I've already asked my peers and Google'd for help and insight regarding this matter and I have come up empty-handed.
So, let me get into the problem.
I have made a simple page with a dropdownlist, a label, and an image control.
The dropdownlist is populated with entries from a database I've built.
The code follows:
public partial class view_products : System.Web.UI.Page
{
private static SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
private SqlCommand sqlcomm = new SqlCommand("sp_itemTable", sqlconn);
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
sqlcomm.CommandType = CommandType.StoredProcedure;
//the query is SELECT * FROM <DataBase Name>
sqlcomm.Parameters.Add("#query", SqlDbType.Int).Value = 5;
try
{
if (sqlconn.State != ConnectionState.Open)
{
SqlConnection.ClearAllPools();
sqlconn.Open();
}
dt.Load(sqlcomm.ExecuteReader());
sqlconn.Close();
}
catch (Exception exception)
{
Response.Write(exception.Message);
}
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "pname";
DropDownList1.DataValueField = "pid";//pid is PK in my DataBase Table
DropDownList1.DataBind();
}
The list populates after the page is loaded.
Now, I want to take the value (ie, pid) selected from the dropdownlist and use it to get records from the database.
The code follows:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
sqlcomm.CommandType = CommandType.StoredProcedure;
sqlcomm.Parameters.Add("#pid", SqlDbType.BigInt).Value = int.Parse(DropDownList1.SelectedValue);
sqlcomm.Parameters.Add("#query", SqlDbType.Int).Value = 4;
try
{
if (sqlconn.State != ConnectionState.Open)
{
SqlConnection.ClearAllPools();
sqlconn.Open();
}
dt.Load(sqlcomm.ExecuteReader());
sqlconn.Close();
}
catch (Exception exception)
{
Response.Write(exception.Message);
}
if (dt.Rows.Count > 0)
{
Label1.Text = dt.Rows[0]["pname"].ToString();
Image1.ImageUrl = dt.Rows[0]["pimage"].ToString();
}
else
Response.Write("Data Retrieval Failed!");
}
}
Here lies the problem.
I can't seem to get this part of the code working. The data isn't displayed. Even though autopostback is enabled in the dropdownlist. And I think I've developed code myopia from working on this for some time now.
Any helpful suggestions would be greatly appreciated.
Thanks for your time.

using datagridView, exception occurs for INSERT command, while deletion and updation are working perfectly in C# using access database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Using save button in my form, all operations (update, delete) working perfectly except INSERT command. Help me out of this...
public partial class frmeditaccess : Form
{
string table = "master";
OleDbDataAdapter da;
OleDbCommandBuilder cb;
DataTable dt;
OleDbConnection conn;
string query;
public frmeditaccess()
{
InitializeComponent();
}
private void btload_Click(object sender, EventArgs e)
{
try
{
conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" + #"Data source= C:\Users\ViPuL\Documents\Visual Studio 2010\Projects\feedback#MERI\feedback#MERI\bin\feedback.mdb";
query = string.Format("SELECT * FROM {0}", table);
da = new OleDbDataAdapter(query, conn);
dt = new DataTable();
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
}
private void btsave_Click(object sender, EventArgs e)
{
try
{
cb = new OleDbCommandBuilder(da);
da.Update(dt); //here update, delete are working. Only, Insert throws exception of syntax error in INSERT command.
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
}
This may be due to reserved keyword used as column name, try by specifying QuotePrefix and QuoteSuffix as below
cb = new OleDbCommandBuilder(da);
cb.QuotePrefix = "[";
cb.QuoteSuffix = "]";
da.Update(dt);

How to use textbox lost-focus event [duplicate]

This question already has answers here:
Jquery function when a textbox loses focus
(4 answers)
Closed 9 years ago.
I have a textbox and I want to check the data from database for duplicate record when I lost the cursor from textbox.
So please help me how to solve this.
VIPUL,
I created the following example for you. This can help you to check the data from the textbox with the data in the Database.
private void textBox1_Leave(object sender, EventArgs e)
{
//Put the value to be checked with the Database in a Variable.
var valueToCheck = textBox1.Text;
//Create connection with the database.
var sqlConn = new SqlConnection("Connection String to Database");
//Create dataset instance to fill with the return results from the Database.
var ds = new DataSet();
//Create SqlCommand to be execute on the database.
var cmd = new SqlCommand("SELECT * FROM TABLE WHERE 'field to be checked' = " + valueToCheck, sqlConn);
//Create SqlDataAdapter
var da = new SqlDataAdapter(cmd);
ds.Clear();
try
{
da.Fill(ds);
}
catch (Exception ex)
{
}
foreach (DataRow row in ds.Tables[0].Rows)
{
//do you stuff here.
}
}
I hope this helps!
This might fix your issue:
<asp:TextBox ID="textBox1" runat="server" onblur="Your Function"></asp:TextBox>

C# My counter does not work [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Hi can anyone help I am not sure why my counter in my button next is not working sorry about all the other code. I want to build run through data in my database by using a counter. If there is an easier way to do it that will also work.
public partial class _Default : System.Web.UI.Page
{
int iDefualt = 2;
int iMainCounter = 0;
SqlConnection con1 = new SqlConnection("Data Source=EON;Initial Catalog=DW2;Persist Security Info=True;User ID=Kapow;Password=Kapow");
DataTable dt = new DataTable();
public void Page_Load(object sender, EventArgs e)
{
con1.Open();
SqlDataReader myReader = null;
//SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);
SqlCommand myCommand = new SqlCommand(sNavigate(0), con1);
/SELECT * FROM tblDW2 WHERE [User]='Petrus'
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtbxDaywords.Text = (myReader["Dayword"].ToString());
}
con1.Close();
iMainCounter = iDefualt;
// "Daywords\t" + "\n" + DateTime.Now.ToString();
}
public string sNavigate(int iNavNum)
{
int iNavigate;
if (iNavNum != 0)
{
iNavigate = iNavNum;
}
else
{
iNavigate = iDefualt;
}
return "SELECT * FROM (SELECT Dayword, ROW_NUMBER() OVER (ORDER BY Dayword) AS Rownumber FROM tblDW2 WHERE [User]='Petrus' ) results WHERE results.Rownumber = "+ iNavigate.ToString();
}
protected void btnNext_Click1(object sender, EventArgs e)
{
iMainCounter++;
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(sNavigate(iMainCounter), con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtbxDaywords.Text = (myReader["Dayword"].ToString());
}
con1.Close();
}
}
As per the ASP.NET Page Life cycle when ever you have any variable initialized in any of the events, may it be page load or any other event. that initialization is specific to the user
and will be re-initialized as soon as the event gets fired.
Solution:
If you are looking forward to hold the counter globally (Not specific to a user): Use application variable to hold the counter value
If you are looking forward to hold the counter specific to a user (for specific user through out the application): use Session to hold the counter Value
Please let me know if you would need a sample code so that I can provide.
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["Incrementer"] == null)
{
Session["Incrementer"] = "1";
}
else
{
int incrementer = Convert.ToInt32(Session["incrementer"].ToString()) + 1;
Session["incrementer"] = incrementer.ToString();
}
Label1.Text = Session["incrementer"].ToString();
}
}
If you don't store somewhere your counter it will be resetted after a PageLoad or a PostBack
Web page are stateless
you can use ViewState o SessionState
anyway if you dont put the counter initilization inside an
If(!IsPostBack)
{
iMainCounter = iDefualt;
}
everytime it will be resetted
In this way you count will be always 2 because you set it in the page load event, and the page load event to check for Ispostback so it will always re initialize to be equal iDefault.
so you should set the iDefault in not post back validation
if(!Page.IsPostBack)
{
iMainCounter = iDefault;
}
Another problem is the iMainCounter not set to static, so each transaction will re-initialize it, so use static int iMainCounter = 0

Categories