Combobox empty and doesnt dropdown - c#

I created a combobox column in a datagridview. The problem is my combobox is empty, blank, and doesn't dropdown when i click on it. When i use the debuger, every properties and value are ok and the items exists and are link to the combobox. Please help me :(
Code : `
public Repair()
{
Main pp = new Main();
InitializeComponent();
this.label4.Text = pp.label3.Text;
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE FComponent IS NOT NULL";
}
else
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
/**ArrayList list1 = new ArrayList(); //{ "C-C", "C-O", "Absence composant", "Mauvaise valeur", "Mauvais sens", "Mauvais composant" };
list1.Add("C-C");
list1.Add("C-O");**/
List<string> list1 = new List<string> { ("C-C"), ("C-O") };
combo.HeaderText = "FaultCodeByOp";
combo.DataPropertyName = "FaultCodeByOp";
combo.DropDownWidth = 120;
combo.FlatStyle = FlatStyle.Flat;
combo.Width = 90;
combo.DataSource = list1;
dataGridView1.Columns.AddRange(combo);
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = true;
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for(int i=0;i<4;i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
foreach (DataGridViewRow row in dataGridView2.Rows)
{
for(int i=0;i<3;i++)
{
dataGridView2.Columns[i].ReadOnly = true;
}
}
}
/**private DataTable GetDescriptionTable()
{
DataTable l_dtDescription = new DataTable();
l_dtDescription.Columns.Add("FaultCodeByOp", typeof(string));
l_dtDescription.Rows.Add("C-O");
l_dtDescription.Rows.Add("C-C");
l_dtDescription.Rows.Add("Absence de composant");
l_dtDescription.Rows.Add("Mauvais composant");
l_dtDescription.Rows.Add("Mauvais sens");
l_dtDescription.Rows.Add("Mauvaise valeur");
return l_dtDescription;
}**/
private void textBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
string Var1 = textBox1.Text;
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailAndPass WHERE BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE SerialNum LIKE #SerialNum AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE SerialNum LIKE #SerialNum And FComponent IS NOT NULL";
}
}
else
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailOnly WHERE (BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent) AND ReportingOperator IS NULL ";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL ";
command1.CommandText = "SELECT DISTINCT Machine, BoardName, BoardNumber FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
}
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
}
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.IsCurrentRowDirty)
{
dataGridView1.Rows[e.RowIndex].Cells[6].Value = true;
}
}
private void metroButton1_Click(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells[6].Value != null) && (bool)row.Cells[6].Value)
{
SqlCommand command = maConnexion.CreateCommand();
command = new SqlCommand("update FailAndPass set FaultCodeByOp=#Fault, RepairingDate=#RD, RepairingTime = #RT, ReportingOperator=#RO WHERE SerialNum=#Serial", maConnexion);
command.Parameters.AddWithValue("#Fault", row.Cells[4].Value != null ? row.Cells[4].Value : DBNull.Value);
command.Parameters.AddWithValue("#RD", DateTime.Today.ToString("d"));
command.Parameters.AddWithValue("#RT", row.Cells[5].Value != null ? row.Cells[5].Value : DBNull.Value);
command.Parameters.AddWithValue("#RO", this.label4.Text);
command.Parameters.AddWithValue("#Serial", this.textBox1.Text);
command.ExecuteNonQuery();
}
}
maConnexion.Close();
this.Hide();
Repair rep = new Repair();
rep.Show();
}
private void metroButton2_Click(object sender, EventArgs e)
{
this.Hide();
Main ff = new Main();
ff.Show();
}
/**private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex > -1)
{
// Bind grid cell with combobox and than bind combobox with datasource.
DataGridViewComboBoxCell l_objGridDropbox = new DataGridViewComboBoxCell();
// Check the column cell, in which it click.
if (dataGridView1.Columns[e.ColumnIndex].Name.Contains("FaultCodeByOp"))
{
// On click of datagridview cell, attched combobox with this click cell of datagridview
dataGridView1[e.ColumnIndex, e.RowIndex] = l_objGridDropbox;
l_objGridDropbox.DataSource = GetDescriptionTable(); // Bind combobox with datasource.
l_objGridDropbox.ValueMember = "FaultCodeByOp";
l_objGridDropbox.DisplayMember = "FaultCodeByOp";
}
}
}**/
}`

It seems that setting the DataGridViewComboBoxColumn to ReadOnly evokes this error in the loop:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < 4; i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
I am trying to find out why exactly..... for now avoid setting it to ReadOnly with a simple if clause:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < 4; i++)
{
if (!(dataGridView1.Columns[i] is DataGridViewComboBoxColumn))
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
}
EDIT:
The Problem seems to be dataGridView1.Columns[0]. This column does not like it to be set with values or to be set to ReadOnly. It also seems not to have any name (tested it) which is very weird. Nontheless, if you start your loop at 1 the error will go away and you can have even your DataGridViewComboBoxColumn to be set to ReadOnly = true without the if clause:
for (int i = 1; i < 4; i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}

Okay guys. I've done a new test.
Here is my test code :
combo.DataSource = list1;
if(combo.IsDataBound)
{
MessageBox.Show("TRUE");
}
else
{
MessageBox.Show("FALSE");
}
It seems that combo.datasource = list1 have all my value ("C-C" and "C-O"). But when i launch the debugger or launch the application, the messagebox which appear is the second one where combo.isdatabound = false. Normally, it should be True?

Related

GridView_RowUpdating method doesn't works in my asp.net project

I have an asp.net project, in which columns in GridView adding manually by button click, here's the method:
protected void addVacations_Click(object sender, EventArgs e)
{
using (var conn = new NpgsqlConnection(connStr))
{
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("insert into vacations(id,name,date,nodes) values(DEFAULT, #imya, #data, #primVac)", conn);
cmd.Parameters.Add(new NpgsqlParameter("#imya", imya.Text));
cmd.Parameters.Add(new NpgsqlParameter("#data", data.Text));
cmd.Parameters.Add(new NpgsqlParameter("#primVac", primVac.Text));
cmd.ExecuteNonQuery();
Response.Redirect(Request.RawUrl);
}
}
I have two others buttons, that adding change GridView's columns by clicking them.
Now i have to add opportunity to change them online by clients. Here's the GridView code:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="id" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" Width="1650px" AutoGenerateDeleteButton="True" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" OnRowEditing="GridView1_RowEditing" AutoGenerateEditButton="True" >
Here's GridView1_RowUpdating method:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int ID5 = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string name = (row.FindControl("name") as TextBox).Text;
string date = (row.FindControl("date") as TextBox).Text;
string prim = (row.FindControl("nodes") as TextBox).Text;
string constr = ConfigurationManager.ConnectionStrings["postgresConnectionString"].ConnectionString;
using (NpgsqlConnection cn = new NpgsqlConnection(constr))
{
string query = "UPDATE vacations SET name=#name,date=#date,nodes=#prim Where id=#ID5";
NpgsqlCommand cmd = new NpgsqlCommand(query, cn);
cmd.Parameters.Add("#name", NpgsqlDbType.Varchar).Value = name;
cmd.Parameters.Add("#date", NpgsqlDbType.Varchar).Value = date;
cmd.Parameters.Add("#nodes", NpgsqlDbType.Varchar).Value = prim;
cmd.Parameters.Add("#id", NpgsqlDbType.Integer).Value = ID5;
cn.Open();
cmd.ExecuteNonQuery();
}
}
Right now i have next error when trying to change rows:
Server error in the application '/'.
The object reference does not point to an instance of the object.
Description: An unhandled exception occurred during the execution of the current web request. Examine the stack trace for more information about this error and the code snippet that caused it.
Exception Information: System.NullReferenceException: The object reference does not point to an instance of the object.
Source error:
Line 361: GridViewRow row = GridView1.Rows[e.RowIndex];
Line 362: int ID5 = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
Line 363: string name = (row.FindControl("name") as TextBox).Text;
The problem exactly in Line 363
I think the problem in my string, if be exact here:
string name = (row.FindControl("name") as TextBox).Text;
string date = (row.FindControl("date") as TextBox).Text;
string prim = (row.FindControl("nodes") as TextBox).Text;
So i need help how to correctly declare my strings? Or what wrong in my code.
Update. Here is my column details, all three buttons:
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = null;//надо удалить текущие колонны (columns)
GridView1.DataBind();
for (int i = 0; GridView1.Columns.Count > i;)
{
GridView1.Columns.RemoveAt(i);
}
using (var conn = new NpgsqlConnection(connStr))
{
conn.Open();
bf1.HeaderText = "Направление деятельности";
bf1.DataField = "lineofbusiness";
bf1.ReadOnly = true;
bf1.SortExpression = "Napr";
bf2.HeaderText = "Объект";
bf2.DataField = "object";
bf2.SortExpression = "Obj";
bf3.HeaderText = "Мероприятия";
bf3.DataField = "events";
bf3.SortExpression = "Merop";
bf4.HeaderText = "Срок";
bf4.DataField = "deadline";
bf4.SortExpression = "Srok";
bf5.HeaderText = "Примечания";
bf5.DataField = "nodes";
bf5.SortExpression = "Prim";
GridView1.Columns.Add(bf1);
GridView1.Columns.Add(bf2);
GridView1.Columns.Add(bf3);
GridView1.Columns.Add(bf4);
GridView1.Columns.Add(bf5);
NpgsqlCommand cmd = new NpgsqlCommand();
NpgsqlDataAdapter sqlDa = new NpgsqlDataAdapter("SELECT id, lineofbusiness, object, events, deadline, nodes FROM mainpage where executor = '" + (string)Session["Name"] + "' ", conn);
//NpgsqlDataAdapter sqlDa1 = new NpgsqlDataAdapter("SELECT lineofbusiness, object, events, deadline, nodes FROM mainpage where executor = '" + curentExec + "' ", conn); //показ по исполнителю(раб код)
DataTable dtbl = new DataTable();
sqlDa.Fill(dtbl);
GridView1.DataSource = dtbl;
GridView1.DataBind();
Panel2.Visible = false;
Panel1.Visible = true;
Panel3.Visible = false;
//conn.Close(); //надо ли?
}
}
protected void Button2_Click(object sender, EventArgs e)
{
GridView1.DataSource = null;//надо удалить текущие колонны (columns)
GridView1.DataBind();
for (int i = 0; GridView1.Columns.Count > i;)
{
GridView1.Columns.RemoveAt(i);
}
using (var conn = new NpgsqlConnection(connStr))
{
conn.Open();
bf1.HeaderText = "Номер";
bf1.DataField = "id";
bf1.ReadOnly = true;
bf1.SortExpression = "11";
//bf2.HeaderText = "ФИО";
//bf2.DataField = "name";
//bf2.SortExpression = "22";
bf3.HeaderText = "Место";
bf3.DataField = "place";
bf3.SortExpression = "33";
bf4.HeaderText = "Цель";
bf4.DataField = "target";
bf4.SortExpression = "44";
bf5.HeaderText = "Срок";
bf5.DataField = "date";
bf5.SortExpression = "44";
bf6.HeaderText = "Результат";
bf6.DataField = "result";
bf6.SortExpression = "44";
GridView1.Columns.Add(bf1);
GridView1.Columns.Add(bf2);
GridView1.Columns.Add(bf3);
GridView1.Columns.Add(bf4);
GridView1.Columns.Add(bf5);
GridView1.Columns.Add(bf6);
NpgsqlCommand cmd = new NpgsqlCommand();
//NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT * FROM trips", conn);
NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT id, place, target, date, result FROM trips where name = '" + (string)Session["Name"] + "' ", conn);
DataTable dtblvac = new DataTable();
sqlDavac.Fill(dtblvac);
GridView1.DataSource = dtblvac;
GridView1.DataBind();
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = true;
}
}
protected void Button3_Click(object sender, EventArgs e)
{
GridView1.DataSource = null;//надо удалить текущие колонны (columns)
GridView1.DataBind();
for (int i = 0; GridView1.Columns.Count > i;)
{
GridView1.Columns.RemoveAt(i);
}
using (var conn = new NpgsqlConnection(connStr))
{
conn.Open();
bf1.HeaderText = "Номер";
bf1.DataField = "id";
bf1.ReadOnly = true;
bf1.SortExpression = "NomerVac";
//bf2.HeaderText = "ФИО";
//bf2.DataField = "name";
//bf2.SortExpression = "NameVac";
bf3.HeaderText = "Дата";
bf3.DataField = "date";
bf3.SortExpression = "DataVac";
bf4.HeaderText = "Примечания";
bf4.DataField = "nodes";
bf4.SortExpression = "PrimVac";
GridView1.Columns.Add(bf1);
GridView1.Columns.Add(bf2);
GridView1.Columns.Add(bf3);
GridView1.Columns.Add(bf4);
NpgsqlCommand cmd = new NpgsqlCommand();
//NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT * FROM vacations", conn);
NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT id, date, nodes FROM vacations where name = '" + (string)Session["Name"] + "' ", conn);
DataTable dtblvac = new DataTable();
sqlDavac.Fill(dtblvac);
GridView1.DataSource = dtblvac;
GridView1.DataBind();
Panel1.Visible = false;
Panel2.Visible = true;
Panel3.Visible = false;
}
}

how to display the datavaluefield of selected items in different listbox in asp.net

I have 3 listboxes.The listbox fetches two values by code-datatextfield and datavaluefield. 1st listbox transfers the datatextfield items from 1st listbox to 2nd listbox.i want to transfer the datavaluefield of selected 1st listbox items to 3rd listbox.
if (ListBox3.SelectedIndex >= 0
{
for (int i = 0; i < ListBox3.Items.Count; i++)
{
if (ListBox3.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox3.Items[i]))
{
arraylist1.Add(ListBox3.Items[i]);
Session["value"] = ListBox3.Items[i];
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
{
ListBox2.Items.Add(((ListItem)arraylist1[i]));
}
ListBox3.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
}
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where paramtext='" + Session["value"] + "'", con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "param";
//ListBox3.DataValueField = "param";
ListBox1.DataBind();
}
for listbox 3
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where pname='" + this.DropDownList1.SelectedValue + "'" ,con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox3.DataSource = ds.Tables[0];
ListBox3.DataTextField = "paramtext";
ListBox3.DataValueField = "param";
ListBox3.DataBind();
}
}
But i want to display the datavaluefield of the items that are selected from listbox3 to listbox1
Since you want to show DataTextField value and DataValueField value from one listbox into 2 different listbox. I suggest you to use a different approach. This will also reduce usage of 2nd database call.
Try following:-
if (ListBox3.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox3.Items.Count; i++)
{
if (ListBox3.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox3.Items[i]))
{
arraylist1.Add(ListBox3.Items[i]);
//Session["value"] = ListBox3.Items[i]; no need of this
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (ListBox2.Items.FindByText(((ListItem)arraylist1[i]).Text)==null)
{
//since you already have text and value field values in arrayList. Use them
ListBox2.Items.Add(new ListItem(((ListItem)arraylist1[i]).Text));
}
if (ListBox1.Items.FindByText(((ListItem)arraylist1[i]).Text)==null)
{
ListBox1.Items.Add(new ListItem((ListItem)arraylist1[i]).Value));
}
ListBox3.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
}
/* This database call can be removed
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where paramtext='" + Session["value"] + "'", con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "param";
//ListBox3.DataValueField = "param";
ListBox1.DataBind();
}*/

How to get a new row from datatable for every click event for window from c#

i am having five rows in datatable i should get each row for every click event from datatable in windowform C# ?? I am using following code it works for only first row i.e getting only first record for every click event but i need each new row for every click event
private void Calculate_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
con.Open();
SqlCommand cmd3 = new SqlCommand("Select top " + que + " * from Samplebox", con);
SqlDataAdapter sdr = new SqlDataAdapter();
sdr.SelectCommand = cmd3;
sdr.Fill(ds, "Samplebox");
DataTable dt = new DataTable();
dt = ds.Tables["Samplebox"];
int i=+0;
if (i < ds.Tables[0].Rows.Count - 1 )
{
i++;
label3.Text = ds.Tables[0].Rows[i]["BoxIDPK"].ToString();
label4.Text = ds.Tables[0].Rows[i][Box Name""].ToString();
if (Convert.ToInt32(ds.Tables[0].Rows[i]["BoxType"]) == 0)
{
radioButton1.Visible = true;
radioButton2.Visible = true;
radioButton3.Visible = false;
radioButton4.Visible = false;
label7.Visible = false;
label8.Visible = false;
label5.Text = dt.Rows[i]["Option1"].ToString();
label6.Text = dt.Rows[i]["Option2"].ToString();
}
else if (Convert.ToInt32(ds.Tables[0].Rows[i]["BoxType"]) == 1)
{
radioButton1.Visible = true;
radioButton2.Visible = true;
radioButton3.Visible = true;
radioButton4.Visible = true;
}
}
con.Close();
}

how to use repeater iteratively?

I have one repeater which displays the list of puja.i have also used one datalist to display the names of temples.whenever i click on search it displays only the last value of the repeater i.e it is taking only the last value of the repeater....my question is how to use loop inside a repeater???
here is my code behind how i used datalist and repeater:
protected void Page_Load(object sender, EventArgs e)
{
//lblnodatafound.Visible = true;
//lbldatafound.Visible = false;
if (Request.QueryString["search"] != null)
{
var dt = new DataTable("Data");
String source = Request.QueryString["search"];
var splitseparator = new string[] { " " };
String[] result = source.Split(splitseparator, StringSplitOptions.RemoveEmptyEntries);
foreach (String s in result)
{
if (IsAlphaNumeric(s) == true)
{
var dttemp = new DataTable();
dttemp = fnsearch(s);
dt.Merge(dttemp, true);
}
}
if (dt.Rows.Count != 0)
{
int count = dt.Rows.Count;
if (dt.Rows.Count > 0)
{
DataList1.DataSource = dt;
DataList1.DataBind();
lblnodatafound.Visible = false;
lbldatafound.Visible = true;
//added the repeater to display the list of puja
for (int i = 0; i < dt.Rows.Count; i++)
{
String id = dt.Rows[i]["id"].ToString();
string query = "select puja.id,puja.name as puja_name, mandir.name as mandir_name from puja,mandir where mandir.id= puja.with_mandir and puja.with_mandir = '" + id + "'";
conn.Open();
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataTable dt1 = new DataTable();
adp.Fill(dt1);
conn.Close();
if (dt1.Rows.Count > 0)
{
lblmandirpuja.Text = "Poja in " + dt1.Rows[0]["mandir_name"];
foreach (RepeaterItem repeatItem in Repeater1.Items){
Repeater1.DataSource = dt1;
Repeater1.DataBind();
}
}
}
}
}
else
{
lblnodatafound.Visible = true;
lbldatafound.Visible=false;
}
}
}
Try to change this line:
if (dt1.Rows.Count > 0)
for something like:
for(int i = 0; i < dt1.Rows.Count; i++)
And this one:
lblmandirpuja.Text = "Poja in " + dt1.Rows[0]["mandir_name"];
The 0 for the i:
lblmandirpuja.Text = "Poja in " + dt1.Rows[i]["mandir_name"];

no row at position 0

I have the following code snippet:
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
DataRow dr = dt.Rows[0];
if (dt.Rows.Count > 0)
{
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}
But I'm getting an error as:
There is no row at position 0.
I have the same query in sql server, but my table has contents for this query.
You are not loading data in to the DataSet. You have to call SqlDataAdapter.Fill to load the data in the DataSet. Also assign the row in the condition where you check that Rows count is greater then zero for not getting exception when not row exists.
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
adap.Fill(ds);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}
Please check your updated code below
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}

Categories

Resources